130215 {
130216using ::std::basic_stringstream;
130217using ::std::stringstream;
130218using ::std::wstringstream;
130219}
130220
130221#include <string>
130222#include <locale>
130223
130224namespace duckdb {
130225using std::string;
130226}
130227
130228namespace duckdb {
130229
130230template <class charT, class traits = std::char_traits<charT>, class Allocator = std::allocator<charT>>
130231class basic_stringstream : public duckdb_base_std::basic_stringstream<charT, traits, Allocator> {
130232public:
130233 using original = duckdb_base_std::basic_stringstream<charT, traits, Allocator>;
130234
130235 explicit basic_stringstream(std::ios_base::openmode which = std::ios_base::out | std::ios_base::in)
130236 : original(which) {
130237 this->imbue(std::locale::classic());
130238 }
130239 explicit basic_stringstream(const std::basic_string<charT, traits, Allocator> &s,
130240 std::ios_base::openmode which = std::ios_base::out | std::ios_base::in)
130241 : original(s, which) {
130242 this->imbue(std::locale::classic());
130243 }
130244 basic_stringstream(const basic_stringstream &) = delete;
130245 basic_stringstream(basic_stringstream &&rhs) noexcept;
130246};
130247
130248typedef basic_stringstream<char> stringstream;
130249}
130250
130251
130252
130253
130254
130255
130256
130257
130258
130259
130260
130261#ifndef DUCKDB_API
130262#if defined(_WIN32) && !defined(__MINGW32__)
130263#ifdef DUCKDB_STATIC_BUILD
130264#define DUCKDB_API
130265#else
130266#if defined(DUCKDB_BUILD_LIBRARY) && !defined(DUCKDB_BUILD_LOADABLE_EXTENSION)
130267#define DUCKDB_API __declspec(dllexport)
130268#else
130269#define DUCKDB_API __declspec(dllimport)
130270#endif
130271#endif
130272#else
130273#define DUCKDB_API
130274#endif
130275#endif
130276
130277#ifndef DUCKDB_EXTENSION_API
130278#ifdef _WIN32
130279#ifdef DUCKDB_STATIC_BUILD
130280#define DUCKDB_EXTENSION_API
130281#else
130282#define DUCKDB_EXTENSION_API __declspec(dllexport)
130283#endif
130284#else
130285#define DUCKDB_EXTENSION_API __attribute__((visibility("default")))
130286#endif
130287#endif
130288
130289
130290
130291
130292
130293
130294
130295
130296
130297
130298
130299
130300
130301
130302
130303
130304
130305
130306
130307
130308
130309
130310
130311
130312
130313
130314
130315#if ( \
130316 \
130317 !defined(DEBUG) && \
130318 \
130319 !defined(DUCKDB_FORCE_ASSERT) && \
130320 \
130321 !defined(__MVS__) \
130322)
130323
130324
130327#include <assert.h>
130328#define D_ASSERT assert
130329namespace duckdb {
130330DUCKDB_API void DuckDBAssertInternal(bool condition, const char *condition_name, const char *file, int linenr);
130331}
130332
130333#else
130334namespace duckdb {
130335DUCKDB_API void DuckDBAssertInternal(bool condition, const char *condition_name, const char *file, int linenr);
130336}
130337
130338#define D_ASSERT(condition) duckdb::DuckDBAssertInternal(bool(condition), #condition, __FILE__, __LINE__)
130339#define D_ASSERT_IS_ENABLED
130340
130341#endif
130342
130344#define ALWAYS_ASSERT(condition) duckdb::DuckDBAssertInternal(bool(condition), #condition, __FILE__, __LINE__)
130345
130346
130347
130348
130349
130350
130351
130352
130353
130354
130355
130356
130357
130358
130359
130360
130361#include <stdint.h>
130362
130363
130364
130365
130366
130367
130368
130369
130370
130371
130372#include <cstdint>
130373
130374namespace duckdb {
130375
130378
130381
130384
130387typedef data_t *data_ptr_t;
130388typedef const data_t *const_data_ptr_t;
130389
130394
130397
130402
130403template <class SRC>
130404data_ptr_t data_ptr_cast(SRC *src) {
130405 return reinterpret_cast<data_ptr_t>(src);
130406}
130407
130408template <class SRC>
130409const_data_ptr_t const_data_ptr_cast(const SRC *src) {
130410 return reinterpret_cast<const_data_ptr_t>(src);
130411}
130412
130413template <class SRC>
130414char *char_ptr_cast(SRC *src) {
130415 return reinterpret_cast<char *>(src);
130416}
130417
130418template <class SRC>
130419const char *const_char_ptr_cast(const SRC *src) {
130420 return reinterpret_cast<const char *>(src);
130421}
130422
130423template <class SRC>
130424const unsigned char *const_uchar_ptr_cast(const SRC *src) {
130425 return reinterpret_cast<const unsigned char *>(src);
130426}
130427
130428template <class SRC>
130429uintptr_t CastPointerToValue(SRC *src) {
130430 return reinterpret_cast<uintptr_t>(src);
130431}
130432
130433template <class SRC>
130434uint64_t cast_pointer_to_uint64(SRC *src) {
130435 return static_cast<uint64_t>(
reinterpret_cast<uintptr_t
>(src));
130436}
130437
130438template <class SRC = data_t>
130439SRC *cast_uint64_to_pointer(uint64_t value) {
130440 return reinterpret_cast<SRC *>(static_cast<uintptr_t>(value));
130441}
130442
130443}
130444
130445
130446namespace duckdb {
130447
130448
130449struct uhugeint_t;
130450
130451struct hugeint_t {
130452public:
130455
130456public:
130457 hugeint_t() = default;
130458 DUCKDB_API hugeint_t(int64_t value);
130459 constexpr hugeint_t(int64_t upper, uint64_t lower) : lower(lower), upper(upper) {
130460 }
130461 constexpr hugeint_t(const hugeint_t &rhs) = default;
130462 constexpr hugeint_t(hugeint_t &&rhs) = default;
130463 hugeint_t &
operator=(
const hugeint_t &rhs) =
default;
130464 hugeint_t &
operator=(hugeint_t &&rhs) =
default;
130465
130466 DUCKDB_API string ToString() const;
130467
130468
130469 DUCKDB_API
bool operator==(
const hugeint_t &rhs)
const;
130470 DUCKDB_API
bool operator!=(
const hugeint_t &rhs)
const;
130471 DUCKDB_API
bool operator<=(
const hugeint_t &rhs)
const;
130472 DUCKDB_API
bool operator<(
const hugeint_t &rhs)
const;
130473 DUCKDB_API
bool operator>(
const hugeint_t &rhs)
const;
130474 DUCKDB_API
bool operator>=(
const hugeint_t &rhs)
const;
130475
130476
130477 DUCKDB_API hugeint_t
operator+(
const hugeint_t &rhs)
const;
130478 DUCKDB_API hugeint_t
operator-(
const hugeint_t &rhs)
const;
130479 DUCKDB_API hugeint_t
operator*(
const hugeint_t &rhs)
const;
130480 DUCKDB_API hugeint_t
operator/(
const hugeint_t &rhs)
const;
130481 DUCKDB_API hugeint_t
operator%(
const hugeint_t &rhs)
const;
130482 DUCKDB_API hugeint_t
operator-()
const;
130483
130484
130485 DUCKDB_API hugeint_t
operator>>(
const hugeint_t &rhs)
const;
130486 DUCKDB_API hugeint_t
operator<<(
const hugeint_t &rhs)
const;
130487 DUCKDB_API hugeint_t
operator&(
const hugeint_t &rhs)
const;
130488 DUCKDB_API hugeint_t
operator|(
const hugeint_t &rhs)
const;
130489 DUCKDB_API hugeint_t
operator^(
const hugeint_t &rhs)
const;
130490 DUCKDB_API hugeint_t
operator~()
const;
130491
130492
130493 DUCKDB_API hugeint_t &
operator+=(
const hugeint_t &rhs);
130494 DUCKDB_API hugeint_t &
operator-=(
const hugeint_t &rhs);
130495 DUCKDB_API hugeint_t &
operator*=(
const hugeint_t &rhs);
130496 DUCKDB_API hugeint_t &
operator/=(
const hugeint_t &rhs);
130497 DUCKDB_API hugeint_t &
operator%=(
const hugeint_t &rhs);
130498 DUCKDB_API hugeint_t &operator>>=(const hugeint_t &rhs);
130499 DUCKDB_API hugeint_t &operator<<=(const hugeint_t &rhs);
130500 DUCKDB_API hugeint_t &
operator&=(
const hugeint_t &rhs);
130501 DUCKDB_API hugeint_t &
operator|=(
const hugeint_t &rhs);
130502 DUCKDB_API hugeint_t &
operator^=(
const hugeint_t &rhs);
130503
130504
130505 DUCKDB_API explicit operator bool() const;
130507
130508
130509 DUCKDB_API
explicit operator uint8_t()
const;
130510 DUCKDB_API
explicit operator uint16_t()
const;
130511 DUCKDB_API
explicit operator uint32_t()
const;
130512 DUCKDB_API
explicit operator uint64_t()
const;
130513 DUCKDB_API
explicit operator int8_t()
const;
130514 DUCKDB_API
explicit operator int16_t()
const;
130515 DUCKDB_API
explicit operator int32_t()
const;
130516 DUCKDB_API
explicit operator int64_t()
const;
130517 DUCKDB_API explicit operator uhugeint_t() const;
130518};
130519
130520}
130521
130522namespace std {
130523template <>
130524struct hash<duckdb::hugeint_t> {
130525 size_t operator()(
const duckdb::hugeint_t &val)
const {
130526 using std::hash;
130527 return hash<int64_t> {}(val.upper) ^ hash<uint64_t> {}(val.lower);
130528 }
130529};
130530}
130531
130532
130533#include <vector>
130534
130535namespace duckdb {
130536
130538
130539
130540
130541class SQLIdentifier {
130542public:
130543 explicit SQLIdentifier(const string &raw_string) : raw_string(raw_string) {
130544 }
130545
130546public:
130547 string raw_string;
130548};
130549
130550
130551
130552class SQLString {
130553public:
130554 explicit SQLString(const string &raw_string) : raw_string(raw_string) {
130555 }
130556
130557public:
130558 string raw_string;
130559};
130560
130562struct LogicalType;
130563
130564enum class ExceptionFormatValueType :
uint8_t {
130565 FORMAT_VALUE_TYPE_DOUBLE,
130566 FORMAT_VALUE_TYPE_INTEGER,
130567 FORMAT_VALUE_TYPE_STRING
130568};
130569
130570struct ExceptionFormatValue {
130571 DUCKDB_API ExceptionFormatValue(double dbl_val);
130572 DUCKDB_API ExceptionFormatValue(int64_t int_val);
130573 DUCKDB_API ExceptionFormatValue(idx_t uint_val);
130574 DUCKDB_API ExceptionFormatValue(string str_val);
130575 DUCKDB_API ExceptionFormatValue(
const String &str_val);
130576 DUCKDB_API ExceptionFormatValue(hugeint_t hg_val);
130577 DUCKDB_API ExceptionFormatValue(uhugeint_t uhg_val);
130578
130579 ExceptionFormatValueType type;
130580
130581 double dbl_val = 0;
130582 hugeint_t int_val = 0;
130583 string str_val;
130584
130585public:
130586 template <class T>
130587 static ExceptionFormatValue CreateFormatValue(const T &value) {
130589 }
130590 static string Format(const string &msg, std::vector<ExceptionFormatValue> &values);
130591};
130592
130593template <>
130594DUCKDB_API ExceptionFormatValue ExceptionFormatValue::CreateFormatValue(const PhysicalType &value);
130595template <>
130596DUCKDB_API ExceptionFormatValue ExceptionFormatValue::CreateFormatValue(const SQLString &value);
130597template <>
130598DUCKDB_API ExceptionFormatValue ExceptionFormatValue::CreateFormatValue(const SQLIdentifier &value);
130599template <>
130600DUCKDB_API ExceptionFormatValue ExceptionFormatValue::CreateFormatValue(const LogicalType &value);
130601template <>
130602DUCKDB_API ExceptionFormatValue ExceptionFormatValue::CreateFormatValue(const float &value);
130603template <>
130604DUCKDB_API ExceptionFormatValue ExceptionFormatValue::CreateFormatValue(const double &value);
130605template <>
130606DUCKDB_API ExceptionFormatValue ExceptionFormatValue::CreateFormatValue(const string &value);
130607template <>
130608DUCKDB_API ExceptionFormatValue ExceptionFormatValue::CreateFormatValue(
const String &value);
130609template <>
130610DUCKDB_API ExceptionFormatValue ExceptionFormatValue::CreateFormatValue(const char *const &value);
130611template <>
130612DUCKDB_API ExceptionFormatValue ExceptionFormatValue::CreateFormatValue(char *const &value);
130613template <>
130614DUCKDB_API ExceptionFormatValue ExceptionFormatValue::CreateFormatValue(const idx_t &value);
130615template <>
130616DUCKDB_API ExceptionFormatValue ExceptionFormatValue::CreateFormatValue(const hugeint_t &value);
130617template <>
130618DUCKDB_API ExceptionFormatValue ExceptionFormatValue::CreateFormatValue(const uhugeint_t &value);
130619
130620}
130621
130622
130623
130624
130625
130626
130627
130628
130629
130630
130631
130632#include <unordered_map>
130633
130634namespace duckdb {
130635using std::unordered_map;
130636}
130637
130638
130639
130640#include <vector>
130641#include <stdexcept>
130642
130643namespace duckdb {
130645struct LogicalType;
130646class Expression;
130647class ParsedExpression;
130648class QueryErrorContext;
130649class TableRef;
130650struct hugeint_t;
130651class optional_idx;
130652
130653inline void AssertRestrictFunction(const void *left_start, const void *left_end, const void *right_start,
130654 const void *right_end, const char *fname, int linenr) {
130655
130656#ifdef DEBUG
130657 if (!(left_end <= right_start || right_end <= left_start)) {
130658 printf(
"ASSERT RESTRICT FAILED: %s:%d\n", fname, linenr);
130659 D_ASSERT(0);
130660 }
130661#endif
130662}
130663
130664#define ASSERT_RESTRICT(left_start, left_end, right_start, right_end) \
130665 AssertRestrictFunction(left_start, left_end, right_start, right_end, __FILE__, __LINE__)
130666
130667
130668
130669
130670
130671enum class ExceptionType :
uint8_t {
130672 INVALID = 0,
130673 OUT_OF_RANGE = 1,
130674 CONVERSION = 2,
130675 UNKNOWN_TYPE = 3,
130676 DECIMAL = 4,
130677 MISMATCH_TYPE = 5,
130678 DIVIDE_BY_ZERO = 6,
130679 OBJECT_SIZE = 7,
130680 INVALID_TYPE = 8,
130681 SERIALIZATION = 9,
130682 TRANSACTION = 10,
130683 NOT_IMPLEMENTED = 11,
130684 EXPRESSION = 12,
130685 CATALOG = 13,
130686 PARSER = 14,
130687 PLANNER = 15,
130688 SCHEDULER = 16,
130689 EXECUTOR = 17,
130690 CONSTRAINT = 18,
130691 INDEX = 19,
130692 STAT = 20,
130693 CONNECTION = 21,
130694 SYNTAX = 22,
130695 SETTINGS = 23,
130696 BINDER = 24,
130697 NETWORK = 25,
130698 OPTIMIZER = 26,
130699 NULL_POINTER = 27,
130700 IO = 28,
130701 INTERRUPT = 29,
130702 FATAL = 30,
130703 INTERNAL = 31,
130704 INVALID_INPUT = 32,
130705 OUT_OF_MEMORY = 33,
130706 PERMISSION = 34,
130707 PARAMETER_NOT_RESOLVED = 35,
130708 PARAMETER_NOT_ALLOWED = 36,
130709 DEPENDENCY = 37,
130710 HTTP = 38,
130711 MISSING_EXTENSION = 39,
130712 AUTOLOAD = 40,
130713 SEQUENCE = 41,
130714 INVALID_CONFIGURATION =
130715 42
130716};
130717
130718class Exception : public std::runtime_error {
130719public:
130720 DUCKDB_API Exception(ExceptionType exception_type, const string &message);
130721
130722 DUCKDB_API Exception(const unordered_map<string, string> &extra_info, ExceptionType exception_type,
130723 const string &message);
130724
130725public:
130726 DUCKDB_API static string ExceptionTypeToString(ExceptionType type);
130727 DUCKDB_API static ExceptionType StringToExceptionType(const string &type);
130728
130729 template <typename... ARGS>
130730 static string ConstructMessage(const string &msg, ARGS const &...params) {
130731 const std::size_t num_args = sizeof...(ARGS);
130732 if (num_args == 0) {
130733 return msg;
130734 }
130735 std::vector<ExceptionFormatValue> values;
130736 return ConstructMessageRecursive(msg, values,
params...);
130737 }
130738
130739 DUCKDB_API static unordered_map<string, string> InitializeExtraInfo(const Expression &expr);
130740 DUCKDB_API static unordered_map<string, string> InitializeExtraInfo(const ParsedExpression &expr);
130741 DUCKDB_API static unordered_map<string, string> InitializeExtraInfo(const QueryErrorContext &error_context);
130742 DUCKDB_API static unordered_map<string, string> InitializeExtraInfo(const TableRef &ref);
130743 DUCKDB_API static unordered_map<string, string> InitializeExtraInfo(optional_idx error_location);
130744 DUCKDB_API static unordered_map<string, string> InitializeExtraInfo(const string &subtype,
130745 optional_idx error_location);
130746
130748 DUCKDB_API static bool IsExecutionError(ExceptionType type);
130749 DUCKDB_API static string ToJSON(ExceptionType type, const string &message);
130750
130751 DUCKDB_API static string ToJSON(const unordered_map<string, string> &extra_info, ExceptionType type,
130752 const string &message);
130753
130754 DUCKDB_API static bool InvalidatesTransaction(ExceptionType exception_type);
130755 DUCKDB_API static bool InvalidatesDatabase(ExceptionType exception_type);
130756
130757 DUCKDB_API static string ConstructMessageRecursive(const string &msg, std::vector<ExceptionFormatValue> &values);
130758
130759 template <class T, typename... ARGS>
130760 static string ConstructMessageRecursive(const string &msg, std::vector<ExceptionFormatValue> &values,
130761 const T ¶m, ARGS &&...params) {
130762 values.push_back(ExceptionFormatValue::CreateFormatValue<T>(param));
130763 return ConstructMessageRecursive(msg, values,
params...);
130764 }
130765
130766 DUCKDB_API static bool UncaughtException();
130767
130768 DUCKDB_API static string GetStackTrace(idx_t max_depth = 120);
130769 static string FormatStackTrace(const string &message = "") {
130770 return (message + "\n" + GetStackTrace());
130771 }
130772
130773 DUCKDB_API static void SetQueryLocation(optional_idx error_location, unordered_map<string, string> &extra_info);
130774};
130775
130776
130777
130778
130779class ConnectionException : public Exception {
130780public:
130781 DUCKDB_API explicit ConnectionException(const string &msg);
130782
130783 template <typename... ARGS>
130784 explicit ConnectionException(const string &msg, ARGS &&...params)
130785 : ConnectionException(ConstructMessage(msg, std::forward<ARGS>(
params)...)) {
130786 }
130787};
130788
130789class PermissionException : public Exception {
130790public:
130791 DUCKDB_API explicit PermissionException(const string &msg);
130792
130793 template <typename... ARGS>
130794 explicit PermissionException(const string &msg, ARGS &&...params)
130795 : PermissionException(ConstructMessage(msg, std::forward<ARGS>(
params)...)) {
130796 }
130797};
130798
130799class OutOfRangeException : public Exception {
130800public:
130801 DUCKDB_API explicit OutOfRangeException(const string &msg);
130802
130803 template <typename... ARGS>
130804 explicit OutOfRangeException(const string &msg, ARGS &&...params)
130805 : OutOfRangeException(ConstructMessage(msg, std::forward<ARGS>(
params)...)) {
130806 }
130807 DUCKDB_API OutOfRangeException(const int64_t value, const PhysicalType orig_type, const PhysicalType new_type);
130808 DUCKDB_API OutOfRangeException(const hugeint_t value, const PhysicalType orig_type, const PhysicalType new_type);
130809 DUCKDB_API OutOfRangeException(const double value, const PhysicalType orig_type, const PhysicalType new_type);
130810 DUCKDB_API OutOfRangeException(const PhysicalType var_type, const idx_t length);
130811};
130812
130813class OutOfMemoryException : public Exception {
130814public:
130815 DUCKDB_API explicit OutOfMemoryException(const string &msg);
130816
130817 template <typename... ARGS>
130818 explicit OutOfMemoryException(const string &msg, ARGS &&...params)
130819 : OutOfMemoryException(ConstructMessage(msg, std::forward<ARGS>(
params)...)) {
130820 }
130821
130822private:
130823 string ExtendOutOfMemoryError(const string &msg);
130824};
130825
130826class SyntaxException : public Exception {
130827public:
130828 DUCKDB_API explicit SyntaxException(const string &msg);
130829
130830 template <typename... ARGS>
130831 explicit SyntaxException(const string &msg, ARGS &&...params)
130832 : SyntaxException(ConstructMessage(msg, std::forward<ARGS>(
params)...)) {
130833 }
130834};
130835
130836class ConstraintException : public Exception {
130837public:
130838 DUCKDB_API explicit ConstraintException(const string &msg);
130839
130840 template <typename... ARGS>
130841 explicit ConstraintException(const string &msg, ARGS &&...params)
130842 : ConstraintException(ConstructMessage(msg, std::forward<ARGS>(
params)...)) {
130843 }
130844};
130845
130846class DependencyException : public Exception {
130847public:
130848 DUCKDB_API explicit DependencyException(const string &msg);
130849
130850 template <typename... ARGS>
130851 explicit DependencyException(const string &msg, ARGS &&...params)
130852 : DependencyException(ConstructMessage(msg, std::forward<ARGS>(
params)...)) {
130853 }
130854};
130855
130856class IOException : public Exception {
130857public:
130858 DUCKDB_API explicit IOException(const string &msg);
130859
130860 DUCKDB_API explicit IOException(const unordered_map<string, string> &extra_info, const string &msg);
130861 explicit IOException(ExceptionType exception_type, const string &msg) : Exception(exception_type, msg) {
130862 }
130863
130864 template <typename... ARGS>
130865 explicit IOException(const string &msg, ARGS &&...params)
130866 : IOException(ConstructMessage(msg, std::forward<ARGS>(
params)...)) {
130867 }
130868
130869 template <typename... ARGS>
130870 explicit IOException(const unordered_map<string, string> &extra_info, const string &msg, ARGS &&...params)
130871 : IOException(extra_info, ConstructMessage(msg, std::forward<ARGS>(
params)...)) {
130872 }
130873};
130874
130875class MissingExtensionException : public Exception {
130876public:
130877 DUCKDB_API explicit MissingExtensionException(const string &msg);
130878
130879 template <typename... ARGS>
130880 explicit MissingExtensionException(const string &msg, ARGS &&...params)
130881 : MissingExtensionException(ConstructMessage(msg, std::forward<ARGS>(
params)...)) {
130882 }
130883};
130884
130885class NotImplementedException : public Exception {
130886public:
130887 DUCKDB_API explicit NotImplementedException(const string &msg);
130888 explicit NotImplementedException(const unordered_map<string, string> &extra_info, const string &msg);
130889
130890 template <typename... ARGS>
130891 explicit NotImplementedException(const string &msg, ARGS &&...params)
130892 : NotImplementedException(ConstructMessage(msg, std::forward<ARGS>(
params)...)) {
130893 }
130894 template <typename... ARGS>
130895 explicit NotImplementedException(const unordered_map<string, string> &extra_info, const string &msg,
130896 ARGS &&...params)
130897 : NotImplementedException(extra_info, ConstructMessage(msg, std::forward<ARGS>(
params)...)) {
130898 }
130899};
130900
130901class AutoloadException : public Exception {
130902public:
130903 DUCKDB_API explicit AutoloadException(const string &extension_name, const string &message);
130904};
130905
130906class SerializationException : public Exception {
130907public:
130908 DUCKDB_API explicit SerializationException(const string &msg);
130909
130910 template <typename... ARGS>
130911 explicit SerializationException(const string &msg, ARGS &&...params)
130912 : SerializationException(ConstructMessage(msg, std::forward<ARGS>(
params)...)) {
130913 }
130914};
130915
130916class SequenceException : public Exception {
130917public:
130918 DUCKDB_API explicit SequenceException(const string &msg);
130919
130920 template <typename... ARGS>
130921 explicit SequenceException(const string &msg, ARGS &&...params)
130922 : SequenceException(ConstructMessage(msg, std::forward<ARGS>(
params)...)) {
130923 }
130924};
130925
130926class InterruptException : public Exception {
130927public:
130928 static constexpr const char *INTERRUPT_MESSAGE = "Interrupted!";
130929 DUCKDB_API InterruptException();
130930};
130931
130932class FatalException : public Exception {
130933public:
130934 explicit FatalException(const string &msg) : FatalException(ExceptionType::FATAL, msg) {
130935 }
130936 template <typename... ARGS>
130937 explicit FatalException(const string &msg, ARGS &&...params)
130938 : FatalException(ConstructMessage(msg, std::forward<ARGS>(
params)...)) {
130939 }
130940
130941protected:
130942 DUCKDB_API explicit FatalException(ExceptionType type, const string &msg);
130943 template <typename... ARGS>
130944 explicit FatalException(ExceptionType type, const string &msg, ARGS &&...params)
130945 : FatalException(type, ConstructMessage(msg, std::forward<ARGS>(
params)...)) {
130946 }
130947};
130948
130949class InternalException : public Exception {
130950public:
130951 DUCKDB_API explicit InternalException(const string &msg);
130952 InternalException(const unordered_map<string, string> &extra_info, const string &msg);
130953
130954 template <typename... ARGS>
130955 explicit InternalException(const string &msg, ARGS &&...params)
130956 : InternalException(ConstructMessage(msg, std::forward<ARGS>(
params)...)) {
130957 }
130958
130959 template <typename... ARGS>
130960 explicit InternalException(const unordered_map<string, string> &extra_info, const string &msg, ARGS &&...params)
130961 : InternalException(extra_info, ConstructMessage(msg, std::forward<ARGS>(
params)...)) {
130962 }
130963};
130964
130965class InvalidInputException : public Exception {
130966public:
130967 DUCKDB_API explicit InvalidInputException(const string &msg);
130968 DUCKDB_API explicit InvalidInputException(const unordered_map<string, string> &extra_info, const string &msg);
130969
130970 template <typename... ARGS>
130971 explicit InvalidInputException(const string &msg, ARGS &&...params)
130972 : InvalidInputException(ConstructMessage(msg, std::forward<ARGS>(
params)...)) {
130973 }
130974
130975 template <typename... ARGS>
130976 explicit InvalidInputException(const Expression &expr, const string &msg, ARGS &&...params)
130977 : InvalidInputException(Exception::InitializeExtraInfo(expr),
130978 ConstructMessage(msg, std::forward<ARGS>(
params)...)) {
130979 }
130980};
130981
130982class ExecutorException : public Exception {
130983public:
130984 DUCKDB_API explicit ExecutorException(const string &msg);
130985
130986 template <typename... ARGS>
130987 explicit ExecutorException(const string &msg, ARGS &&...params)
130988 : ExecutorException(ConstructMessage(msg, std::forward<ARGS>(
params)...)) {
130989 }
130990};
130991
130992class InvalidConfigurationException : public Exception {
130993public:
130994 DUCKDB_API explicit InvalidConfigurationException(const string &msg);
130995
130996 DUCKDB_API explicit InvalidConfigurationException(const unordered_map<string, string> &extra_info,
130997 const string &msg);
130998
130999 template <typename... ARGS>
131000 explicit InvalidConfigurationException(const string &msg, ARGS &&...params)
131001 : InvalidConfigurationException(ConstructMessage(msg, std::forward<ARGS>(
params)...)) {
131002 }
131003 template <typename... ARGS>
131004 explicit InvalidConfigurationException(const Expression &expr, const string &msg, ARGS &&...params)
131005 : InvalidConfigurationException(ConstructMessage(msg, std::forward<ARGS>(
params)...),
131006 Exception::InitializeExtraInfo(expr)) {
131007 }
131008};
131009
131010class InvalidTypeException : public Exception {
131011public:
131012 DUCKDB_API InvalidTypeException(PhysicalType type, const string &msg);
131013 DUCKDB_API InvalidTypeException(const LogicalType &type, const string &msg);
131014 DUCKDB_API explicit InvalidTypeException(const string &msg);
131015};
131016
131017class TypeMismatchException : public Exception {
131018public:
131019 DUCKDB_API TypeMismatchException(const PhysicalType type_1, const PhysicalType type_2, const string &msg);
131020 DUCKDB_API TypeMismatchException(const LogicalType &type_1, const LogicalType &type_2, const string &msg);
131021 DUCKDB_API TypeMismatchException(optional_idx error_location, const LogicalType &type_1, const LogicalType &type_2,
131022 const string &msg);
131023 DUCKDB_API explicit TypeMismatchException(const string &msg);
131024};
131025
131026class ParameterNotAllowedException : public Exception {
131027public:
131028 DUCKDB_API explicit ParameterNotAllowedException(const string &msg);
131029
131030 template <typename... ARGS>
131031 explicit ParameterNotAllowedException(const string &msg, ARGS &&...params)
131032 : ParameterNotAllowedException(ConstructMessage(msg, std::forward<ARGS>(
params)...)) {
131033 }
131034};
131035
131039class ParameterNotResolvedException : public Exception {
131040public:
131041 DUCKDB_API explicit ParameterNotResolvedException();
131042};
131043
131044}
131045
131046
131047
131048
131049
131050
131051
131052
131053
131054
131055
131056#if __GNUC__
131057#define DUCKDB_BUILTIN_EXPECT(cond, expected_value) (__builtin_expect(cond, expected_value))
131058#else
131059#define DUCKDB_BUILTIN_EXPECT(cond, expected_value) (cond)
131060#endif
131061
131062#define DUCKDB_LIKELY(...) DUCKDB_BUILTIN_EXPECT((__VA_ARGS__), 1)
131063#define DUCKDB_UNLIKELY(...) DUCKDB_BUILTIN_EXPECT((__VA_ARGS__), 0)
131064
131065
131066
131067namespace duckdb {
131068
131069template <bool IS_ENABLED>
131070struct MemorySafety {
131071#ifdef DEBUG
131072
131073 static constexpr bool ENABLED = true;
131074#else
131075 static constexpr bool ENABLED = IS_ENABLED;
131076#endif
131077};
131078
131079}
131080
131081
131082
131083#include <memory>
131084
131085#define DUCKDB_BASE_STD
131086
131087namespace duckdb_base_std {
131088using ::std::make_shared;
131089using ::std::shared_ptr;
131090using ::std::unique_ptr;
131091
131092}
131093
131094
131095#include <type_traits>
131096
131097namespace duckdb {
131098
131099template <class DATA_TYPE, class DELETER = std::default_delete<DATA_TYPE>, bool SAFE = true>
131100class unique_ptr : public duckdb_base_std::unique_ptr<DATA_TYPE, DELETER> {
131101public:
131102 using original = duckdb_base_std::unique_ptr<DATA_TYPE, DELETER>;
131103 using original::original;
131104 using pointer = typename original::pointer;
131105
131106private:
131107 static inline void AssertNotNull(const bool null) {
131108#if defined(DUCKDB_DEBUG_NO_SAFETY) || defined(DUCKDB_CLANG_TIDY)
131109 return;
131110#else
131111 if (DUCKDB_UNLIKELY(null)) {
131112 throw duckdb::InternalException("Attempted to dereference unique_ptr that is NULL!");
131113 }
131114#endif
131115 }
131116
131117public:
131118 typename std::add_lvalue_reference<DATA_TYPE>::type
operator*()
const {
131119 const auto ptr = original::get();
131120 if (MemorySafety<SAFE>::ENABLED) {
131121 AssertNotNull(!ptr);
131122 }
131123 return *ptr;
131124 }
131125
131126 typename original::pointer operator->() const {
131127 const auto ptr = original::get();
131128 if (MemorySafety<SAFE>::ENABLED) {
131129 AssertNotNull(!ptr);
131130 }
131131 return ptr;
131132 }
131133
131134#ifdef DUCKDB_CLANG_TIDY
131135
131136 [[clang::reinitializes]]
131137#endif
131138 inline void
131139 reset(typename original::pointer ptr = typename original::pointer()) noexcept {
131140 original::reset(ptr);
131141 }
131142};
131143
131144template <class DATA_TYPE, class DELETER>
131145class unique_ptr<DATA_TYPE[], DELETER, true> : public duckdb_base_std::unique_ptr<DATA_TYPE[], DELETER> {
131146public:
131147 using original = duckdb_base_std::unique_ptr<DATA_TYPE[], DELETER>;
131148 using original::original;
131149
131150private:
131151 static inline void AssertNotNull(const bool null) {
131152#if defined(DUCKDB_DEBUG_NO_SAFETY) || defined(DUCKDB_CLANG_TIDY)
131153 return;
131154#else
131155 if (DUCKDB_UNLIKELY(null)) {
131156 throw duckdb::InternalException("Attempted to dereference unique_ptr that is NULL!");
131157 }
131158#endif
131159 }
131160
131161public:
131162 typename std::add_lvalue_reference<DATA_TYPE>::type operator[](size_t __i) const {
131163 const auto ptr = original::get();
131164 if (MemorySafety<true>::ENABLED) {
131165 AssertNotNull(!ptr);
131166 }
131167 return ptr[__i];
131168 }
131169};
131170
131171template <class DATA_TYPE, class DELETER, bool SAFE>
131172class unique_ptr<DATA_TYPE[], DELETER, SAFE> : public duckdb_base_std::unique_ptr<DATA_TYPE[], DELETER> {
131173public:
131174 using original = duckdb_base_std::unique_ptr<DATA_TYPE[], DELETER>;
131175 using original::original;
131176
131177private:
131178 static inline void AssertNotNull(const bool null) {
131179#if defined(DUCKDB_DEBUG_NO_SAFETY) || defined(DUCKDB_CLANG_TIDY)
131180 return;
131181#else
131182 if (DUCKDB_UNLIKELY(null)) {
131183 throw duckdb::InternalException("Attempted to dereference unique_ptr that is NULL!");
131184 }
131185#endif
131186 }
131187
131188public:
131189 typename std::add_lvalue_reference<DATA_TYPE>::type operator[](size_t __i) const {
131190 const auto ptr = original::get();
131191 if (MemorySafety<SAFE>::ENABLED) {
131192 AssertNotNull(!ptr);
131193 }
131194 return ptr[__i];
131195 }
131196};
131197
131198template <typename T>
131199using unique_array = unique_ptr<T[], std::default_delete<T[]>, true>;
131200
131201template <typename T>
131202using unsafe_unique_array = unique_ptr<T[], std::default_delete<T[]>, false>;
131203
131204template <typename T>
131205using unsafe_unique_ptr = unique_ptr<T, std::default_delete<T>, false>;
131206
131207}
131208
131209
131210
131211namespace duckdb {
131212class Serializer;
131213class Deserializer;
131214class BinarySerializer;
131215class BinaryDeserializer;
131216class WriteStream;
131217class ReadStream;
131218
131220#ifndef DUCKDB_DEBUG_MOVE
131221using std::move;
131222#endif
131223
131224
131225#define DEFAULT_SCHEMA "main"
131226#define INVALID_SCHEMA ""
131227#define INVALID_CATALOG ""
131228#define SYSTEM_CATALOG "system"
131229#define TEMP_CATALOG "temp"
131230#define IN_MEMORY_PATH ":memory:"
131231
131232DUCKDB_API bool IsInvalidSchema(const string &str);
131233DUCKDB_API bool IsInvalidCatalog(const string &str);
131234
131239DUCKDB_API
extern const column_t VIRTUAL_COLUMN_START;
131240DUCKDB_API bool IsRowIdColumnId(column_t column_id);
131241DUCKDB_API bool IsVirtualColumn(column_t column_id);
131242
131247
131252
131253extern const double PI;
131254
131255struct DConstants {
131257 static constexpr const idx_t INVALID_INDEX =
idx_t(-1);
131259 static constexpr const idx_t MAX_VECTOR_SIZE = 1ULL << 37ULL;
131260};
131261
131262struct LogicalIndex {
131263 explicit LogicalIndex(idx_t index) :
index(
index) {
131264 }
131265
131267
131268 inline bool operator==(
const LogicalIndex &rhs)
const {
131269 return index == rhs.index;
131270 };
131271 inline bool operator!=(
const LogicalIndex &rhs)
const {
131272 return index != rhs.index;
131273 };
131274 inline bool operator<(
const LogicalIndex &rhs)
const {
131275 return index < rhs.index;
131276 };
131277 bool IsValid() {
131278 return index != DConstants::INVALID_INDEX;
131279 }
131280};
131281
131282struct PhysicalIndex {
131283 explicit PhysicalIndex(idx_t index) :
index(
index) {
131284 }
131285
131287
131288 inline bool operator==(
const PhysicalIndex &rhs)
const {
131289 return index == rhs.index;
131290 };
131291 inline bool operator!=(
const PhysicalIndex &rhs)
const {
131292 return index != rhs.index;
131293 };
131294 inline bool operator<(
const PhysicalIndex &rhs)
const {
131295 return index < rhs.index;
131296 };
131297 bool IsValid() {
131298 return index != DConstants::INVALID_INDEX;
131299 }
131300};
131301
131302DUCKDB_API
bool IsPowerOfTwo(uint64_t
v);
131303DUCKDB_API
uint64_t NextPowerOfTwo(uint64_t
v);
131304DUCKDB_API
uint64_t PreviousPowerOfTwo(uint64_t
v);
131305
131306}
131307
131308
131309namespace duckdb {
131310
131311enum class ProfilerPrintFormat :
uint8_t { QUERY_TREE, JSON, QUERY_TREE_OPTIMIZER, NO_OUTPUT, HTML, GRAPHVIZ, MERMAID };
131312
131313}
131314
131315
131316
131317
131318
131319
131320
131321
131322
131323
131324
131325
131326
131327
131328
131329
131330
131331
131332
131333
131334
131335
131336
131337
131338
131339
131340
131341
131342
131343
131344
131345
131346
131347
131348
131349
131350
131351
131352
131353
131354
131355
131356
131357
131358
131359
131360
131361
131362
131363
131364
131365
131366
131367
131368
131369
131370
131371
131372
131373
131374
131375
131376
131377
131378
131379
131380
131381
131382
131383
131384
131385
131386
131387
131388
131389
131390
131391#include <stdint.h>
131392
131393namespace duckdb {
131394
131395
131396struct hugeint_t;
131397
131398struct uhugeint_t {
131399public:
131402
131403public:
131404 uhugeint_t() = default;
131405 DUCKDB_API uhugeint_t(uint64_t value);
131406 constexpr uhugeint_t(uint64_t upper, uint64_t lower) : lower(lower), upper(upper) {
131407 }
131408 constexpr uhugeint_t(const uhugeint_t &rhs) = default;
131409 constexpr uhugeint_t(uhugeint_t &&rhs) = default;
131410 uhugeint_t &
operator=(
const uhugeint_t &rhs) =
default;
131411 uhugeint_t &
operator=(uhugeint_t &&rhs) =
default;
131412
131413 DUCKDB_API string ToString() const;
131414
131415
131416 DUCKDB_API
bool operator==(
const uhugeint_t &rhs)
const;
131417 DUCKDB_API
bool operator!=(
const uhugeint_t &rhs)
const;
131418 DUCKDB_API
bool operator<=(
const uhugeint_t &rhs)
const;
131419 DUCKDB_API
bool operator<(
const uhugeint_t &rhs)
const;
131420 DUCKDB_API
bool operator>(
const uhugeint_t &rhs)
const;
131421 DUCKDB_API
bool operator>=(
const uhugeint_t &rhs)
const;
131422
131423
131424 DUCKDB_API uhugeint_t
operator+(
const uhugeint_t &rhs)
const;
131425 DUCKDB_API uhugeint_t
operator-(
const uhugeint_t &rhs)
const;
131426 DUCKDB_API uhugeint_t
operator*(
const uhugeint_t &rhs)
const;
131427 DUCKDB_API uhugeint_t
operator/(
const uhugeint_t &rhs)
const;
131428 DUCKDB_API uhugeint_t
operator%(
const uhugeint_t &rhs)
const;
131429 DUCKDB_API uhugeint_t
operator-()
const;
131430
131431
131432 DUCKDB_API uhugeint_t
operator>>(
const uhugeint_t &rhs)
const;
131433 DUCKDB_API uhugeint_t
operator<<(
const uhugeint_t &rhs)
const;
131434 DUCKDB_API uhugeint_t
operator&(
const uhugeint_t &rhs)
const;
131435 DUCKDB_API uhugeint_t
operator|(
const uhugeint_t &rhs)
const;
131436 DUCKDB_API uhugeint_t
operator^(
const uhugeint_t &rhs)
const;
131437 DUCKDB_API uhugeint_t
operator~()
const;
131438
131439
131440 DUCKDB_API uhugeint_t &
operator+=(
const uhugeint_t &rhs);
131441 DUCKDB_API uhugeint_t &
operator-=(
const uhugeint_t &rhs);
131442 DUCKDB_API uhugeint_t &
operator*=(
const uhugeint_t &rhs);
131443 DUCKDB_API uhugeint_t &
operator/=(
const uhugeint_t &rhs);
131444 DUCKDB_API uhugeint_t &
operator%=(
const uhugeint_t &rhs);
131445 DUCKDB_API uhugeint_t &operator>>=(const uhugeint_t &rhs);
131446 DUCKDB_API uhugeint_t &operator<<=(const uhugeint_t &rhs);
131447 DUCKDB_API uhugeint_t &
operator&=(
const uhugeint_t &rhs);
131448 DUCKDB_API uhugeint_t &
operator|=(
const uhugeint_t &rhs);
131449 DUCKDB_API uhugeint_t &
operator^=(
const uhugeint_t &rhs);
131450
131451
131452 DUCKDB_API explicit operator bool() const;
131454
131455
131456 DUCKDB_API
explicit operator uint8_t()
const;
131457 DUCKDB_API
explicit operator uint16_t()
const;
131458 DUCKDB_API
explicit operator uint32_t()
const;
131459 DUCKDB_API
explicit operator uint64_t()
const;
131460 DUCKDB_API
explicit operator int8_t()
const;
131461 DUCKDB_API
explicit operator int16_t()
const;
131462 DUCKDB_API
explicit operator int32_t()
const;
131463 DUCKDB_API
explicit operator int64_t()
const;
131464 DUCKDB_API operator hugeint_t() const;
131465};
131466
131467}
131468
131469namespace std {
131470template <>
131471struct hash<duckdb::uhugeint_t> {
131472 size_t operator()(
const duckdb::uhugeint_t &val)
const {
131473 using std::hash;
131474 return hash<uint64_t> {}(val.upper) ^ hash<uint64_t> {}(val.lower);
131475 }
131476};
131477}
131478
131479
131480#include <cstring>
131481
131482namespace duckdb {
131483
131484#ifndef DUCKDB_IS_BIG_ENDIAN
131485#if defined(__BYTE_ORDER__) && defined(__ORDER_BIG_ENDIAN__) && __BYTE_ORDER__ == __ORDER_BIG_ENDIAN__
131486#define DUCKDB_IS_BIG_ENDIAN 1
131487#else
131488#define DUCKDB_IS_BIG_ENDIAN 0
131489#endif
131490#endif
131491
131492#if defined(__clang__) || defined(__GNUC__) && (__GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 3))
131493#define BSWAP16(x) __builtin_bswap16(static_cast<uint16_t>(x))
131494#define BSWAP32(x) __builtin_bswap32(static_cast<uint32_t>(x))
131495#define BSWAP64(x) __builtin_bswap64(static_cast<uint64_t>(x))
131496#else
131497#define BSWAP16(x) ((uint16_t)((((uint16_t)(x)&0xff00) >> 8) | (((uint16_t)(x)&0x00ff) << 8)))
131498
131499#define BSWAP32(x) \
131500 ((uint32_t)((((uint32_t)(x)&0xff000000) >> 24) | (((uint32_t)(x)&0x00ff0000) >> 8) | \
131501 (((uint32_t)(x)&0x0000ff00) << 8) | (((uint32_t)(x)&0x000000ff) << 24)))
131502
131503#define BSWAP64(x) \
131504 ((uint64_t)((((uint64_t)(x)&0xff00000000000000ull) >> 56) | (((uint64_t)(x)&0x00ff000000000000ull) >> 40) | \
131505 (((uint64_t)(x)&0x0000ff0000000000ull) >> 24) | (((uint64_t)(x)&0x000000ff00000000ull) >> 8) | \
131506 (((uint64_t)(x)&0x00000000ff000000ull) << 8) | (((uint64_t)(x)&0x0000000000ff0000ull) << 24) | \
131507 (((uint64_t)(x)&0x000000000000ff00ull) << 40) | (((uint64_t)(x)&0x00000000000000ffull) << 56)))
131508#endif
131509
131510static inline int8_t BSwap(
const int8_t &x) {
131511 return x;
131512}
131513
131514static inline uint8_t BSwap(
const uint8_t &x) {
131515 return x;
131516}
131517
131518static inline uint16_t BSwap(
const uint16_t &x) {
131519 return BSWAP16(x);
131520}
131521
131522static inline int16_t BSwap(
const int16_t &x) {
131523 return static_cast<int16_t>(BSWAP16(x));
131524}
131525
131526static inline uint32_t BSwap(
const uint32_t &x) {
131527 return BSWAP32(x);
131528}
131529
131530static inline int32_t BSwap(
const int32_t &x) {
131531 return static_cast<int32_t>(BSWAP32(x));
131532}
131533
131534static inline uint64_t BSwap(
const uint64_t &x) {
131535 return BSWAP64(x);
131536}
131537
131538static inline int64_t BSwap(
const int64_t &x) {
131539 return static_cast<int64_t>(BSWAP64(x));
131540}
131541
131542static inline uhugeint_t BSwap(const uhugeint_t &x) {
131543 return uhugeint_t(BSWAP64(x.upper), BSWAP64(x.lower));
131544}
131545
131546static inline hugeint_t BSwap(const hugeint_t &x) {
131547 return hugeint_t(
static_cast<int64_t>(BSWAP64(x.upper)), BSWAP64(x.lower));
131548}
131549
131550static inline float BSwap(const float &x) {
131552 std::memcpy(&temp, &x, sizeof(temp));
131553 temp = BSWAP32(temp);
131554 float result;
131555 std::memcpy(&result, &temp, sizeof(result));
131556 return result;
131557}
131558
131559static inline double BSwap(const double &x) {
131561 std::memcpy(&temp, &x, sizeof(temp));
131562 temp = BSWAP64(temp);
131563 double result;
131564 std::memcpy(&result, &temp, sizeof(result));
131565 return result;
131566}
131567
131568template <class T>
131569static inline T BSwapIfLE(const T &x) {
131570#if DUCKDB_IS_BIG_ENDIAN
131571 return x;
131572#else
131573 return BSwap(x);
131574#endif
131575}
131576
131577template <class T>
131578static inline T BSwapIfBE(const T &x) {
131579#if DUCKDB_IS_BIG_ENDIAN
131580 return BSwap(x);
131581#else
131582 return x;
131583#endif
131584}
131585
131586}
131587
131588
131589
131590
131591
131592
131593
131594
131595
131596
131597
131598
131599
131600
131601
131602
131603
131604
131605#include <memory>
131606#include <type_traits>
131607
131608namespace duckdb {
131609
131610
131611
131612
131613
131614#if _LIBCPP_STD_VER >= 17
131615template <class U, class T>
131616struct __bounded_convertible_to_unbounded : std::false_type {};
131617
131618template <class _Up, std::size_t _Np, class T>
131619struct __bounded_convertible_to_unbounded<_Up[_Np], T> : std::is_same<std::remove_cv<T>, _Up[]> {};
131620
131621template <class U, class T>
131622struct compatible_with_t : std::_Or<std::is_convertible<U *, T *>, __bounded_convertible_to_unbounded<U, T>> {};
131623#else
131624template <class U, class T>
131625struct compatible_with_t : std::is_convertible<U *, T *> {};
131626#endif
131627
131628}
131629
131630
131631
131632
131633
131634namespace duckdb {
131635
131636template <typename T, bool SAFE = true>
131637class weak_ptr;
131638
131639template <class T>
131640class enable_shared_from_this;
131641
131642template <typename T, bool SAFE = true>
131643class shared_ptr {
131644public:
131645 using original = std::shared_ptr<T>;
131646 using element_type = typename original::element_type;
131647 using weak_type = weak_ptr<T, SAFE>;
131648
131649private:
131650 static inline void AssertNotNull(const bool null) {
131651#if defined(DUCKDB_DEBUG_NO_SAFETY) || defined(DUCKDB_CLANG_TIDY)
131652 return;
131653#else
131654 if (DUCKDB_UNLIKELY(null)) {
131655 throw duckdb::InternalException("Attempted to dereference shared_ptr that is NULL!");
131656 }
131657#endif
131658 }
131659
131660private:
131661 template <class U, bool SAFE_P>
131662 friend class weak_ptr;
131663
131664 template <class U, bool SAFE_P>
131665 friend class shared_ptr;
131666
131667 template <typename U, typename S>
131668 friend shared_ptr<S> shared_ptr_cast(shared_ptr<U> src);
131669
131670private:
131671 original internal;
131672
131673public:
131674
131675 shared_ptr() : internal() {
131676 }
131677 shared_ptr(std::nullptr_t) : internal(nullptr) {
131678 }
131679
131680
131681 template <class U, typename std::enable_if<compatible_with_t<U, T>::value, int>::type = 0>
131682 explicit shared_ptr(U *ptr) : internal(ptr) {
131683 __enable_weak_this(internal.get(), internal.get());
131684 }
131685
131686 template <typename DELETER>
131687 shared_ptr(T *ptr, DELETER deleter) : internal(ptr, deleter) {
131688 __enable_weak_this(internal.get(), internal.get());
131689 }
131690
131691
131692 template <class U>
131693 shared_ptr(const shared_ptr<U> &ref, T *ptr) noexcept : internal(ref.internal, ptr) {
131694 }
131695#if _LIBCPP_STD_VER >= 20
131696 template <class U>
131697 shared_ptr(shared_ptr<U> &&ref, T *ptr) noexcept : internal(std::move(ref.internal), ptr) {
131698 }
131699#endif
131700
131701
131702 template <class U, typename std::enable_if<compatible_with_t<U, T>::value, int>::type = 0>
131703 shared_ptr(const shared_ptr<U> &ref) noexcept : internal(ref.internal) {
131704 }
131705 shared_ptr(const shared_ptr &other) : internal(other.internal) {
131706 }
131707
131708 template <class U, typename std::enable_if<compatible_with_t<U, T>::value, int>::type = 0>
131709#ifdef DUCKDB_CLANG_TIDY
131710 [[clang::reinitializes]]
131711#endif
131712 shared_ptr(shared_ptr<U> &&ref) noexcept
131713 : internal(std::move(ref.internal)) {
131714 }
131715
131716#ifdef DUCKDB_CLANG_TIDY
131717 [[clang::reinitializes]]
131718#endif
131719 shared_ptr(shared_ptr<T, SAFE> &&other) noexcept
131720 : internal(std::move(other.internal)) {
131721 }
131722
131723
131724 explicit shared_ptr(std::shared_ptr<T> other) : internal(other) {
131725
131726
131727 __enable_weak_this(internal.get(), internal.get());
131728 }
131729
131730
131731 template <class U>
131732 explicit shared_ptr(weak_ptr<U> other) : internal(other.internal) {
131733 }
131734
131735
131736 template <class U, class DELETER, bool SAFE_P,
131737 typename std::enable_if<compatible_with_t<U, T>::value &&
131738 std::is_convertible<typename unique_ptr<U, DELETER>::pointer, T *>::value,
131739 int>::type = 0>
131740#ifdef DUCKDB_CLANG_TIDY
131741 [[clang::reinitializes]]
131742#endif
131743 shared_ptr(unique_ptr<U, DELETER, SAFE_P> &&other)
131744 : internal(std::move(other)) {
131745 __enable_weak_this(internal.get(), internal.get());
131746 }
131747
131748
131749 ~shared_ptr() = default;
131750
131751
131752 shared_ptr<T, SAFE> &
operator=(
const shared_ptr<T, SAFE> &other)
noexcept {
131753 if (this == &other) {
131754 return *this;
131755 }
131756
131757 shared_ptr(other).swap(*this);
131758 return *this;
131759 }
131760 template <class U, typename std::enable_if<compatible_with_t<U, T>::value, int>::type = 0>
131761 shared_ptr<T> &
operator=(
const shared_ptr<U> &other) {
131762 shared_ptr(other).swap(*this);
131763 return *this;
131764 }
131765
131766
131767 shared_ptr<T, SAFE> &
operator=(shared_ptr &&other)
noexcept {
131768
131769 shared_ptr(std::move(other)).swap(*this);
131770 return *this;
131771 }
131772 template <class U, typename std::enable_if<compatible_with_t<U, T>::value, int>::type = 0>
131773 shared_ptr<T, SAFE> &
operator=(shared_ptr<U> &&other) {
131774 shared_ptr(std::move(other)).swap(*this);
131775 return *this;
131776 }
131777
131778
131779 template <class U, class DELETER, bool SAFE_P,
131780 typename std::enable_if<compatible_with_t<U, T>::value &&
131781 std::is_convertible<typename unique_ptr<U, DELETER>::pointer, T *>::value,
131782 int>::type = 0>
131783 shared_ptr<T, SAFE> &
operator=(unique_ptr<U, DELETER, SAFE_P> &&ref) {
131784 shared_ptr(std::move(ref)).swap(*this);
131785 return *this;
131786 }
131787
131788#ifdef DUCKDB_CLANG_TIDY
131789 [[clang::reinitializes]]
131790#endif
131791 void
131792 reset() {
131793 internal.reset();
131794 }
131795 template <typename U>
131796#ifdef DUCKDB_CLANG_TIDY
131797 [[clang::reinitializes]]
131798#endif
131799 void
131800 reset(U *ptr) {
131801 internal.reset(ptr);
131802 }
131803 template <typename U, typename DELETER>
131804#ifdef DUCKDB_CLANG_TIDY
131805 [[clang::reinitializes]]
131806#endif
131807 void
131808 reset(U *ptr, DELETER deleter) {
131809 internal.reset(ptr, deleter);
131810 }
131811
131812 void swap(shared_ptr &r)
noexcept {
131813 internal.swap(r.internal);
131814 }
131815
131817 return internal.get();
131818 }
131819
131820 long use_count() const {
131821 return internal.use_count();
131822 }
131823
131824 explicit operator bool() const noexcept {
131825 return internal.operator bool();
131826 }
131827
131828 typename std::add_lvalue_reference<T>::type
operator*()
const {
131829 if (MemorySafety<SAFE>::ENABLED) {
131830 const auto ptr = internal.get();
131831 AssertNotNull(!ptr);
131832 return *ptr;
131833 } else {
131834 return *internal;
131835 }
131836 }
131837
131838 T *operator->() const {
131839 if (MemorySafety<SAFE>::ENABLED) {
131840 const auto ptr = internal.get();
131841 AssertNotNull(!ptr);
131842 return ptr;
131843 } else {
131844 return internal.operator->();
131845 }
131846 }
131847
131848
131849 template <typename U>
131850 bool operator==(
const shared_ptr<U> &other)
const noexcept {
131851 return internal == other.internal;
131852 }
131853 template <typename U>
131854 bool operator!=(
const shared_ptr<U> &other)
const noexcept {
131855 return internal != other.internal;
131856 }
131857
131858 bool operator==(std::nullptr_t)
const noexcept {
131859 return internal == nullptr;
131860 }
131861 bool operator!=(std::nullptr_t)
const noexcept {
131862 return internal != nullptr;
131863 }
131864
131865 template <typename U>
131866 bool operator<(
const shared_ptr<U> &other)
const noexcept {
131867 return internal < other.internal;
131868 }
131869 template <typename U>
131870 bool operator<=(
const shared_ptr<U> &other)
const noexcept {
131871 return internal <= other.internal;
131872 }
131873 template <typename U>
131874 bool operator>(
const shared_ptr<U> &other)
const noexcept {
131875 return internal > other.internal;
131876 }
131877 template <typename U>
131878 bool operator>=(
const shared_ptr<U> &other)
const noexcept {
131879 return internal >= other.internal;
131880 }
131881
131882 shared_ptr<T, SAFE> atomic_load() const {
131883 return shared_ptr<T, SAFE>(std::atomic_load(&internal));
131884 }
131885
131886 shared_ptr<T, SAFE> atomic_load(std::memory_order order) const {
131887 return shared_ptr<T, SAFE>(std::atomic_load_explicit(&internal, order));
131888 }
131889
131890 void atomic_store(const shared_ptr<T, SAFE> &new_ptr) {
131891 std::atomic_store(&internal, new_ptr.internal);
131892 }
131893
131894private:
131895
131896 template <class U, class V,
131897 typename std::enable_if<std::is_convertible<V *, const enable_shared_from_this<U> *>::value,
131898 int>::type = 0>
131899 void __enable_weak_this(const enable_shared_from_this<U> *object,
131900 V *ptr) noexcept {
131901 typedef typename std::remove_cv<U>::type non_const_u_t;
131902 if (object && object->__weak_this_.expired()) {
131903
131904
131905 auto non_const = const_cast<non_const_u_t *>(static_cast<const U *>(ptr));
131906 object->__weak_this_ = shared_ptr<non_const_u_t>(*this, non_const);
131907 }
131908 }
131909
131910 void __enable_weak_this(...) noexcept {
131911 }
131912};
131913
131914template <typename T>
131915using unsafe_shared_ptr = shared_ptr<T, false>;
131916
131917}
131918
131919
131920
131921
131922
131923namespace duckdb {
131924
131925template <typename T, bool SAFE>
131926class weak_ptr {
131927public:
131928 using original = std::weak_ptr<T>;
131929 using element_type = typename original::element_type;
131930
131931private:
131932 template <class U, bool SAFE_P>
131933 friend class shared_ptr;
131934
131935private:
131936 original internal;
131937
131938public:
131939
131940 weak_ptr() : internal() {
131941 }
131942
131943
131944 template <class U, typename std::enable_if<compatible_with_t<U, T>::value, int>::type = 0>
131945 weak_ptr(shared_ptr<U, SAFE> const &ptr) noexcept : internal(ptr.internal) {
131946 }
131947 weak_ptr(weak_ptr const &other) noexcept : internal(other.internal) {
131948 }
131949 template <class U, typename std::enable_if<compatible_with_t<U, T>::value, int>::type = 0>
131950 weak_ptr(weak_ptr<U> const &ptr) noexcept : internal(ptr.internal) {
131951 }
131952#ifdef DUCKDB_CLANG_TIDY
131953 [[clang::reinitializes]]
131954#endif
131955 weak_ptr(weak_ptr &&ptr) noexcept
131956 : internal(std::move(ptr.internal)) {
131957 }
131958 template <class U, typename std::enable_if<compatible_with_t<U, T>::value, int>::type = 0>
131959#ifdef DUCKDB_CLANG_TIDY
131960 [[clang::reinitializes]]
131961#endif
131962 weak_ptr(weak_ptr<U> &&ptr) noexcept
131963 : internal(std::move(ptr.internal)) {
131964 }
131965
131966
131967 ~weak_ptr() = default;
131968
131969
131970 weak_ptr &
operator=(
const weak_ptr &other) {
131971 if (this == &other) {
131972 return *this;
131973 }
131974 internal = other.internal;
131975 return *this;
131976 }
131977
131978 template <class U, typename std::enable_if<compatible_with_t<U, T>::value, int>::type = 0>
131979 weak_ptr &
operator=(
const shared_ptr<U, SAFE> &ptr) {
131980 internal = ptr.internal;
131981 return *this;
131982 }
131983
131984
131985#ifdef DUCKDB_CLANG_TIDY
131986
131987 [[clang::reinitializes]]
131988#endif
131989 void
131990 reset() {
131991 internal.reset();
131992 }
131993
131994
131995 long use_count() const {
131996 return internal.use_count();
131997 }
131998
131999 bool expired() const {
132000 return internal.expired();
132001 }
132002
132003 shared_ptr<T, SAFE> lock() const {
132004 return shared_ptr<T, SAFE>(internal.lock());
132005 }
132006
132007
132008 template <typename U>
132009 bool operator==(
const weak_ptr<U> &other)
const noexcept {
132010 return internal == other.internal;
132011 }
132012
132013 template <typename U>
132014 bool operator!=(
const weak_ptr<U> &other)
const noexcept {
132015 return internal != other.internal;
132016 }
132017
132018 template <typename U>
132019 bool operator<(
const weak_ptr<U> &other)
const noexcept {
132020 return internal < other.internal;
132021 }
132022
132023 template <typename U>
132024 bool operator<=(
const weak_ptr<U> &other)
const noexcept {
132025 return internal <= other.internal;
132026 }
132027
132028 template <typename U>
132029 bool operator>(
const weak_ptr<U> &other)
const noexcept {
132030 return internal > other.internal;
132031 }
132032
132033 template <typename U>
132034 bool operator>=(
const weak_ptr<U> &other)
const noexcept {
132035 return internal >= other.internal;
132036 }
132037};
132038
132039template <typename T>
132040using unsafe_weak_ptr = weak_ptr<T, false>;
132041
132042}
132043
132044
132045
132046
132047
132048
132049namespace duckdb {
132050
132051template <class T>
132052class enable_shared_from_this {
132053public:
132054 template <class U, bool SAFE>
132055 friend class shared_ptr;
132056
132057private:
132058 mutable weak_ptr<T> __weak_this_;
132059
132060protected:
132061 constexpr enable_shared_from_this() noexcept {
132062 }
132063 enable_shared_from_this(enable_shared_from_this const &) noexcept {
132064 }
132065 enable_shared_from_this &
operator=(enable_shared_from_this
const &)
noexcept {
132066 return *this;
132067 }
132068 ~enable_shared_from_this() {
132069 }
132070
132071public:
132072 shared_ptr<T> shared_from_this() {
132073 return shared_ptr<T>(__weak_this_);
132074 }
132075 shared_ptr<T const> shared_from_this() const {
132076 return shared_ptr<const T>(__weak_this_);
132077 }
132078
132079#if _LIBCPP_STD_VER >= 17
132080 weak_ptr<T> weak_from_this() noexcept {
132081 return __weak_this_;
132082 }
132083
132084 weak_ptr<const T> weak_from_this() const noexcept {
132085 return __weak_this_;
132086 }
132087#endif
132088};
132089
132090}
132091
132092
132093#include <string.h>
132094#include <type_traits>
132095
132096#ifdef _MSC_VER
132097#define suint64_t int64_t
132098#endif
132099
132100#if defined(_WIN32) || defined(_WIN64)
132101#define DUCKDB_WINDOWS
132102#elif defined(__unix__) || defined(__unix) || (defined(__APPLE__) && defined(__MACH__))
132103#define DUCKDB_POSIX
132104#endif
132105
132106namespace duckdb {
132107
132108
132109#ifndef __has_cpp_attribute
132110#define __has_cpp_attribute(x) 0
132111#endif
132112#if __has_cpp_attribute(clang::fallthrough)
132113#define DUCKDB_EXPLICIT_FALLTHROUGH [[clang::fallthrough]]
132114#elif __has_cpp_attribute(gnu::fallthrough)
132115#define DUCKDB_EXPLICIT_FALLTHROUGH [[gnu::fallthrough]]
132116#else
132117#define DUCKDB_EXPLICIT_FALLTHROUGH
132118#endif
132119
132120template <class... T>
132121struct AlwaysFalse {
132122 static constexpr bool VALUE = false;
132123};
132124
132125template<typename T>
132126using reference = std::reference_wrapper<T>;
132127
132128template<class DATA_TYPE, bool SAFE = true>
132129struct TemplatedUniqueIf
132130{
132131 typedef unique_ptr<DATA_TYPE, std::default_delete<DATA_TYPE>, SAFE> templated_unique_single_t;
132132};
132133
132134template<class DATA_TYPE, size_t N>
132135struct TemplatedUniqueIf<DATA_TYPE[N]>
132136{
132137 typedef void TemplatedUniqueArrayKnownBound;
132138};
132139
132140template<class DATA_TYPE, class... ARGS>
132141inline
132142typename TemplatedUniqueIf<DATA_TYPE, true>::templated_unique_single_t
132143make_uniq(ARGS&&... args)
132144{
132145 return unique_ptr<DATA_TYPE, std::default_delete<DATA_TYPE>, true>(new DATA_TYPE(std::forward<ARGS>(args)...));
132146}
132147
132148template<class DATA_TYPE, class... ARGS>
132149inline
132150shared_ptr<DATA_TYPE>
132151make_shared_ptr(ARGS&&... args)
132152{
132153 return shared_ptr<DATA_TYPE>(duckdb_base_std::make_shared<DATA_TYPE>(std::forward<ARGS>(args)...));
132154}
132155
132156template<class DATA_TYPE, class... ARGS>
132157inline
132158typename TemplatedUniqueIf<DATA_TYPE, false>::templated_unique_single_t
132159make_unsafe_uniq(ARGS&&... args)
132160{
132161 return unique_ptr<DATA_TYPE, std::default_delete<DATA_TYPE>, false>(new DATA_TYPE(std::forward<ARGS>(args)...));
132162}
132163
132164template<class DATA_TYPE>
132165inline unique_ptr<DATA_TYPE[], std::default_delete<DATA_TYPE[]>, true>
132166make_uniq_array(size_t n)
132167{
132168 return unique_ptr<DATA_TYPE[], std::default_delete<DATA_TYPE[]>, true>(new DATA_TYPE[n]());
132169}
132170
132171template<class DATA_TYPE>
132172inline unique_ptr<DATA_TYPE[], std::default_delete<DATA_TYPE[]>, true>
132173make_uniq_array_uninitialized(size_t n)
132174{
132175 return unique_ptr<DATA_TYPE[], std::default_delete<DATA_TYPE[]>, true>(new DATA_TYPE[n]);
132176}
132177
132178template<class DATA_TYPE>
132179inline unique_ptr<DATA_TYPE[], std::default_delete<DATA_TYPE[]>, false>
132180make_unsafe_uniq_array(size_t n)
132181{
132182 return unique_ptr<DATA_TYPE[], std::default_delete<DATA_TYPE[]>, false>(new DATA_TYPE[n]());
132183}
132184
132185template<class DATA_TYPE>
132186inline unique_ptr<DATA_TYPE[], std::default_delete<DATA_TYPE[]>, false>
132187make_unsafe_uniq_array_uninitialized(size_t n)
132188{
132189 return unique_ptr<DATA_TYPE[], std::default_delete<DATA_TYPE[]>, false>(new DATA_TYPE[n]);
132190}
132191
132192template<class DATA_TYPE, class... ARGS>
132193 typename TemplatedUniqueIf<DATA_TYPE>::TemplatedUniqueArrayKnownBound
132194 make_uniq(ARGS&&...) = delete;
132195
132196
132197template <typename S, typename T, typename... ARGS>
132198unique_ptr<S> make_uniq_base(ARGS &&... args) {
132199 return unique_ptr<S>(new T(std::forward<ARGS>(args)...));
132200}
132201
132202#ifdef DUCKDB_ENABLE_DEPRECATED_API
132203template <typename S, typename T, typename... Args>
132204unique_ptr<S> make_unique_base(Args &&... args) {
132205 return unique_ptr<S>(new T(std::forward<Args>(args)...));
132206}
132207#endif
132208
132209template <typename SRC, typename TGT>
132210unique_ptr<TGT> unique_ptr_cast(unique_ptr<SRC> src) {
132211 return unique_ptr<TGT>(static_cast<TGT *>(src.release()));
132212}
132213
132214template <typename SRC, typename TGT>
132215shared_ptr<TGT> shared_ptr_cast(shared_ptr<SRC> src) {
132216 return shared_ptr<TGT>(std::static_pointer_cast<TGT, SRC>(src.internal));
132217}
132218
132219#ifdef DUCKDB_DEBUG_MOVE
132220template<class T>
132221typename std::remove_reference<T>::type&& move(T&& t) noexcept {
132222
132223 static_assert(sizeof(T) == 0, "Use std::move instead of unqualified move or duckdb::move");
132224}
132225#endif
132226
132227template <class T, class... ARGS>
132228static duckdb::unique_ptr<T> make_unique(ARGS&&... __args) {
132229#ifndef DUCKDB_ENABLE_DEPRECATED_API
132230 static_assert(sizeof(T) == 0, "Use make_uniq instead of make_unique!");
132231#endif
132232 return unique_ptr<T>(new T(std::forward<ARGS>(__args)...));
132233}
132234
132235template <class T, class... ARGS>
132236static duckdb::shared_ptr<T> make_shared(ARGS&&... __args) {
132237#ifndef DUCKDB_ENABLE_DEPRECATED_API
132238 static_assert(sizeof(T) == 0, "Use make_shared_ptr instead of make_shared!");
132239#endif
132240 return shared_ptr<T>(new T(std::forward<ARGS>(__args)...));
132241}
132242
132243template <typename T>
132244constexpr T MaxValue(T a, T b) {
132245 return a > b ? a : b;
132246}
132247
132248template <typename T>
132249constexpr T MinValue(T a, T b) {
132250 return a < b ? a : b;
132251}
132252
132254template <typename T>
132256 return MinValue(MaxValue(
v,
min),
max);
132257}
132258
132259template <typename T>
132260T AbsValue(T a) {
132261 return a < 0 ? -a : a;
132262}
132263
132265template<class T, T val=8, typename = typename std::enable_if<!std::is_pointer<T>::value>::type>
132267 return ((n + (val - 1)) / val) * val;
132268}
132269
132270template <class T>
132272 return ((n + (val - 1)) / val) * val;
132273}
132274
132275template<uintptr_t alignment, class T>
132276inline T *AlignPointer(T *addr) {
132277 static_assert((alignment & (alignment - 1)) == 0, "'alignment' has to be a power of 2");
132278 return reinterpret_cast<T *>((reinterpret_cast<uintptr_t>(addr) + alignment - 1) & ~(alignment - 1));
132279}
132280
132281template<class T, T val=8>
132282constexpr inline T AlignValueFloor(T n) {
132283 return (n / val) * val;
132284}
132285
132286template<class T, T val=8>
132287static inline bool ValueIsAligned(T n) {
132288 return (n % val) == 0;
132289}
132290
132291template <typename T>
132292T SignValue(T a) {
132293 return a < 0 ? -1 : 1;
132294}
132295
132296template <typename T>
132297const T Load(const_data_ptr_t ptr) {
132298 T ret;
132299 memcpy(&ret, ptr, sizeof(ret));
132300 return ret;
132301}
132302
132303template <typename T>
132304const T LoadLE(const_data_ptr_t ptr) {
132305 return BSwapIfBE(Load<T>(ptr));
132306}
132307
132308template <typename T>
132309void Store(const T &val, data_ptr_t ptr) {
132310 memcpy(ptr, (void *)&val, sizeof(val));
132311}
132312
132319template<class T>
132321 if (target.get() != source.get()) {
132322 target = source;
132323 }
132324}
132325
132326template<typename T>
132327using const_reference = std::reference_wrapper<const T>;
132328
132330template<class T>
132332 return &a.get() == &b.get();
132333}
132334
132335template<class T>
132337 return &a == &b;
132338}
132339
132340template<class T, class SRC>
132341void DynamicCastCheck(const SRC *source) {
132342#ifndef __APPLE__
132343
132344 D_ASSERT(reinterpret_cast<const T *>(source) == dynamic_cast<const T *>(source));
132345#endif
132346}
132347
132349template<typename T>
132350class PostIncrement {
132351public:
132352 explicit PostIncrement(T &t) : t(t) {
132353 }
132354 ~PostIncrement() {
132355 ++t;
132356 }
132357private:
132358 T &t;
132359};
132360
132361}
132362
132363
132364
132365
132366
132367
132368
132369
132370
132371
132372
132373
132374
132375
132376
132377
132378#include <vector>
132379
132380namespace duckdb {
132381
132382template <class DATA_TYPE, bool SAFE = true, class ALLOCATOR = std::allocator<DATA_TYPE>>
132383class vector : public std::vector<DATA_TYPE, ALLOCATOR> {
132384public:
132385 using original = std::vector<DATA_TYPE, ALLOCATOR>;
132386 using original::original;
132387 using value_type =
typename original::value_type;
132388 using allocator_type = typename original::allocator_type;
132389 using size_type = typename original::size_type;
132390 using difference_type = typename original::difference_type;
132391 using reference = typename original::reference;
132392 using const_reference = typename original::const_reference;
132393 using pointer = typename original::pointer;
132394 using const_pointer = typename original::const_pointer;
132395 using iterator = typename original::iterator;
132396 using const_iterator = typename original::const_iterator;
132397 using reverse_iterator = typename original::reverse_iterator;
132398 using const_reverse_iterator = typename original::const_reverse_iterator;
132399
132400private:
132401 static inline void AssertIndexInBounds(idx_t index, idx_t size) {
132402#if defined(DUCKDB_DEBUG_NO_SAFETY) || defined(DUCKDB_CLANG_TIDY)
132403 return;
132404#else
132405 if (DUCKDB_UNLIKELY(index >= size)) {
132406 throw InternalException("Attempted to access index %ld within vector of size %ld", index, size);
132407 }
132408#endif
132409 }
132410
132411public:
132412#ifdef DUCKDB_CLANG_TIDY
132413
132414 [[clang::reinitializes]]
132415#endif
132416 inline void
132417 clear() noexcept {
132418 original::clear();
132419 }
132420
132421
132422
132423 vector() = default;
132424 vector(original &&other) : original(std::move(other)) {
132425 }
132426 template <bool INTERNAL_SAFE>
132427 vector(vector<DATA_TYPE, INTERNAL_SAFE> &&other) : original(std::move(other)) {
132428 }
132429
132430 template <bool INTERNAL_SAFE = false>
132431 inline typename original::reference
get(
typename original::size_type __n) {
132432 if (MemorySafety<INTERNAL_SAFE>::ENABLED) {
132433 AssertIndexInBounds(__n, original::size());
132434 }
132435 return original::operator[](__n);
132436 }
132437
132438 template <bool INTERNAL_SAFE = false>
132439 inline typename original::const_reference
get(
typename original::size_type __n)
const {
132440 if (MemorySafety<INTERNAL_SAFE>::ENABLED) {
132441 AssertIndexInBounds(__n, original::size());
132442 }
132443 return original::operator[](__n);
132444 }
132445
132446 typename original::reference operator[](typename original::size_type __n) {
132448 }
132449 typename original::const_reference operator[](typename original::size_type __n) const {
132451 }
132452
132453 typename original::reference front() {
132455 }
132456
132457 typename original::const_reference front() const {
132459 }
132460
132461 typename original::reference back() {
132462 if (MemorySafety<SAFE>::ENABLED && original::empty()) {
132463 throw InternalException("'back' called on an empty vector!");
132464 }
132465 return get<SAFE>(original::size() - 1);
132466 }
132467
132468 typename original::const_reference back() const {
132469 if (MemorySafety<SAFE>::ENABLED && original::empty()) {
132470 throw InternalException("'back' called on an empty vector!");
132471 }
132472 return get<SAFE>(original::size() - 1);
132473 }
132474
132475 void unsafe_erase_at(idx_t idx) {
132476 original::erase(original::begin() + static_cast<typename original::iterator::difference_type>(idx));
132477 }
132478
132479 void erase_at(idx_t idx) {
132480 if (MemorySafety<SAFE>::ENABLED && idx > original::size()) {
132481 throw InternalException("Can't remove offset %d from vector of size %d", idx, original::size());
132482 }
132483 unsafe_erase_at(idx);
132484 }
132485};
132486
132487template <typename T>
132488using unsafe_vector = vector<T, false>;
132489
132490}
132491
132492
132493
132494
132495
132496
132497
132498
132499
132500
132501
132502
132503
132504
132505namespace duckdb {
132506
132507
132508
132509
132510enum class CatalogType :
uint8_t {
132511 INVALID = 0,
132513 SCHEMA_ENTRY = 2,
132514 VIEW_ENTRY = 3,
132515 INDEX_ENTRY = 4,
132516 PREPARED_STATEMENT = 5,
132517 SEQUENCE_ENTRY = 6,
132518 COLLATION_ENTRY = 7,
132519 TYPE_ENTRY = 8,
132520 DATABASE_ENTRY = 9,
132521 COORDINATE_SYSTEM_ENTRY = 10,
132522
132523
132524 TABLE_FUNCTION_ENTRY = 25,
132525 SCALAR_FUNCTION_ENTRY = 26,
132526 AGGREGATE_FUNCTION_ENTRY = 27,
132527 PRAGMA_FUNCTION_ENTRY = 28,
132528 COPY_FUNCTION_ENTRY = 29,
132529 MACRO_ENTRY = 30,
132530 TABLE_MACRO_ENTRY = 31,
132531
132532
132533 DELETED_ENTRY = 51,
132534 RENAMED_ENTRY = 52,
132535
132536
132537 SECRET_ENTRY = 71,
132538 SECRET_TYPE_ENTRY = 72,
132539 SECRET_FUNCTION_ENTRY = 73,
132540
132541
132542 DEPENDENCY_ENTRY = 100
132543
132544};
132545
132546DUCKDB_API string CatalogTypeToString(CatalogType type);
132547CatalogType CatalogTypeFromString(const string &type);
132548
132549}
132550
132551
132552
132553
132554
132555
132556
132557
132558
132559
132560
132561
132562#include <atomic>
132563
132564namespace duckdb {
132565
132566using std::atomic;
132567
132577
132578}
132579
132580
132581
132582
132583
132584
132585
132586
132587
132588
132589
132590
132591
132592
132593
132594namespace duckdb {
132595
132596template <class T, bool SAFE = true>
132597class optional_ptr {
132598public:
132599 optional_ptr() noexcept : ptr(nullptr) {
132600 }
132601 optional_ptr(T *ptr_p) : ptr(ptr_p) {
132602 }
132603 optional_ptr(T &ref) : ptr(&ref) {
132604 }
132605 optional_ptr(
const unique_ptr<T> &ptr_p) : ptr(ptr_p.
get()) {
132606 }
132607 optional_ptr(
const shared_ptr<T> &ptr_p) : ptr(ptr_p.
get()) {
132608 }
132609
132610 void CheckValid() const {
132611 if (MemorySafety<SAFE>::ENABLED) {
132612 if (!ptr) {
132613 throw InternalException("Attempting to dereference an optional pointer that is not set");
132614 }
132615 }
132616 }
132617
132618 operator bool() const {
132619 return ptr;
132620 }
132622 CheckValid();
132623 return *ptr;
132624 }
132626 CheckValid();
132627 return *ptr;
132628 }
132629 T *operator->() {
132630 CheckValid();
132631 return ptr;
132632 }
132633 const T *operator->() const {
132634 CheckValid();
132635 return ptr;
132636 }
132638
132639 return ptr;
132640 }
132641 const T *
get()
const {
132642
132643 return ptr;
132644 }
132645
132646 T *get_mutable() const {
132647
132648 return ptr;
132649 }
132650
132651 bool operator==(
const optional_ptr<T> &rhs)
const {
132652 return ptr == rhs.ptr;
132653 }
132654
132655 bool operator!=(
const optional_ptr<T> &rhs)
const {
132656 return ptr != rhs.ptr;
132657 }
132658
132659private:
132660 T *ptr;
132661};
132662
132663template <typename T>
132664using unsafe_optional_ptr = optional_ptr<T, false>;
132665
132666}
132667
132668
132669
132670
132671
132672
132673
132674
132675
132676
132677
132678
132679
132680
132681
132682
132683
132684
132685
132686
132687
132688
132689
132690
132691
132692
132693
132694
132695
132696
132697
132698
132699
132700
132701
132702
132703
132704namespace duckdb {
132705
132706class optional_idx {
132707 static constexpr const idx_t INVALID_INDEX =
idx_t(-1);
132708
132709public:
132710 optional_idx() :
index(INVALID_INDEX) {
132711 }
132713 if (index == INVALID_INDEX) {
132714 throw InternalException("optional_idx cannot be initialized with an invalid index");
132715 }
132716 }
132717
132718 static optional_idx Invalid() {
132719 return optional_idx();
132720 }
132721
132722 bool IsValid() const {
132723 return index != INVALID_INDEX;
132724 }
132725
132726 void SetInvalid() {
132727 index = INVALID_INDEX;
132728 }
132729
132730 idx_t GetIndex()
const {
132731 if (index == INVALID_INDEX) {
132732 throw InternalException("Attempting to get the index of an optional_idx that is not set");
132733 }
132735 }
132736
132737 inline bool operator==(
const optional_idx &rhs)
const {
132738 return index == rhs.index;
132739 }
132740
132741 inline bool operator!=(
const optional_idx &rhs)
const {
132742 return index != rhs.index;
132743 }
132744
132745private:
132747};
132748
132749}
132750
132751
132752namespace duckdb {
132753class ParsedExpression;
132754
132755class QueryErrorContext {
132756public:
132757 QueryErrorContext(const ParsedExpression &expr);
132758 explicit QueryErrorContext(optional_idx query_location_p = optional_idx()) : query_location(query_location_p) {
132759 }
132760
132762 optional_idx query_location;
132763
132764public:
132765 static string Format(const string &query, const string &error_message, optional_idx error_loc,
132766 bool add_line_indicator = true);
132767};
132768
132769}
132770
132771
132772
132773namespace duckdb {
132774struct EntryLookupInfo;
132775
132776class CatalogException : public Exception {
132777public:
132778 DUCKDB_API explicit CatalogException(const string &msg);
132779
132780 DUCKDB_API explicit CatalogException(const unordered_map<string, string> &extra_info, const string &msg);
132781
132782 template <typename... ARGS>
132783 explicit CatalogException(const string &msg, ARGS &&...params)
132784 : CatalogException(ConstructMessage(msg, std::forward<ARGS>(
params)...)) {
132785 }
132786
132787 template <typename... ARGS>
132788 explicit CatalogException(QueryErrorContext error_context, const string &msg, ARGS &&...params)
132789 : CatalogException(Exception::InitializeExtraInfo(error_context),
132790 ConstructMessage(msg, std::forward<ARGS>(
params)...)) {
132791 }
132792
132793 static CatalogException MissingEntry(const EntryLookupInfo &lookup_info, const string &suggestion);
132794 static CatalogException MissingEntry(CatalogType type, const string &name, const string &suggestion,
132795 QueryErrorContext context = QueryErrorContext());
132796 static CatalogException MissingEntry(const string &type, const string &name, const vector<string> &suggestions,
132797 QueryErrorContext context = QueryErrorContext());
132798 static CatalogException EntryAlreadyExists(CatalogType type, const string &name,
132799 QueryErrorContext context = QueryErrorContext());
132800};
132801
132802}
132803
132804
132805
132806
132807
132808
132809
132810
132811
132812
132813
132814
132815
132816
132817
132818
132819
132820
132821
132822
132823
132824
132825
132826
132827
132828
132829
132830
132831
132832namespace duckdb {
132833
132834class Serializer;
132835class Deserializer;
132836class Value;
132837class TypeCatalogEntry;
132838class Vector;
132839class ClientContext;
132840class ParsedExpression;
132841class CoordinateReferenceSystem;
132842
132843struct string_t;
132844
132845template <class T>
132846using child_list_t = vector<std::pair<std::string, T>>;
132848template <class T>
132850
132851template <class T, typename... ARGS>
132852buffer_ptr<T> make_buffer(ARGS &&...args) {
132853 return make_shared_ptr<T>(std::forward<ARGS>(args)...);
132854}
132855
132856struct list_entry_t {
132857 list_entry_t() = default;
132858 list_entry_t(uint64_t offset, uint64_t length) : offset(offset), length(length) {
132859 }
132860 inline constexpr bool operator!=(
const list_entry_t &other)
const {
132861 return !(*this == other);
132862 }
132863 inline constexpr bool operator==(
const list_entry_t &other)
const {
132864 return offset == other.offset && length == other.length;
132865 }
132866
132869};
132870
132872
132873
132874
132875
132876
132877
132880
132881
132884
132887
132890
132893
132896
132899
132902
132905
132908
132910
132911
132914
132917
132919
132920
132922
132923
132925
132926
132928
132929
132931
132932
132935
132936
132939
132940
132943
132944
132946 INTERVAL = 21,
132947
132950
132951
132954
132956 STRUCT = 24,
132957
132959
132960
132965
132966
132968
132969
132971 ARRAY = 29,
132972
132975
132976
132978
132979
132981
132982
132984
132985
132987 VARCHAR = 200,
132988 UINT128 = 203,
132989 INT128 = 204,
132990 UNKNOWN = 205,
132992 BIT = 206,
132993
132994 INVALID = 255
132995};
132996
132997
132998
132999
133001 INVALID = 0,
133002 SQLNULL = 1,
133003 UNKNOWN = 2,
133004 ANY = 3,
133005 UNBOUND = 4,
133006
133007
133008
133009
133010
133011
133012 TEMPLATE = 5,
133013
133015
133017 TINYINT = 11,
133018 SMALLINT = 12,
133019 INTEGER = 13,
133020 BIGINT = 14,
133021 DATE = 15,
133022 TIME = 16,
133023 TIMESTAMP_SEC = 17,
133024 TIMESTAMP_MS = 18,
133025 TIMESTAMP = 19,
133027 DECIMAL = 21,
133030 CHAR = 24,
133031 VARCHAR = 25,
133032 BLOB = 26,
133033 INTERVAL = 27,
133034 UTINYINT = 28,
133035 USMALLINT = 29,
133036 UINTEGER = 30,
133037 UBIGINT = 31,
133038 TIMESTAMP_TZ = 32,
133039 TIME_TZ = 34,
133040 TIME_NS = 35,
133041 BIT = 36,
133042 STRING_LITERAL = 37,
133043 INTEGER_LITERAL = 38,
133044 BIGNUM = 39,
133045 UHUGEINT = 49,
133046 HUGEINT = 50,
133047 POINTER = 51,
133048 VALIDITY = 53,
133049 UUID = 54,
133050
133051 GEOMETRY = 60,
133052
133053 STRUCT = 100,
133055 MAP = 102,
133056 TABLE = 103,
133057 ENUM = 104,
133058 AGGREGATE_STATE = 105,
133059 LAMBDA = 106,
133060 UNION = 107,
133061 ARRAY = 108,
133062 VARIANT = 109
133063};
133064
133065struct ExtraTypeInfo;
133066struct ExtensionTypeInfo;
133067
133068struct aggregate_state_t;
133069
133070struct LogicalType {
133071 DUCKDB_API LogicalType();
133072 DUCKDB_API LogicalType(LogicalTypeId id);
133073 DUCKDB_API LogicalType(LogicalTypeId id, shared_ptr<ExtraTypeInfo> type_info);
133074 DUCKDB_API LogicalType(const LogicalType &other);
133075 DUCKDB_API LogicalType(LogicalType &&other) noexcept;
133076
133077 DUCKDB_API ~LogicalType();
133078
133080 return id_;
133081 }
133083 return physical_type_;
133084 }
133085 inline const optional_ptr<ExtraTypeInfo> AuxInfo() const {
133086 return type_info_.get();
133087 }
133088 inline bool IsNested() const {
133089 auto internal = InternalType();
133090 if (internal == PhysicalType::STRUCT) {
133091 return true;
133092 }
133093 if (internal == PhysicalType::LIST) {
133094 return true;
133095 }
133096 if (internal == PhysicalType::ARRAY) {
133097 return true;
133098 }
133099 return false;
133100 }
133101 inline bool IsUnknown() const {
133102 return id_ == LogicalTypeId::UNKNOWN;
133103 }
133104 inline bool IsUnbound() const {
133105 return id_ == LogicalTypeId::UNBOUND;
133106 }
133107
133108 inline shared_ptr<ExtraTypeInfo> GetAuxInfoShrPtr() const {
133109 return type_info_;
133110 }
133111
133113 LogicalType Copy() const;
133115 LogicalType DeepCopy() const;
133116
133117 inline void CopyAuxInfo(const LogicalType &other) {
133118 type_info_ = other.type_info_;
133119 }
133120 bool EqualTypeInfo(const LogicalType &rhs) const;
133121
133122
133123 inline LogicalType &
operator=(
const LogicalType &other) {
133124 if (this == &other) {
133125 return *this;
133126 }
133127 id_ = other.id_;
133128 physical_type_ = other.physical_type_;
133129 type_info_ = other.type_info_;
133130 return *this;
133131 }
133132
133133 inline LogicalType &
operator=(LogicalType &&other)
noexcept {
133134 id_ = other.id_;
133135 physical_type_ = other.physical_type_;
133136 std::swap(type_info_, other.type_info_);
133137 return *this;
133138 }
133139
133140 DUCKDB_API
bool operator==(
const LogicalType &rhs)
const;
133141 inline bool operator!=(
const LogicalType &rhs)
const {
133142 return !(*this == rhs);
133143 }
133144
133145 DUCKDB_API void Serialize(Serializer &serializer) const;
133146 DUCKDB_API static LogicalType Deserialize(Deserializer &deserializer);
133147
133148 static bool TypeIsTimestamp(LogicalTypeId id) {
133149 return (id == LogicalTypeId::TIMESTAMP || id == LogicalTypeId::TIMESTAMP_MS ||
133150 id == LogicalTypeId::TIMESTAMP_NS || id == LogicalTypeId::TIMESTAMP_SEC ||
133151 id == LogicalTypeId::TIMESTAMP_TZ);
133152 }
133153 static bool TypeIsTimestamp(const LogicalType &type) {
133154 return TypeIsTimestamp(type.id());
133155 }
133156 DUCKDB_API string ToString() const;
133157 DUCKDB_API bool IsIntegral() const;
133158 DUCKDB_API bool IsFloating() const;
133159 DUCKDB_API bool IsNumeric() const;
133160 DUCKDB_API static bool IsNumeric(LogicalTypeId type);
133161 DUCKDB_API bool IsTemporal() const;
133162 DUCKDB_API
hash_t Hash()
const;
133163 DUCKDB_API void SetAlias(string alias);
133164 DUCKDB_API bool HasAlias() const;
133165 DUCKDB_API string GetAlias() const;
133166
133167 DUCKDB_API bool HasExtensionInfo() const;
133168 DUCKDB_API optional_ptr<const ExtensionTypeInfo> GetExtensionInfo() const;
133169 DUCKDB_API optional_ptr<ExtensionTypeInfo> GetExtensionInfo();
133170 DUCKDB_API void SetExtensionInfo(unique_ptr<ExtensionTypeInfo> info);
133171
133173 DUCKDB_API static LogicalType MaxLogicalType(ClientContext &context, const LogicalType &left, const LogicalType &right);
133174 DUCKDB_API static bool TryGetMaxLogicalType(ClientContext &context, const LogicalType &left, const LogicalType &right, LogicalType &result);
133175 DUCKDB_API static bool TryGetMaxLogicalTypeUnchecked(const LogicalType &left, const LogicalType &right, LogicalType &result);
133177 DUCKDB_API static LogicalType ForceMaxLogicalType(const LogicalType &left, const LogicalType &right);
133179 DUCKDB_API static LogicalType NormalizeType(const LogicalType &type);
133180
133181
133183 DUCKDB_API bool GetDecimalProperties(uint8_t &width, uint8_t &scale) const;
133184
133185 DUCKDB_API void Verify() const;
133186
133187 DUCKDB_API bool IsSigned() const;
133188 DUCKDB_API bool IsUnsigned() const;
133189
133190 DUCKDB_API bool IsValid() const;
133191 DUCKDB_API bool IsComplete() const;
133192 DUCKDB_API bool IsTemplated() const;
133193
133195 bool SupportsRegularUpdate() const;
133196
133197
133198private:
133201 shared_ptr<ExtraTypeInfo> type_info_;
133202
133203private:
133205
133206public:
133207 static constexpr const LogicalTypeId SQLNULL = LogicalTypeId::SQLNULL;
133208 static constexpr const LogicalTypeId UNKNOWN = LogicalTypeId::UNKNOWN;
133210 static constexpr const LogicalTypeId TINYINT = LogicalTypeId::TINYINT;
133211 static constexpr const LogicalTypeId UTINYINT = LogicalTypeId::UTINYINT;
133212 static constexpr const LogicalTypeId SMALLINT = LogicalTypeId::SMALLINT;
133213 static constexpr const LogicalTypeId USMALLINT = LogicalTypeId::USMALLINT;
133214 static constexpr const LogicalTypeId INTEGER = LogicalTypeId::INTEGER;
133215 static constexpr const LogicalTypeId UINTEGER = LogicalTypeId::UINTEGER;
133216 static constexpr const LogicalTypeId BIGINT = LogicalTypeId::BIGINT;
133217 static constexpr const LogicalTypeId UBIGINT = LogicalTypeId::UBIGINT;
133220 static constexpr const LogicalTypeId DATE = LogicalTypeId::DATE;
133221 static constexpr const LogicalTypeId TIMESTAMP = LogicalTypeId::TIMESTAMP;
133222 static constexpr const LogicalTypeId TIMESTAMP_S = LogicalTypeId::TIMESTAMP_SEC;
133223 static constexpr const LogicalTypeId TIMESTAMP_MS = LogicalTypeId::TIMESTAMP_MS;
133225 static constexpr const LogicalTypeId TIME = LogicalTypeId::TIME;
133226 static constexpr const LogicalTypeId TIME_NS = LogicalTypeId::TIME_NS;
133227 static constexpr const LogicalTypeId TIMESTAMP_TZ = LogicalTypeId::TIMESTAMP_TZ;
133228 static constexpr const LogicalTypeId TIME_TZ = LogicalTypeId::TIME_TZ;
133229 static constexpr const LogicalTypeId VARCHAR = LogicalTypeId::VARCHAR;
133230 static constexpr const LogicalTypeId ANY = LogicalTypeId::ANY;
133231 static constexpr const LogicalTypeId BLOB = LogicalTypeId::BLOB;
133232 static constexpr const LogicalTypeId BIT = LogicalTypeId::BIT;
133233 static constexpr const LogicalTypeId BIGNUM = LogicalTypeId::BIGNUM;
133234
133235 static constexpr const LogicalTypeId INTERVAL = LogicalTypeId::INTERVAL;
133236 static constexpr const LogicalTypeId HUGEINT = LogicalTypeId::HUGEINT;
133237 static constexpr const LogicalTypeId UHUGEINT = LogicalTypeId::UHUGEINT;
133238 static constexpr const LogicalTypeId UUID = LogicalTypeId::UUID;
133239 static constexpr const LogicalTypeId HASH = LogicalTypeId::UBIGINT;
133240 static constexpr const LogicalTypeId POINTER = LogicalTypeId::POINTER;
133241 static constexpr const LogicalTypeId TABLE = LogicalTypeId::TABLE;
133242 static constexpr const LogicalTypeId LAMBDA = LogicalTypeId::LAMBDA;
133243 static constexpr const LogicalTypeId INVALID = LogicalTypeId::INVALID;
133245
133246
133247 DUCKDB_API static LogicalType DECIMAL(uint8_t width, uint8_t scale);
133248 DUCKDB_API static LogicalType VARCHAR_COLLATION(string collation);
133249 DUCKDB_API
static LogicalType
LIST(
const LogicalType &child);
133250 DUCKDB_API static LogicalType STRUCT(child_list_t<LogicalType> children);
133251 DUCKDB_API static LogicalType AGGREGATE_STATE(aggregate_state_t state_type);
133252 DUCKDB_API static LogicalType MAP(const LogicalType &child);
133253 DUCKDB_API static LogicalType MAP(LogicalType key, LogicalType value);
133254 DUCKDB_API static LogicalType UNION(child_list_t<LogicalType> members);
133255 DUCKDB_API static LogicalType ARRAY(const LogicalType &child, optional_idx index);
133256 DUCKDB_API static LogicalType ENUM(Vector &ordered_data, idx_t size);
133257 DUCKDB_API static LogicalType GEOMETRY();
133258 DUCKDB_API static LogicalType GEOMETRY(const string &crs);
133259 DUCKDB_API static LogicalType GEOMETRY(const CoordinateReferenceSystem &crs);
133260
133261 DUCKDB_API static LogicalType ANY_PARAMS(LogicalType target, idx_t cast_score = 5);
133262 DUCKDB_API static LogicalType TEMPLATE(const string &name);
133263 DUCKDB_API static LogicalType VARIANT();
133265 DUCKDB_API static LogicalType INTEGER_LITERAL(const Value &constant);
133266
133267 DUCKDB_API static LogicalType ENUM(const string &enum_name, Vector &ordered_data, idx_t size);
133268 DUCKDB_API static LogicalType UNBOUND(unique_ptr<ParsedExpression> expr);
133269 DUCKDB_API
static LogicalType
TYPE();
133271 DUCKDB_API static const vector<LogicalType> Numeric();
133273 DUCKDB_API static const vector<LogicalType> Integral();
133275 DUCKDB_API static const vector<LogicalType> Real();
133277 DUCKDB_API static const vector<LogicalType> AllTypes();
133278
133279public:
133281 static constexpr auto JSON_TYPE_NAME = "JSON";
133282 DUCKDB_API static LogicalType JSON();
133283 DUCKDB_API bool IsJSONType() const;
133284};
133285
133286struct DecimalType {
133287 DUCKDB_API
static uint8_t GetWidth(
const LogicalType &type);
133288 DUCKDB_API
static uint8_t GetScale(
const LogicalType &type);
133289 DUCKDB_API
static uint8_t MaxWidth();
133290};
133291
133292struct StringType {
133293 DUCKDB_API static string GetCollation(const LogicalType &type);
133294};
133295
133296struct ListType {
133297 DUCKDB_API static const LogicalType &GetChildType(const LogicalType &type);
133298};
133299
133300
133301struct UnboundType {
133302
133303 DUCKDB_API static LogicalType TryParseAndDefaultBind(const string &type_str);
133304 DUCKDB_API static LogicalType TryDefaultBind(const LogicalType &unbound_type);
133305 DUCKDB_API static const unique_ptr<ParsedExpression> &GetTypeExpression(const LogicalType &type);
133306};
133307
133308struct EnumType {
133309 DUCKDB_API
static int64_t GetPos(
const LogicalType &type,
const string_t &key);
133310 DUCKDB_API static const Vector &GetValuesInsertOrder(const LogicalType &type);
133311 DUCKDB_API
static idx_t GetSize(
const LogicalType &type);
133312 DUCKDB_API static const string GetValue(const Value &val);
133313 DUCKDB_API
static PhysicalType GetPhysicalType(
const LogicalType &type);
133314 DUCKDB_API static string_t GetString(const LogicalType &type, idx_t pos);
133315};
133316
133317struct StructType {
133318 DUCKDB_API static const child_list_t<LogicalType> &GetChildTypes(const LogicalType &type);
133319 DUCKDB_API static const LogicalType &GetChildType(const LogicalType &type, idx_t index);
133320 DUCKDB_API static const string &GetChildName(const LogicalType &type, idx_t index);
133321 DUCKDB_API
static idx_t GetChildIndexUnsafe(
const LogicalType &type,
const string &name);
133322 DUCKDB_API
static idx_t GetChildCount(
const LogicalType &type);
133323 DUCKDB_API static bool IsUnnamed(const LogicalType &type);
133324};
133325
133326struct MapType {
133327 DUCKDB_API
static const LogicalType &
KeyType(
const LogicalType &type);
133328 DUCKDB_API static const LogicalType &ValueType(const LogicalType &type);
133329};
133330
133331struct UnionType {
133332 DUCKDB_API
static const idx_t MAX_UNION_MEMBERS = 256;
133333 DUCKDB_API
static idx_t GetMemberCount(
const LogicalType &type);
133334 DUCKDB_API static const LogicalType &GetMemberType(const LogicalType &type, idx_t index);
133335 DUCKDB_API static const string &GetMemberName(const LogicalType &type, idx_t index);
133336 DUCKDB_API static const child_list_t<LogicalType> CopyMemberTypes(const LogicalType &type);
133337};
133338
133339struct ArrayType {
133340 DUCKDB_API static const LogicalType &GetChildType(const LogicalType &type);
133341 DUCKDB_API
static idx_t GetSize(
const LogicalType &type);
133342 DUCKDB_API static bool IsAnySize(const LogicalType &type);
133343 DUCKDB_API
static constexpr idx_t MAX_ARRAY_SIZE = 100000;
133345 DUCKDB_API static LogicalType ConvertToList(const LogicalType &type);
133346};
133347
133348struct AggregateStateType {
133349 DUCKDB_API static const string GetTypeName(const LogicalType &type);
133350 DUCKDB_API static const aggregate_state_t &GetStateType(const LogicalType &type);
133351};
133352
133353struct AnyType {
133354 DUCKDB_API static LogicalType GetTargetType(const LogicalType &type);
133355 DUCKDB_API
static idx_t GetCastScore(
const LogicalType &type);
133356};
133357
133358struct IntegerLiteral {
133360 DUCKDB_API static LogicalType GetType(const LogicalType &type);
133362 DUCKDB_API static bool FitsInType(const LogicalType &type, const LogicalType &target);
133363};
133364
133365struct TemplateType {
133366
133367 DUCKDB_API static const string &GetName(const LogicalType &type);
133368};
133369
133370struct GeoType {
133371 DUCKDB_API static bool HasCRS(const LogicalType &type);
133372 DUCKDB_API static const CoordinateReferenceSystem &GetCRS(const LogicalType &type);
133373};
133374
133375
133376DUCKDB_API string LogicalTypeIdToString(LogicalTypeId type);
133377
133378DUCKDB_API
LogicalTypeId TransformStringToLogicalTypeId(
const string &str);
133379
133380DUCKDB_API LogicalType TransformStringToLogicalType(const string &str, ClientContext &context);
133381
133384
133385DUCKDB_API string TypeIdToString(PhysicalType type);
133386DUCKDB_API
idx_t GetTypeIdSize(PhysicalType type);
133387DUCKDB_API bool TypeIsConstantSize(PhysicalType type);
133388DUCKDB_API bool TypeIsIntegral(PhysicalType type);
133389DUCKDB_API bool TypeIsNumeric(PhysicalType type);
133390DUCKDB_API bool TypeIsInteger(PhysicalType type);
133391
133392bool ApproxEqual(float l, float r);
133393bool ApproxEqual(double l, double r);
133394
133395struct aggregate_state_t {
133396 aggregate_state_t() {
133397 }
133398
133399 aggregate_state_t(string function_name_p, LogicalType return_type_p, vector<LogicalType> bound_argument_types_p)
133400 : function_name(std::move(function_name_p)), return_type(std::move(return_type_p)),
133401 bound_argument_types(std::move(bound_argument_types_p)) {
133402 }
133403
133404 string function_name;
133405 LogicalType return_type;
133406 vector<LogicalType> bound_argument_types;
133407};
133408
133409
133410
133411}
133412
133413
133414
133415
133416
133417
133418
133419
133420
133421
133422
133423
133424
133425
133426
133427
133428
133429
133430
133431
133432
133433
133434
133435
133436
133437
133438
133439#include <type_traits>
133440
133441
133442#undef max
133443
133444#include <limits>
133445
133446namespace duckdb {
133447
133448template <class T>
133449struct NumericLimits {
133450 static constexpr T Minimum() {
133451 return std::numeric_limits<T>::has_infinity ? -std::numeric_limits<T>::infinity()
133452 : std::numeric_limits<T>::lowest();
133453 }
133454 static constexpr T Maximum() {
133455 return std::numeric_limits<T>::has_infinity ? std::numeric_limits<T>::infinity()
133456 : std::numeric_limits<T>::
max();
133457 }
133458 static constexpr bool IsSigned() {
133459 return std::is_signed<T>::value;
133460 }
133461 static constexpr bool IsIntegral() {
133462 return std::is_integral<T>::value || std::is_enum<T>::value;
133463 }
133464 static constexpr idx_t Digits();
133465};
133466
133467template <>
133468struct NumericLimits<hugeint_t> {
133469 static constexpr hugeint_t Minimum() {
133470 return {std::numeric_limits<int64_t>::lowest(), 0};
133471 };
133472 static constexpr hugeint_t Maximum() {
133473 return {std::numeric_limits<int64_t>::max(), std::numeric_limits<uint64_t>::max()};
133474 };
133475 static constexpr bool IsSigned() {
133476 return true;
133477 }
133478 static constexpr bool IsIntegral() {
133479 return true;
133480 }
133481 static constexpr idx_t Digits() {
133482 return 39;
133483 }
133484};
133485
133486template <>
133487struct NumericLimits<uhugeint_t> {
133488 static constexpr uhugeint_t Minimum() {
133489 return {0, 0};
133490 };
133491 static constexpr uhugeint_t Maximum() {
133492 return {std::numeric_limits<uint64_t>::max(), std::numeric_limits<uint64_t>::max()};
133493 };
133494 static constexpr bool IsSigned() {
133495 return false;
133496 }
133497 static constexpr bool IsIntegral() {
133498 return true;
133499 }
133500 static constexpr idx_t Digits() {
133501 return 39;
133502 }
133503};
133504
133505template <>
133506constexpr idx_t NumericLimits<int8_t>::Digits() {
133507 return 3;
133508}
133509
133510template <>
133511constexpr idx_t NumericLimits<int16_t>::Digits() {
133512 return 5;
133513}
133514
133515template <>
133516constexpr idx_t NumericLimits<int32_t>::Digits() {
133517 return 10;
133518}
133519
133520template <>
133521constexpr idx_t NumericLimits<int64_t>::Digits() {
133522 return 19;
133523}
133524
133525template <>
133526constexpr idx_t NumericLimits<uint8_t>::Digits() {
133527 return 3;
133528}
133529
133530template <>
133531constexpr idx_t NumericLimits<uint16_t>::Digits() {
133532 return 5;
133533}
133534
133535template <>
133536constexpr idx_t NumericLimits<uint32_t>::Digits() {
133537 return 10;
133538}
133539
133540template <>
133541constexpr idx_t NumericLimits<uint64_t>::Digits() {
133542 return 20;
133543}
133544
133545template <>
133546constexpr idx_t NumericLimits<float>::Digits() {
133547 return 127;
133548}
133549
133550template <>
133551constexpr idx_t NumericLimits<double>::Digits() {
133552 return 250;
133553}
133554
133555}
133556
133557
133558
133559
133560
133561
133562
133563
133564
133565
133566
133567
133568
133569
133570
133571
133572
133573
133574
133575
133576
133577
133578
133579#include <type_traits>
133580
133581
133582
133583
133584namespace duckdb {
133585
133586template <class T>
133587struct MakeSigned {
133588 using type = typename std::make_signed<T>::type;
133589};
133590
133591template <>
133592struct MakeSigned<hugeint_t> {
133593 using type = hugeint_t;
133594};
133595
133596template <>
133597struct MakeSigned<uhugeint_t> {
133598 using type = hugeint_t;
133599};
133600
133601template <class T>
133602struct MakeUnsigned {
133603 using type = typename std::make_unsigned<T>::type;
133604};
133605
133606template <>
133607struct MakeUnsigned<hugeint_t> {
133608 using type = uhugeint_t;
133609};
133610
133611template <>
133612struct MakeUnsigned<uhugeint_t> {
133613 using type = uhugeint_t;
133614};
133615
133616template <class TO, class FROM>
133617static void ThrowNumericCastError(FROM in, TO minval, TO maxval) {
133618 throw InternalException("Information loss on integer cast: value %d outside of target range [%d, %d]", in, minval,
133619 maxval);
133620}
133621
133622template <class TO, class FROM, bool are_same_type>
133623struct NumericCastImpl;
133624
133625template <class TO, class FROM>
133626struct NumericCastImpl<TO, FROM, true> {
133627 static TO Convert(FROM val) {
133628 return static_cast<TO>(val);
133629 }
133630};
133631
133632template <class TO, class FROM>
133633struct NumericCastImpl<TO, FROM, false> {
133634 static TO Convert(FROM val) {
133635
133636 auto minval = NumericLimits<TO>::Minimum();
133637 auto maxval = NumericLimits<TO>::Maximum();
133638 auto unsigned_in = static_cast<typename MakeUnsigned<FROM>::type>(val);
133639 auto unsigned_min = static_cast<typename MakeUnsigned<TO>::type>(minval);
133640 auto unsigned_max = static_cast<typename MakeUnsigned<TO>::type>(maxval);
133641 auto signed_in = static_cast<typename MakeSigned<FROM>::type>(val);
133642 auto signed_min = static_cast<typename MakeSigned<TO>::type>(minval);
133643 auto signed_max = static_cast<typename MakeSigned<TO>::type>(maxval);
133644
133645 if (!NumericLimits<FROM>::IsSigned() && !NumericLimits<TO>::IsSigned() &&
133646 (unsigned_in < unsigned_min || unsigned_in > unsigned_max)) {
133647 ThrowNumericCastError(val, static_cast<TO>(unsigned_min), static_cast<TO>(unsigned_max));
133648 }
133649
133650 if (NumericLimits<FROM>::IsSigned() && NumericLimits<TO>::IsSigned() &&
133651 (signed_in < signed_min || signed_in > signed_max)) {
133652 ThrowNumericCastError(val, static_cast<TO>(signed_min), static_cast<TO>(signed_max));
133653 }
133654
133655 if (NumericLimits<FROM>::IsSigned() != NumericLimits<TO>::IsSigned() &&
133656 (signed_in < signed_min || unsigned_in > unsigned_max)) {
133657 ThrowNumericCastError(val, static_cast<TO>(signed_min), static_cast<TO>(unsigned_max));
133658 }
133659
133660 return static_cast<TO>(val);
133661 }
133662};
133663
133664
133665
133666
133667template <class TO, class FROM,
133668 class = typename std::enable_if<(NumericLimits<TO>::IsIntegral() && NumericLimits<FROM>::IsIntegral()) ||
133669 std::is_same<TO, FROM>::value>::type>
133670TO NumericCast(FROM val) {
133671 return NumericCastImpl<TO, FROM, std::is_same<TO, FROM>::value>::Convert(val);
133672}
133673
133674
133675
133676
133677template <class TO, class FROM,
133678 class = typename std::enable_if<(NumericLimits<TO>::IsIntegral() && NumericLimits<FROM>::IsIntegral()) ||
133679 std::is_same<TO, FROM>::value>::type>
133680TO UnsafeNumericCast(FROM in) {
133681#if defined(DEBUG) || defined(UNSAFE_NUMERIC_CAST)
133682 return NumericCast<TO, FROM>(in);
133683#endif
133684 return static_cast<TO>(in);
133685}
133686
133687
133688
133689
133690template <class TO, class FROM>
133691TO LossyNumericCast(FROM val) {
133692 return static_cast<TO>(val);
133693}
133694
133695
133696
133697
133698
133699template <class TO>
133700TO ExactNumericCast(double val) {
133701 auto res = LossyNumericCast<TO>(val);
133702#if defined(DEBUG) || defined(UNSAFE_NUMERIC_CAST)
133703 if (val != double(res)) {
133704 throw InternalException("Information loss on double cast: value %lf outside of target range [%lf, %lf]", val,
133705 double(res), double(res));
133706 }
133707#endif
133708 return res;
133709}
133710
133711template <class TO>
133712TO ExactNumericCast(float val) {
133713 auto res = LossyNumericCast<TO>(val);
133714#if defined(DEBUG) || defined(UNSAFE_NUMERIC_CAST)
133715 if (val != float(res)) {
133716 throw InternalException("Information loss on float cast: value %f outside of target range [%f, %f]", val,
133717 float(res), float(res));
133718 }
133719#endif
133720 return res;
133721}
133722
133723template <class T>
133724struct NextUnsigned {};
133725
133726template <>
133727struct NextUnsigned<uint8_t> {
133729};
133730
133731template <>
133732struct NextUnsigned<uint16_t> {
133734};
133735
133736template <>
133737struct NextUnsigned<uint32_t> {
133739};
133740
133741template <>
133742struct NextUnsigned<uint64_t> {
133743#if ((__GNUC__ >= 5) || defined(__clang__)) && defined(__SIZEOF_INT128__)
133744 using type = __uint128_t;
133745#else
133746 using type = uhugeint_t;
133747#endif
133748};
133749
133750template <class TYPE>
133751class FastMod {
133752 using NEXT_TYPE = typename NextUnsigned<TYPE>::type;
133753 static_assert(sizeof(NEXT_TYPE) != 0, "NextUnsigned not available for this type");
133754
133755public:
133756 explicit FastMod(TYPE divisor_p) : divisor(divisor_p), multiplier((static_cast<
TYPE>(-1) / divisor) + 1) {
133757 }
133758
133759 TYPE Div(
const TYPE &val)
const {
133760 return static_cast<TYPE>((
static_cast<NEXT_TYPE
>(val) * multiplier) >> (
sizeof(
TYPE) * 8));
133761 }
133762
133763 TYPE Mod(
const TYPE &val,
const TYPE "ient)
const {
133764 return val - quotient * divisor;
133765 }
133766
133767 TYPE Mod(
const TYPE &val)
const {
133768 return Mod(val, Div(val));
133769 }
133770
133771 const TYPE &GetDivisor()
const {
133772 return divisor;
133773 }
133774
133775private:
133776 const TYPE divisor;
133777 const TYPE multiplier;
133778};
133779
133780}
133781
133782
133783
133784
133785
133786
133787
133788
133789
133790
133791
133792#include <utility>
133793
133794namespace duckdb {
133795using std::make_pair;
133796using std::pair;
133797}
133798
133799
133800
133801
133802
133803
133804
133805
133806
133807
133808
133809#include <set>
133810
133811namespace duckdb {
133812using std::multiset;
133813using std::set;
133814}
133815
133816
133817
133818
133819
133820
133821
133822
133823
133824
133825
133826
133827#include <unordered_map>
133828#include <string>
133829
133830
133831
133832
133833namespace duckdb {
133834
133835enum class ComplexJSONType :
uint8_t { VALUE = 0, OBJECT = 1, ARRAY = 2 };
133836
133838struct ComplexJSON {
133840 explicit ComplexJSON(const string &str);
133842 ComplexJSON();
133844 void AddObjectEntry(const string &key, unique_ptr<ComplexJSON> object);
133846 void AddArrayElement(unique_ptr<ComplexJSON> object);
133848 ComplexJSON &GetObject(const string &key);
133850 ComplexJSON &GetArrayElement(const idx_t &index);
133852 string GetValue(const string &key) const;
133854 string GetValue(const idx_t &index) const;
133856 static string GetValueRecursive(const ComplexJSON &child);
133858 unordered_map<string, string> Flatten() const;
133859
133860private:
133862 string str_value;
133864 unordered_map<string, unique_ptr<ComplexJSON>> obj_value;
133866 vector<unique_ptr<ComplexJSON>> arr_value;
133868 ComplexJSONType type;
133869};
133870
133871}
133872
133873
133874
133875
133876
133877
133878
133879
133880
133881
133882
133883
133884
133885
133886
133887namespace duckdb {
133888
133889class ParserException : public Exception {
133890public:
133891 DUCKDB_API explicit ParserException(const string &msg);
133892
133893 DUCKDB_API explicit ParserException(const unordered_map<string, string> &extra_info, const string &msg);
133894
133895 template <typename... ARGS>
133896 explicit ParserException(const string &msg, ARGS &&...params)
133897 : ParserException(ConstructMessage(msg, std::forward<ARGS>(
params)...)) {
133898 }
133899 template <typename... ARGS>
133900 explicit ParserException(optional_idx error_location, const string &msg, ARGS &&...params)
133901 : ParserException(Exception::InitializeExtraInfo(error_location),
133902 ConstructMessage(msg, std::forward<ARGS>(
params)...)) {
133903 }
133904 template <typename... ARGS>
133905 explicit ParserException(const ParsedExpression &expr, const string &msg, ARGS &&...params)
133906 : ParserException(Exception::InitializeExtraInfo(expr), ConstructMessage(msg, std::forward<ARGS>(
params)...)) {
133907 }
133908
133909 static ParserException SyntaxError(const string &query, const string &error_message, optional_idx error_location);
133910};
133911
133912}
133913
133914
133915#include <cstring>
133916
133917namespace duckdb {
133918
133919#ifndef DUCKDB_QUOTE_DEFINE
133920
133921
133922
133923
133924
133925
133926#define DUCKDB_QUOTE_DEFINE_IMPL(x) #x
133927#define DUCKDB_QUOTE_DEFINE(x) DUCKDB_QUOTE_DEFINE_IMPL(x)
133928#endif
133929
133936class StringUtil {
133937public:
133938 static string GenerateRandomName(idx_t length = 16);
133939
133940 static uint8_t GetHexValue(
char c) {
133941 if (c >= '0' && c <= '9') {
133942 return UnsafeNumericCast<uint8_t>(c - '0');
133943 }
133944 if (c >= 'a' && c <= 'f') {
133945 return UnsafeNumericCast<uint8_t>(c - 'a' + 10);
133946 }
133947 if (c >= 'A' && c <= 'F') {
133948 return UnsafeNumericCast<uint8_t>(c - 'A' + 10);
133949 }
133950 throw InvalidInputException("Invalid input for hex digit: %s", string(1, c));
133951 }
133952 static uint8_t GetBinaryValue(
char c) {
133953 if (c >= '0' && c <= '1') {
133954 return UnsafeNumericCast<uint8_t>(c - '0');
133955 }
133956 throw InvalidInputException("Invalid input for binary digit: %s", string(1, c));
133957 }
133958
133959 static bool CharacterIsSpace(char c) {
133960 return c == ' ' || c == '\t' || c == '\n' || c == '\v' || c == '\f' || c == '\r';
133961 }
133962 static bool CharacterIsNewline(char c) {
133963 return c == '\n' || c == '\r';
133964 }
133965 static bool CharacterIsDigit(char c) {
133966 return c >= '0' && c <= '9';
133967 }
133968 static bool CharacterIsHex(char c) {
133969 return (c >= '0' && c <= '9') || (c >= 'a' && c <= 'f') || (c >= 'A' && c <= 'F');
133970 }
133971 static char CharacterToUpper(char c) {
133972 if (c >= 'a' && c <= 'z') {
133973 return UnsafeNumericCast<char>(c - ('a' - 'A'));
133974 }
133975 return c;
133976 }
133977 static char CharacterToLower(char c) {
133978 if (c >= 'A' && c <= 'Z') {
133979 return UnsafeNumericCast<char>(c + ('a' - 'A'));
133980 }
133981 return c;
133982 }
133983 static bool CharacterIsAlpha(char c) {
133984 return (c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z');
133985 }
133986 static bool CharacterIsAlphaNumeric(char c) {
133987 return CharacterIsAlpha(c) || CharacterIsDigit(c);
133988 }
133989 static bool CharacterIsOperator(char c) {
133990 if (c == '_') {
133991 return false;
133992 }
133993 if (c >= '!' && c <= '/') {
133994 return true;
133995 }
133996 if (c >= ':' && c <= '@') {
133997 return true;
133998 }
133999 if (c >= '[' && c <= '`') {
134000 return true;
134001 }
134002 if (c >= '{' && c <= '~') {
134003 return true;
134004 }
134005 return false;
134006 }
134007
134008 template <class TO>
134009 static vector<TO> ConvertStrings(const vector<string> &strings) {
134010 vector<TO> result;
134011 for (auto &string : strings) {
134012 result.emplace_back(string);
134013 }
134014 return result;
134015 }
134016
134017 static vector<SQLIdentifier> ConvertToSQLIdentifiers(const vector<string> &strings) {
134018 return ConvertStrings<SQLIdentifier>(strings);
134019 }
134020
134021 static vector<SQLString> ConvertToSQLStrings(const vector<string> &strings) {
134022 return ConvertStrings<SQLString>(strings);
134023 }
134024
134026 DUCKDB_API static bool Contains(const string &haystack, const string &needle);
134027 DUCKDB_API static bool Contains(const string &haystack, const char &needle_char);
134028
134030 DUCKDB_API static optional_idx Find(const string &haystack, const string &needle);
134031
134033 DUCKDB_API static bool StartsWith(string str, string prefix);
134034
134036 DUCKDB_API static bool EndsWith(const string &str, const string &suffix);
134037
134039 DUCKDB_API static string Repeat(const string &str, const idx_t n);
134040
134042 DUCKDB_API static vector<string> Split(const string &str, char delimiter);
134043
134045 DUCKDB_API static vector<string> SplitWithParentheses(const string &str, char delimiter = ',', char par_open = '(',
134046 char par_close = ')');
134047
134049 DUCKDB_API static vector<string> SplitWithQuote(const string &str, char delimiter = ',', char quote = '"');
134050
134052 DUCKDB_API static string Join(const vector<string> &input, const string &separator);
134053 DUCKDB_API static string Join(const set<string> &input, const string &separator);
134054
134056 DUCKDB_API static string URLEncode(const string &str, bool encode_slash = true);
134057 DUCKDB_API
static idx_t URLEncodeSize(
const char *input, idx_t input_size,
bool encode_slash =
true);
134058 DUCKDB_API static void URLEncodeBuffer(const char *input, idx_t input_size, char *output, bool encode_slash = true);
134060 DUCKDB_API static string URLDecode(const string &str, bool plus_to_space = false);
134061 DUCKDB_API
static idx_t URLDecodeSize(
const char *input, idx_t input_size,
bool plus_to_space =
false);
134062 DUCKDB_API static void URLDecodeBuffer(const char *input, idx_t input_size, char *output,
134063 bool plus_to_space = false);
134064
134066 DUCKDB_API static void SkipBOM(const char *buffer_ptr, const idx_t &buffer_size, idx_t &buffer_pos);
134067
134068 DUCKDB_API
static idx_t ToUnsigned(
const string &str);
134069 DUCKDB_API
static int64_t ToSigned(
const string &str);
134070 DUCKDB_API static double ToDouble(const string &str);
134071
134072 template <class T>
134073 static string ToString(const vector<T> &input, const string &separator) {
134074 vector<string> input_list;
134075 for (auto &i : input) {
134076 input_list.push_back(i.ToString());
134077 }
134079 }
134080
134083 template <typename C, typename S, typename FUNC>
134084 static string Join(const C &input, S count, const string &separator, FUNC f) {
134085
134086 std::string result;
134087
134088
134089
134090 if (count > 0) {
134091 result += f(input[0]);
134092 }
134093
134094
134095 for (size_t i = 1; i < count; i++) {
134096 result += separator + f(input[i]);
134097 }
134098
134099 return result;
134100 }
134101
134103 DUCKDB_API static string BytesToHumanReadableString(idx_t bytes, idx_t multiplier = 1024);
134104
134105 DUCKDB_API
static string TryParseFormattedBytes(
const string &
arg, idx_t &result);
134106
134107 DUCKDB_API
static idx_t ParseFormattedBytes(
const string &
arg);
134108
134110 DUCKDB_API static string Upper(const string &str);
134111
134113 DUCKDB_API static string Lower(const string &str);
134114
134116 DUCKDB_API static string Title(const string &str);
134117
134118 DUCKDB_API static bool IsLower(const string &str);
134119 DUCKDB_API static bool IsUpper(const string &str);
134120
134122 DUCKDB_API
static uint64_t CIHash(
const string &str);
134123 DUCKDB_API
static uint64_t CIHash(
const char *str, idx_t size);
134124
134126 DUCKDB_API static bool CIEquals(const string &l1, const string &l2);
134127
134129 DUCKDB_API static bool CIEquals(const char *l1, idx_t l1_size, const char *l2, idx_t l2_size);
134130
134132 DUCKDB_API static bool CIStartsWith(const string &str, const string &prefix);
134133
134135 DUCKDB_API static bool CILessThan(const string &l1, const string &l2);
134136
134138 DUCKDB_API
static idx_t CIFind(vector<string> &vec,
const string &str);
134139
134141 template <typename... ARGS>
134142 static string Format(const string fmt_str, ARGS... params) {
134143 return Exception::ConstructMessage(fmt_str,
params...);
134144 }
134145
134147 DUCKDB_API static vector<string> Split(const string &input, const string &split);
134148
134150 DUCKDB_API static void LTrim(string &str);
134152 DUCKDB_API static void RTrim(string &str);
134154 DUCKDB_API static void RTrim(string &str, const string &chars_to_trim);
134156 DUCKDB_API static void Trim(string &str);
134157
134158 DUCKDB_API static string Replace(string source, const string &from, const string &to);
134159
134166 DUCKDB_API
static idx_t LevenshteinDistance(
const string &s1,
const string &s2, idx_t not_equal_penalty = 1);
134167
134169 DUCKDB_API
static idx_t SimilarityScore(
const string &s1,
const string &s2);
134171 DUCKDB_API static double SimilarityRating(const string &s1, const string &s2);
134176 DUCKDB_API static vector<string> TopNStrings(vector<pair<string, double>> scores, idx_t n = 5,
134177 double threshold = 0.5);
134180 DUCKDB_API static vector<string> TopNStrings(const vector<pair<string, idx_t>> &scores, idx_t n = 5,
134181 idx_t threshold = 5);
134184 DUCKDB_API static vector<string> TopNLevenshtein(const vector<string> &strings, const string &target, idx_t n = 5,
134185 idx_t threshold = 5);
134188 DUCKDB_API static vector<string> TopNJaroWinkler(const vector<string> &strings, const string &target, idx_t n = 5,
134189 double threshold = 0.5);
134190 DUCKDB_API static string CandidatesMessage(const vector<string> &candidates,
134191 const string &candidate = "Candidate bindings");
134192
134195 DUCKDB_API static string CandidatesErrorMessage(const vector<string> &strings, const string &target,
134196 const string &message_prefix, idx_t n = 5);
134197
134200 static bool Equals(const char *s1, const char *s2) {
134201 if (s1 == s2) {
134202 return true;
134203 }
134204 if (s1 == nullptr || s2 == nullptr) {
134205 return false;
134206 }
134207 return strcmp(s1, s2) == 0;
134208 }
134209 static bool Equals(const string &s1, const char *s2) {
134210 return Equals(s1.c_str(), s2);
134211 }
134212 static bool Equals(const char *s1, const string &s2) {
134213 return Equals(s1, s2.c_str());
134214 }
134215 static bool Equals(const string &s1, const string &s2) {
134216 return s1 == s2;
134217 }
134218 static bool Equals(const string_t &s1, const char *s2);
134219 static bool Equals(const char *s1, const string_t &s2);
134220
134226 DUCKDB_API static unique_ptr<ComplexJSON> ParseJSONMap(const string &json, bool ignore_errors = false);
134227
134231 DUCKDB_API static string ExceptionToJSONMap(ExceptionType type, const string &message,
134232 const unordered_map<string, string> &map);
134233
134235 DUCKDB_API static string ToJSONMap(const unordered_map<string, string> &map);
134237 DUCKDB_API static string ToComplexJSONMap(const ComplexJSON &complex_json);
134238
134239 DUCKDB_API static string ValidateJSON(const char *data, const idx_t &len);
134240
134241 DUCKDB_API static string GetFileName(const string &file_path);
134242 DUCKDB_API static string GetFileExtension(const string &file_name);
134243 DUCKDB_API static string GetFileStem(const string &file_name);
134244 DUCKDB_API static string GetFilePath(const string &file_path);
134245
134246 struct EnumStringLiteral {
134248 const char *string;
134249 };
134250
134251 DUCKDB_API
static uint32_t StringToEnum(
const EnumStringLiteral enum_list[], idx_t enum_count,
134252 const char *enum_name, const char *str_value);
134253 DUCKDB_API static const char *EnumToString(const EnumStringLiteral enum_list[], idx_t enum_count,
134254 const char *enum_name, uint32_t enum_value);
134255 DUCKDB_API
static const uint8_t ASCII_TO_LOWER_MAP[];
134256 DUCKDB_API
static const uint8_t ASCII_TO_UPPER_MAP[];
134257};
134258}
134259
134260
134261
134262
134263#include <functional>
134264
134265namespace duckdb {
134266
134267struct date_t;
134268struct dtime_t;
134269struct dtime_ns_t;
134270struct dtime_tz_t;
134271
134273struct timestamp_t {
134274
134275
134277
134278 timestamp_t() = default;
134279 explicit inline constexpr timestamp_t(int64_t micros) : value(micros) {
134280 }
134281 inline timestamp_t &
operator=(int64_t micros) {
134282 value = micros;
134283 return *this;
134284 }
134285
134286
134287 explicit inline operator int64_t()
const {
134288 return value;
134289 }
134290
134291
134292 inline bool operator==(
const timestamp_t &rhs)
const {
134293 return value == rhs.value;
134294 };
134295 inline bool operator!=(
const timestamp_t &rhs)
const {
134296 return value != rhs.value;
134297 };
134298 inline bool operator<=(
const timestamp_t &rhs)
const {
134299 return value <= rhs.value;
134300 };
134301 inline bool operator<(
const timestamp_t &rhs)
const {
134302 return value < rhs.value;
134303 };
134304 inline bool operator>(
const timestamp_t &rhs)
const {
134305 return value > rhs.value;
134306 };
134307 inline bool operator>=(
const timestamp_t &rhs)
const {
134308 return value >= rhs.value;
134309 };
134310
134311
134312 timestamp_t
operator+(
const double &value)
const;
134314
134315
134316 timestamp_t &
operator+=(
const int64_t &delta);
134317 timestamp_t &
operator-=(
const int64_t &delta);
134318
134319
134320 static constexpr timestamp_t infinity() {
134321 return timestamp_t(NumericLimits<int64_t>::Maximum());
134322 }
134323 static constexpr timestamp_t ninfinity() {
134324 return timestamp_t(-NumericLimits<int64_t>::Maximum());
134325 }
134326 static constexpr inline timestamp_t epoch() {
134327 return timestamp_t(0);
134328 }
134329};
134330
134332struct timestamp_sec_t : public timestamp_t {
134333 timestamp_sec_t() = default;
134334 explicit inline constexpr timestamp_sec_t(int64_t seconds) : timestamp_t(seconds) {
134335 }
134336};
134337
134339struct timestamp_ms_t : public timestamp_t {
134340 timestamp_ms_t() = default;
134341 explicit inline constexpr timestamp_ms_t(int64_t millis) : timestamp_t(millis) {
134342 }
134343};
134344
134346struct timestamp_ns_t : public timestamp_t {
134347 timestamp_ns_t() = default;
134348 explicit inline constexpr timestamp_ns_t(int64_t nanos) : timestamp_t(nanos) {
134349 }
134350};
134351
134354struct timestamp_tz_t : public timestamp_t {
134355 timestamp_tz_t() = default;
134356 explicit inline constexpr timestamp_tz_t(int64_t micros) : timestamp_t(micros) {
134357 }
134358 explicit inline constexpr timestamp_tz_t(timestamp_t ts) : timestamp_t(ts) {
134359 }
134360};
134361
134362enum class TimestampCastResult :
uint8_t {
134363 SUCCESS,
134364 ERROR_INCORRECT_FORMAT,
134365 ERROR_NON_UTC_TIMEZONE,
134366 ERROR_RANGE,
134367 STRICT_UTC
134368};
134369
134370struct TimestampComponents {
134374
134379};
134380
134382class Timestamp {
134383public:
134384
134385 constexpr static const int32_t MIN_YEAR = -290308;
134386 constexpr static const int32_t MIN_MONTH = 12;
134387 constexpr static const int32_t MIN_DAY = 22;
134388
134389public:
134391 DUCKDB_API static timestamp_t FromString(const string &str, bool use_offset);
134395 DUCKDB_API static TimestampCastResult TryConvertTimestampTZ(const char *str, idx_t len, timestamp_t &result,
134396 const bool use_offset, bool &has_offset, string_t &tz,
134397 optional_ptr<int32_t> nanos = nullptr);
134399 DUCKDB_API static TimestampCastResult TryConvertTimestamp(const char *str, idx_t len, timestamp_t &result,
134400 const bool use_offset,
134401 optional_ptr<int32_t> nanos = nullptr,
134402 bool strict = false);
134403 DUCKDB_API static TimestampCastResult TryConvertTimestamp(const char *str, idx_t len, timestamp_ns_t &result);
134404 DUCKDB_API static timestamp_t FromCString(const char *str, idx_t len, bool use_offset = false,
134405 optional_ptr<int32_t> nanos = nullptr);
134407 DUCKDB_API static string ToString(timestamp_t timestamp);
134408
134409 DUCKDB_API static date_t GetDate(timestamp_t timestamp);
134410
134411 DUCKDB_API static dtime_t GetTime(timestamp_t timestamp);
134412 DUCKDB_API static dtime_ns_t GetTimeNs(timestamp_ns_t timestamp);
134414 DUCKDB_API static timestamp_t FromDatetime(date_t date, dtime_t time);
134415 DUCKDB_API static bool TryFromDatetime(date_t date, dtime_t time, timestamp_t &result);
134416 DUCKDB_API static bool TryFromDatetime(date_t date, dtime_tz_t timetz, timestamp_t &result);
134418 DUCKDB_API static bool TryFromTimestampNanos(timestamp_t ts, int32_t nanos, timestamp_ns_t &result);
134419
134421 static inline bool CharacterIsTimeZone(char c) {
134422 return StringUtil::CharacterIsAlpha(c) || StringUtil::CharacterIsDigit(c) || c == '_' || c == '/' || c == '+' ||
134423 c == '-';
134424 }
134425
134427 static inline bool IsFinite(timestamp_t timestamp) {
134428 return timestamp != timestamp_t::infinity() &&
timestamp != timestamp_t::ninfinity();
134429 }
134430
134432 DUCKDB_API static void Convert(timestamp_t date, date_t &out_date, dtime_t &out_time);
134434 DUCKDB_API static void Convert(timestamp_ns_t date, date_t &out_date, dtime_t &out_time, int32_t &out_nanos);
134436 DUCKDB_API static timestamp_t GetCurrentTimestamp();
134437
134439 DUCKDB_API static timestamp_t FromEpochSecondsPossiblyInfinite(int64_t s);
134440 DUCKDB_API static timestamp_t FromEpochSeconds(int64_t s);
134442 DUCKDB_API static timestamp_t FromEpochMsPossiblyInfinite(int64_t ms);
134443 DUCKDB_API static timestamp_t FromEpochMs(int64_t ms);
134445 DUCKDB_API static timestamp_t FromEpochMicroSeconds(int64_t micros);
134447 DUCKDB_API static timestamp_t FromEpochNanoSecondsPossiblyInfinite(int64_t nanos);
134448 DUCKDB_API static timestamp_t FromEpochNanoSeconds(int64_t nanos);
134449
134451 DUCKDB_API static timestamp_ns_t TimestampNsFromEpochMicros(int64_t micros);
134452 DUCKDB_API static timestamp_ns_t TimestampNsFromEpochMillis(int64_t millis);
134453
134455 DUCKDB_API static bool TryGetEpochNanoSeconds(timestamp_t timestamp, int64_t &result);
134457 DUCKDB_API
static int64_t GetEpochSeconds(timestamp_t timestamp);
134459 DUCKDB_API
static int64_t GetEpochMs(timestamp_t timestamp);
134461 DUCKDB_API
static int64_t GetEpochMicroSeconds(timestamp_t timestamp);
134463 DUCKDB_API
static int64_t GetEpochNanoSeconds(timestamp_t timestamp);
134464 DUCKDB_API
static int64_t GetEpochNanoSeconds(timestamp_ns_t timestamp);
134466 DUCKDB_API
static int64_t GetEpochRounded(timestamp_t timestamp,
const int64_t power_of_ten);
134468 DUCKDB_API static double GetJulianDay(timestamp_t timestamp);
134469
134471 DUCKDB_API static TimestampComponents GetComponents(timestamp_t timestamp);
134472 DUCKDB_API static time_t ToTimeT(timestamp_t);
134473 DUCKDB_API static timestamp_t FromTimeT(time_t);
134474
134475 DUCKDB_API static bool TryParseUTCOffset(const char *str, idx_t &pos, idx_t len, int &hh, int &mm, int &ss);
134476
134477 DUCKDB_API static string FormatError(const string &str);
134478 DUCKDB_API static string FormatError(string_t str);
134479 DUCKDB_API static string UnsupportedTimezoneError(const string &str);
134480 DUCKDB_API static string UnsupportedTimezoneError(string_t str);
134481 DUCKDB_API static string RangeError(const string &str);
134482 DUCKDB_API static string RangeError(string_t str);
134483};
134484
134485}
134486
134487namespace std {
134488
134490template <>
134491struct hash<duckdb::timestamp_t> {
134492 std::size_t
operator()(
const duckdb::timestamp_t &k)
const {
134493 using std::hash;
134494 return hash<int64_t>()((
int64_t)k);
134495 }
134496};
134497template <>
134498struct hash<duckdb::timestamp_ms_t> {
134499 std::size_t
operator()(
const duckdb::timestamp_ms_t &k)
const {
134500 using std::hash;
134501 return hash<int64_t>()((
int64_t)k);
134502 }
134503};
134504template <>
134505struct hash<duckdb::timestamp_ns_t> {
134506 std::size_t
operator()(
const duckdb::timestamp_ns_t &k)
const {
134507 using std::hash;
134508 return hash<int64_t>()((
int64_t)k);
134509 }
134510};
134511template <>
134512struct hash<duckdb::timestamp_sec_t> {
134513 std::size_t
operator()(
const duckdb::timestamp_sec_t &k)
const {
134514 using std::hash;
134515 return hash<int64_t>()((
int64_t)k);
134516 }
134517};
134518template <>
134519struct hash<duckdb::timestamp_tz_t> {
134520 std::size_t
operator()(
const duckdb::timestamp_tz_t &k)
const {
134521 using std::hash;
134522 return hash<int64_t>()((
int64_t)k);
134523 }
134524};
134525}
134526
134527
134528
134529
134530
134531
134532
134533
134534
134535
134536
134537
134538
134539
134540
134541
134542
134543
134544
134545
134546
134547
134548
134549
134550
134551
134552
134553
134554
134555
134556
134557
134558
134559
134560
134561
134562
134563
134564
134565
134566
134567
134568
134569
134570
134571
134572
134573
134574
134575
134576
134577
134578
134579#include <functional>
134580
134581namespace duckdb {
134582
134584struct dtime_t {
134586
134587 dtime_t() = default;
134588 explicit inline constexpr dtime_t(int64_t micros_p) : micros(micros_p) {
134589 }
134590 inline dtime_t &
operator=(int64_t micros_p) {
134591 micros = micros_p;
134592 return *this;
134593 }
134594
134595
134596 explicit inline operator int64_t()
const {
134597 return micros;
134598 }
134599 explicit inline operator double() const {
134600 return static_cast<double>(micros);
134601 }
134602
134603
134604 inline bool operator==(
const dtime_t &rhs)
const {
134605 return micros == rhs.micros;
134606 };
134607 inline bool operator!=(
const dtime_t &rhs)
const {
134608 return micros != rhs.micros;
134609 };
134610 inline bool operator<=(
const dtime_t &rhs)
const {
134611 return micros <= rhs.micros;
134612 };
134613 inline bool operator<(
const dtime_t &rhs)
const {
134614 return micros < rhs.micros;
134615 };
134616 inline bool operator>(
const dtime_t &rhs)
const {
134617 return micros > rhs.micros;
134618 };
134619 inline bool operator>=(
const dtime_t &rhs)
const {
134620 return micros >= rhs.micros;
134621 };
134622
134623
134624 inline dtime_t
operator+(
const int64_t µs)
const {
134625 return dtime_t(this->micros + micros);
134626 };
134627 inline dtime_t
operator+(
const double µs)
const {
134628 return dtime_t(this->micros +
int64_t(micros));
134629 };
134630 inline dtime_t
operator-(
const int64_t µs)
const {
134631 return dtime_t(this->micros - micros);
134632 };
134633 inline dtime_t
operator*(
const idx_t &copies)
const {
134634 return dtime_t(this->micros * UnsafeNumericCast<int64_t>(copies));
134635 };
134636 inline dtime_t
operator/(
const idx_t &copies)
const {
134637 return dtime_t(this->micros / UnsafeNumericCast<int64_t>(copies));
134638 };
134640 return this->micros - other.micros;
134641 };
134642
134643
134644 inline dtime_t &
operator+=(
const int64_t µs) {
134645 this->micros += micros;
134646 return *this;
134647 };
134648 inline dtime_t &
operator-=(
const int64_t µs) {
134649 this->micros -= micros;
134650 return *this;
134651 };
134652 inline dtime_t &
operator+=(
const dtime_t &other) {
134653 this->micros += other.micros;
134654 return *this;
134655 };
134656
134657
134658 static inline dtime_t allballs() {
134659 return dtime_t(0);
134660 }
134661};
134662
134664struct dtime_ns_t : public dtime_t {
134665 dtime_ns_t() = default;
134666 explicit inline constexpr dtime_ns_t(const int64_t nanos) : dtime_t(nanos) {
134667 }
134668 inline dtime_t time() const {
134669 return dtime_t(micros / 1000);
134670 }
134671};
134672
134673struct dtime_tz_t {
134674 static constexpr const int TIME_BITS = 40;
134675 static constexpr const int OFFSET_BITS = 24;
134676 static constexpr const uint64_t OFFSET_MASK = ~uint64_t(0) >> TIME_BITS;
134677 static constexpr const int32_t MAX_OFFSET = 16 * 60 * 60 - 1;
134678 static constexpr const int32_t MIN_OFFSET = -MAX_OFFSET;
134679 static constexpr const uint64_t OFFSET_MICROS = 1000000;
134680
134682
134683
134684
134685
134686 static inline uint64_t encode_offset(int32_t offset) {
134687 return uint64_t(MAX_OFFSET - offset);
134688 }
134689 static inline int32_t decode_offset(uint64_t bits) {
134690 return MAX_OFFSET -
int32_t(bits & OFFSET_MASK);
134691 }
134692
134693 static inline uint64_t encode_micros(int64_t micros) {
134694 return encode_micros(UnsafeNumericCast<uint64_t>(micros));
134695 }
134696 static inline uint64_t encode_micros(uint64_t micros) {
134697 return micros << OFFSET_BITS;
134698 }
134699 static inline int64_t decode_micros(uint64_t bits) {
134700 return int64_t(bits >> OFFSET_BITS);
134701 }
134702
134703 dtime_tz_t() = default;
134704
134705 inline dtime_tz_t(dtime_t t, int32_t offset) : bits(encode_micros(t.micros) | encode_offset(offset)) {
134706 }
134707 explicit inline dtime_tz_t(uint64_t bits_p) : bits(bits_p) {
134708 }
134709
134710 inline dtime_t time() const {
134711 return dtime_t(decode_micros(bits));
134712 }
134713
134714 inline int32_t offset()
const {
134715 return decode_offset(bits);
134716 }
134717
134718
134719
134720
134721 inline uint64_t sort_key()
const {
134722 return bits + encode_micros((bits & OFFSET_MASK) * OFFSET_MICROS);
134723 }
134724
134725
134726 inline bool operator==(
const dtime_tz_t &rhs)
const {
134727 return bits == rhs.bits;
134728 };
134729 inline bool operator!=(
const dtime_tz_t &rhs)
const {
134730 return bits != rhs.bits;
134731 };
134732 inline bool operator<=(
const dtime_tz_t &rhs)
const {
134733 return sort_key() <= rhs.sort_key();
134734 };
134735 inline bool operator<(
const dtime_tz_t &rhs)
const {
134736 return sort_key() < rhs.sort_key();
134737 };
134738 inline bool operator>(
const dtime_tz_t &rhs)
const {
134739 return sort_key() > rhs.sort_key();
134740 };
134741 inline bool operator>=(
const dtime_tz_t &rhs)
const {
134742 return sort_key() >= rhs.sort_key();
134743 };
134744};
134745
134746}
134747
134748namespace std {
134749
134751template <>
134752struct hash<duckdb::dtime_t> {
134753 std::size_t
operator()(
const duckdb::dtime_t &k)
const {
134754 using std::hash;
134755 return hash<int64_t>()((
int64_t)k);
134756 }
134757};
134758
134759template <>
134760struct hash<duckdb::dtime_tz_t> {
134761 std::size_t
operator()(
const duckdb::dtime_tz_t &k)
const {
134762 using std::hash;
134763 return hash<uint64_t>()(k.bits);
134764 }
134765};
134766}
134767
134768
134769namespace duckdb {
134770
134771struct string_t;
134772struct interval_t;
134773
134776 return left ^ right;
134777}
134778
134779#ifdef DUCKDB_HASH_ZERO
134780template <class T>
134782 return 0;
134783}
134784
134785DUCKDB_API
hash_t Hash(
const char *val,
size_t size);
134786DUCKDB_API
hash_t Hash(uint8_t *val,
size_t size);
134787#else
134791 x ^= x >> 32;
134792 x *= 0xd6e8feb86659fd93U;
134793 x ^= x >> 32;
134794 x *= 0xd6e8feb86659fd93U;
134795 x ^= x >> 32;
134796 return x;
134797}
134798
134799inline hash_t MurmurHash32(uint32_t x) {
134801}
134802
134803template <class T>
134805 return MurmurHash32(
static_cast<uint32_t>(value));
134806}
134807
134808template <>
134809DUCKDB_API
inline hash_t Hash(uint64_t val) {
134811}
134812template <>
134813DUCKDB_API
inline hash_t Hash(int64_t val) {
134815}
134816template <>
134817DUCKDB_API
hash_t Hash(hugeint_t val);
134818template <>
134819DUCKDB_API
hash_t Hash(uhugeint_t val);
134820template <>
134821DUCKDB_API
hash_t Hash(
float val);
134822template <>
134823DUCKDB_API
hash_t Hash(
double val);
134824template <>
134825DUCKDB_API
hash_t Hash(
const char *val);
134826template <>
134827DUCKDB_API
hash_t Hash(
char *val);
134828template <>
134829DUCKDB_API
hash_t Hash(string_t val);
134830template <>
134831DUCKDB_API
hash_t Hash(interval_t val);
134832template <>
134833DUCKDB_API
hash_t Hash(dtime_tz_t val);
134834DUCKDB_API
hash_t Hash(
const char *val,
size_t size);
134835DUCKDB_API
hash_t Hash(uint8_t *val,
size_t size);
134836#endif
134837
134838}
134839
134840
134841#include <cstring>
134842#include <algorithm>
134843
134844namespace duckdb {
134845
134846struct string_t {
134847 friend struct StringComparisonOperators;
134848
134849public:
134850 static constexpr idx_t PREFIX_BYTES = 4 *
sizeof(char);
134851 static constexpr idx_t INLINE_BYTES = 12 *
sizeof(char);
134852 static constexpr idx_t HEADER_SIZE =
sizeof(
uint32_t) + PREFIX_BYTES;
134853 static constexpr idx_t MAX_STRING_SIZE = NumericLimits<uint32_t>::Maximum();
134854#ifndef DUCKDB_DEBUG_NO_INLINE
134855 static constexpr idx_t PREFIX_LENGTH = PREFIX_BYTES;
134856 static constexpr idx_t INLINE_LENGTH = INLINE_BYTES;
134857#else
134858 static constexpr idx_t PREFIX_LENGTH = 0;
134859 static constexpr idx_t INLINE_LENGTH = 0;
134860#endif
134861
134862 string_t() = default;
134863 explicit string_t(uint32_t len) {
134864 value.inlined.length = len;
134865 }
134866 string_t(const char *data, uint32_t len) {
134867 value.inlined.length = len;
134868 D_ASSERT(data || GetSize() == 0);
134869 if (IsInlined()) {
134870
134871
134872 memset(value.inlined.inlined, 0, INLINE_BYTES);
134873 if (GetSize() == 0) {
134874 return;
134875 }
134876
134877 memcpy(value.inlined.inlined, data, GetSize());
134878 } else {
134879
134880#ifndef DUCKDB_DEBUG_NO_INLINE
134881 memcpy(value.pointer.prefix, data, PREFIX_LENGTH);
134882#else
134883 memset(value.pointer.prefix, 0, PREFIX_BYTES);
134884#endif
134885 value.pointer.ptr = (char *)data;
134886 }
134887 }
134888
134889 string_t(const char *data)
134890 : string_t(data, UnsafeNumericCast<
uint32_t>(strlen(data))) {
134891 }
134892 string_t(const string &value)
134893 : string_t(value.c_str(), UnsafeNumericCast<
uint32_t>(value.
size())) {
134894 }
134895
134896 bool IsInlined() const {
134897 return GetSize() <= INLINE_LENGTH;
134898 }
134899
134900 const char *GetData() const {
134901 return IsInlined() ? const_char_ptr_cast(value.inlined.inlined) : value.pointer.ptr;
134902 }
134903 const char *GetDataUnsafe() const {
134904 return GetData();
134905 }
134906
134907 char *GetDataWriteable() const {
134908 return IsInlined() ? (char *)value.inlined.inlined : value.pointer.ptr;
134909 }
134910
134911 const char *GetPrefix() const {
134912 return value.inlined.inlined;
134913 }
134914
134915 char *GetPrefixWriteable() {
134916 return value.inlined.inlined;
134917 }
134918
134919 idx_t GetSize()
const {
134920 return value.inlined.length;
134921 }
134922
134923 void SetSizeAndFinalize(uint32_t size, idx_t allocated_size) {
134924 value.inlined.length =
size;
134925 if (allocated_size > INLINE_LENGTH && IsInlined()) {
134927 D_ASSERT(value.pointer.ptr);
134928 auto ptr = value.pointer.ptr;
134929 memcpy(GetDataWriteable(), ptr, size);
134930 }
134931 Finalize();
134932 VerifyCharacters();
134933 }
134934
134935 bool Empty() const {
134936 return value.inlined.length == 0;
134937 }
134938
134939 string GetString() const {
134940 return string(GetData(), GetSize());
134941 }
134942
134943 explicit operator string() const {
134944 return GetString();
134945 }
134946
134947 char *GetPointer() const {
134948 D_ASSERT(!IsInlined());
134949 return value.pointer.ptr;
134950 }
134951
134952 void SetPointer(char *new_ptr) {
134953 D_ASSERT(!IsInlined());
134954 value.pointer.ptr = new_ptr;
134955 }
134956
134957 void Finalize() {
134958
134959 if (GetSize() <= INLINE_LENGTH) {
134960
134961 memset(value.inlined.inlined + GetSize(), 0, INLINE_BYTES - GetSize());
134962 } else {
134963
134964#ifndef DUCKDB_DEBUG_NO_INLINE
134965 auto dataptr = GetData();
134966 memcpy(value.pointer.prefix, dataptr, PREFIX_LENGTH);
134967#else
134968 memset(value.pointer.prefix, 0, PREFIX_BYTES);
134969#endif
134970 }
134971 }
134972
134973 void Verify() const;
134974 void VerifyUTF8() const;
134975 void VerifyCharacters() const;
134976 void VerifyNull() const;
134977
134978 struct StringComparisonOperators {
134979 static inline bool Equals(const string_t &a, const string_t &b) {
134980#ifdef DUCKDB_DEBUG_NO_INLINE
134981 if (a.GetSize() != b.GetSize()) {
134982 return false;
134983 }
134984 return (memcmp(a.GetData(), b.GetData(), a.GetSize()) == 0);
134985#endif
134986 uint64_t a_bulk_comp = Load<uint64_t>(const_data_ptr_cast(&a));
134987 uint64_t b_bulk_comp = Load<uint64_t>(const_data_ptr_cast(&b));
134988 if (a_bulk_comp != b_bulk_comp) {
134989
134990 return false;
134991 }
134992
134993 a_bulk_comp = Load<uint64_t>(const_data_ptr_cast(&a) + 8u);
134994 b_bulk_comp = Load<uint64_t>(const_data_ptr_cast(&b) + 8u);
134995 if (a_bulk_comp == b_bulk_comp) {
134996
134997 return true;
134998 }
134999 if (!a.IsInlined()) {
135000
135001 if (memcmp(a.value.pointer.ptr, b.value.pointer.ptr, a.GetSize()) == 0) {
135002 return true;
135003 }
135004 }
135005
135006
135007
135008 return false;
135009 }
135010
135011 static bool GreaterThan(const string_t &left, const string_t &right) {
135012 const uint32_t left_length = UnsafeNumericCast<uint32_t>(left.GetSize());
135013 const uint32_t right_length = UnsafeNumericCast<uint32_t>(right.GetSize());
135014 const uint32_t min_length = std::min<uint32_t>(left_length, right_length);
135015
135016#ifndef DUCKDB_DEBUG_NO_INLINE
135017 uint32_t a_prefix = Load<uint32_t>(const_data_ptr_cast(left.GetPrefix()));
135018 uint32_t b_prefix = Load<uint32_t>(const_data_ptr_cast(right.GetPrefix()));
135019
135020
135021
135022
135023
135024
135025
135026 if (a_prefix != b_prefix) {
135027 return BSwapIfLE(a_prefix) > BSwapIfLE(b_prefix);
135028 }
135029#endif
135030 auto memcmp_res = memcmp(left.GetData(), right.GetData(), min_length);
135031 return memcmp_res > 0 || (memcmp_res == 0 && left_length > right_length);
135032 }
135033 };
135034
135036 return StringComparisonOperators::Equals(*this, r);
135037 }
135038
135040 return !(*this == r);
135041 }
135042
135043 bool operator>(
const string_t &r)
const {
135044 return StringComparisonOperators::GreaterThan(*this, r);
135045 }
135046 bool operator<(
const string_t &r)
const {
135047 return r > *this;
135048 }
135049
135050private:
135051 union {
135052 struct {
135054 char prefix[4];
135055 char *ptr;
135056 } pointer;
135057 struct {
135059 char inlined[12];
135060 } inlined;
135061 } value;
135062};
135063
135064}
135065
135066namespace std {
135067template <>
135068struct hash<duckdb::string_t> {
135069 size_t operator()(
const duckdb::string_t &val)
const {
135070 return Hash(val);
135071 }
135072};
135073}
135074
135075
135076
135077#include <functional>
135078
135079namespace duckdb {
135080
135081struct timestamp_t;
135082
135084struct date_t {
135086
135087 date_t() = default;
135088 explicit inline date_t(int32_t days_p) : days(days_p) {
135089 }
135090
135091
135092 explicit inline operator int32_t()
const {
135093 return days;
135094 }
135095
135096
135097 inline bool operator==(
const date_t &rhs)
const {
135098 return days == rhs.days;
135099 };
135100 inline bool operator!=(
const date_t &rhs)
const {
135101 return days != rhs.days;
135102 };
135103 inline bool operator<=(
const date_t &rhs)
const {
135104 return days <= rhs.days;
135105 };
135106 inline bool operator<(
const date_t &rhs)
const {
135107 return days < rhs.days;
135108 };
135109 inline bool operator>(
const date_t &rhs)
const {
135110 return days > rhs.days;
135111 };
135112 inline bool operator>=(
const date_t &rhs)
const {
135113 return days >= rhs.days;
135114 };
135115
135116
135117 inline date_t
operator+(
const int32_t &days)
const {
135118 return date_t(this->days + days);
135119 };
135120 inline date_t
operator-(
const int32_t &days)
const {
135121 return date_t(this->days - days);
135122 };
135123
135124
135125 inline date_t &
operator+=(
const int32_t &days) {
135126 this->days += days;
135127 return *this;
135128 };
135129 inline date_t &
operator-=(
const int32_t &days) {
135130 this->days -= days;
135131 return *this;
135132 };
135133
135134
135135 static inline date_t infinity() {
135136 return date_t(NumericLimits<int32_t>::Maximum());
135137 }
135138 static inline date_t ninfinity() {
135139 return date_t(-NumericLimits<int32_t>::Maximum());
135140 }
135141 static inline date_t epoch() {
135142 return date_t(0);
135143 }
135144};
135145
135146enum class DateCastResult :
uint8_t { SUCCESS, ERROR_INCORRECT_FORMAT, ERROR_RANGE };
135147
135148struct DateSpecial {
135149 const char *str;
135151};
135152
135154class Date {
135155public:
135156 static const DateSpecial PINF;
135157 static const DateSpecial NINF;
135158 static const DateSpecial EPOCH;
135159
135160 static const string_t MONTH_NAMES[12];
135161 static const string_t MONTH_NAMES_ABBREVIATED[12];
135162 static const string_t DAY_NAMES[7];
135163 static const string_t DAY_NAMES_ABBREVIATED[7];
135164 static const int32_t NORMAL_DAYS[13];
135165 static const int32_t CUMULATIVE_DAYS[13];
135166 static const int32_t LEAP_DAYS[13];
135167 static const int32_t CUMULATIVE_LEAP_DAYS[13];
135168 static const int32_t CUMULATIVE_YEAR_DAYS[401];
135169 static const int8_t MONTH_PER_DAY_OF_YEAR[365];
135170 static const int8_t LEAP_MONTH_PER_DAY_OF_YEAR[366];
135171
135172
135173 constexpr static const int32_t DATE_MIN_YEAR = -5877641;
135174 constexpr static const int32_t DATE_MIN_MONTH = 6;
135175 constexpr static const int32_t DATE_MIN_DAY = 25;
135176
135177 constexpr static const int32_t DATE_MAX_YEAR = 5881580;
135178 constexpr static const int32_t DATE_MAX_MONTH = 7;
135179 constexpr static const int32_t DATE_MAX_DAY = 10;
135180 constexpr static const int32_t EPOCH_YEAR = 1970;
135181
135182 constexpr static const int32_t YEAR_INTERVAL = 400;
135183 constexpr static const int32_t DAYS_PER_YEAR_INTERVAL = 146097;
135184
135185public:
135187 DUCKDB_API static date_t FromString(const string &str, bool strict = false);
135189 DUCKDB_API static date_t FromCString(const char *str, idx_t len, bool strict = false);
135191 DUCKDB_API static string ToString(date_t date);
135194 DUCKDB_API static bool TryConvertDateSpecial(const char *buf, idx_t len, idx_t &pos, const DateSpecial &special);
135197 DUCKDB_API static DateCastResult TryConvertDate(const char *buf, idx_t len, idx_t &pos, date_t &result,
135198 bool &special, bool strict = false);
135199
135202 DUCKDB_API static string Format(int32_t year, int32_t month, int32_t day);
135203
135205 DUCKDB_API static void Convert(date_t date, int32_t &out_year, int32_t &out_month, int32_t &out_day);
135207 DUCKDB_API static date_t FromDate(int32_t year, int32_t month, int32_t day);
135208 DUCKDB_API static bool TryFromDate(int32_t year, int32_t month, int32_t day, date_t &result);
135209
135211 DUCKDB_API static bool IsLeapYear(int32_t year);
135212
135215 DUCKDB_API static bool IsValid(int32_t year, int32_t month, int32_t day);
135216
135218 static inline bool IsFinite(date_t date) {
135219 return date != date_t::infinity() && date != date_t::ninfinity();
135220 }
135221
135223 DUCKDB_API
static int32_t MonthDays(int32_t year, int32_t month);
135224
135226 DUCKDB_API
static int64_t Epoch(date_t date);
135228 DUCKDB_API
static int64_t EpochNanoseconds(date_t date);
135230 DUCKDB_API
static int64_t EpochMicroseconds(date_t date);
135232 DUCKDB_API
static int64_t EpochMilliseconds(date_t date);
135234 DUCKDB_API static date_t EpochToDate(int64_t epoch);
135235
135237 DUCKDB_API
static int32_t EpochDays(date_t date);
135239 DUCKDB_API static date_t EpochDaysToDate(int32_t epoch);
135240
135242 DUCKDB_API
static int32_t ExtractYear(date_t date);
135244 DUCKDB_API
static int32_t ExtractMonth(date_t date);
135246 DUCKDB_API
static int32_t ExtractDay(date_t date);
135248 DUCKDB_API
static int32_t ExtractISODayOfTheWeek(date_t date);
135250 DUCKDB_API
static int32_t ExtractDayOfTheYear(date_t date);
135252 DUCKDB_API
static int64_t ExtractJulianDay(date_t date);
135258 DUCKDB_API static void ExtractISOYearWeek(date_t date, int32_t &year, int32_t &week);
135259 DUCKDB_API
static int32_t ExtractISOWeekNumber(date_t date);
135260 DUCKDB_API
static int32_t ExtractISOYearNumber(date_t date);
135265 DUCKDB_API
static int32_t ExtractWeekNumberRegular(date_t date,
bool monday_first =
true);
135267 DUCKDB_API static date_t GetMondayOfCurrentWeek(date_t date);
135268
135270 DUCKDB_API static bool ParseDoubleDigit(const char *buf, idx_t len, idx_t &pos, int32_t &result);
135271
135272 DUCKDB_API static string FormatError(const string &str);
135273 DUCKDB_API static string FormatError(string_t str);
135274
135275 DUCKDB_API static string RangeError(const string &str);
135276 DUCKDB_API static string RangeError(string_t str);
135277
135278private:
135279 static void ExtractYearOffset(int32_t &n, int32_t &year, int32_t &year_offset);
135280};
135281
135282}
135283
135284namespace std {
135285
135287template <>
135288struct hash<duckdb::date_t> {
135289 std::size_t
operator()(
const duckdb::date_t &k)
const {
135290 using std::hash;
135291 return hash<int32_t>()((
int32_t)k);
135292 }
135293};
135294}
135295
135296
135297
135298
135299
135300
135301
135302
135303
135304
135305
135306
135307
135308
135309
135310namespace duckdb {
135311
135312struct dtime_t;
135313struct date_t;
135314struct dtime_tz_t;
135315struct timestamp_t;
135316struct TimestampComponents;
135317
135318class Serializer;
135319class Deserializer;
135320
135321struct interval_t {
135325
135326 inline void Normalize(int64_t &months, int64_t &days, int64_t µs) const;
135327
135328
135329 inline static void Borrow(const int64_t msf, int64_t &lsf, int32_t &f, const int64_t scale);
135330 inline interval_t Normalize() const;
135331
135332 inline bool operator==(
const interval_t &right)
const {
135333
135334 const auto &left = *this;
135335 if (left.months == right.months && left.days == right.days && left.micros == right.micros) {
135336 return true;
135337 }
135338
135339 int64_t lmonths, ldays, lmicros;
135340 int64_t rmonths, rdays, rmicros;
135341 left.Normalize(lmonths, ldays, lmicros);
135342 right.Normalize(rmonths, rdays, rmicros);
135343
135344 return lmonths == rmonths && ldays == rdays && lmicros == rmicros;
135345 }
135346 inline bool operator!=(
const interval_t &right)
const {
135347 return !(*this == right);
135348 }
135349
135350 inline bool operator>(
const interval_t &right)
const {
135351 const auto &left = *this;
135352 int64_t lmonths, ldays, lmicros;
135353 int64_t rmonths, rdays, rmicros;
135354 left.Normalize(lmonths, ldays, lmicros);
135355 right.Normalize(rmonths, rdays, rmicros);
135356
135357 if (lmonths > rmonths) {
135358 return true;
135359 } else if (lmonths < rmonths) {
135360 return false;
135361 }
135362 if (ldays > rdays) {
135363 return true;
135364 } else if (ldays < rdays) {
135365 return false;
135366 }
135367 return lmicros > rmicros;
135368 }
135369
135370 inline bool operator<(
const interval_t &right)
const {
135371 return right > *this;
135372 }
135373
135374 inline bool operator<=(
const interval_t &right)
const {
135375 return !(*this > right);
135376 }
135377
135378 inline bool operator>=(
const interval_t &right)
const {
135379 return !(*this < right);
135380 }
135381
135382
135383 void Serialize(Serializer &serializer) const;
135384 static interval_t Deserialize(Deserializer &source);
135385};
135386
135389class Interval {
135390public:
135391 static constexpr const int32_t MONTHS_PER_MILLENIUM = 12000;
135392 static constexpr const int32_t MONTHS_PER_CENTURY = 1200;
135393 static constexpr const int32_t MONTHS_PER_DECADE = 120;
135394 static constexpr const int32_t MONTHS_PER_YEAR = 12;
135395 static constexpr const int32_t MONTHS_PER_QUARTER = 3;
135396 static constexpr const int32_t DAYS_PER_WEEK = 7;
135398 static constexpr const int64_t DAYS_PER_MONTH = 30;
135399 static constexpr const int64_t DAYS_PER_YEAR = 365;
135400 static constexpr const int64_t MSECS_PER_SEC = 1000;
135401 static constexpr const int32_t SECS_PER_MINUTE = 60;
135402 static constexpr const int32_t MINS_PER_HOUR = 60;
135403 static constexpr const int32_t HOURS_PER_DAY = 24;
135404 static constexpr const int32_t SECS_PER_HOUR = SECS_PER_MINUTE * MINS_PER_HOUR;
135405 static constexpr const int32_t SECS_PER_DAY = SECS_PER_HOUR * HOURS_PER_DAY;
135406 static constexpr const int32_t SECS_PER_WEEK = SECS_PER_DAY * DAYS_PER_WEEK;
135407
135408 static constexpr const int64_t MICROS_PER_MSEC = 1000;
135409 static constexpr const int64_t MICROS_PER_SEC = MICROS_PER_MSEC * MSECS_PER_SEC;
135410 static constexpr const int64_t MICROS_PER_MINUTE = MICROS_PER_SEC * SECS_PER_MINUTE;
135411 static constexpr const int64_t MICROS_PER_HOUR = MICROS_PER_MINUTE * MINS_PER_HOUR;
135412 static constexpr const int64_t MICROS_PER_DAY = MICROS_PER_HOUR * HOURS_PER_DAY;
135413 static constexpr const int64_t MICROS_PER_WEEK = MICROS_PER_DAY * DAYS_PER_WEEK;
135414 static constexpr const int64_t MICROS_PER_MONTH = MICROS_PER_DAY * DAYS_PER_MONTH;
135415
135416 static constexpr const int64_t NANOS_PER_MICRO = 1000;
135417 static constexpr const int64_t NANOS_PER_MSEC = NANOS_PER_MICRO * MICROS_PER_MSEC;
135418 static constexpr const int64_t NANOS_PER_SEC = NANOS_PER_MSEC * MSECS_PER_SEC;
135419 static constexpr const int64_t NANOS_PER_MINUTE = NANOS_PER_SEC * SECS_PER_MINUTE;
135420 static constexpr const int64_t NANOS_PER_HOUR = NANOS_PER_MINUTE * MINS_PER_HOUR;
135421 static constexpr const int64_t NANOS_PER_DAY = NANOS_PER_HOUR * HOURS_PER_DAY;
135422 static constexpr const int64_t NANOS_PER_WEEK = NANOS_PER_DAY * DAYS_PER_WEEK;
135423
135424public:
135426 static bool FromString(const string &str, interval_t &result);
135428 static bool FromCString(const char *str, idx_t len, interval_t &result, string *error_message, bool strict);
135430 static string ToString(const interval_t &val);
135431
135433 DUCKDB_API static interval_t FromMicro(int64_t micros);
135434
135436 static int64_t GetMilli(
const interval_t &val);
135437
135439 static bool TryGetMicro(const interval_t &val, int64_t µs);
135440 static int64_t GetMicro(
const interval_t &val);
135441
135443 static int64_t GetNanoseconds(
const interval_t &val);
135444
135446 static interval_t GetAge(timestamp_t timestamp_1, timestamp_t timestamp_2);
135448 static interval_t GetAge(TimestampComponents ts1, TimestampComponents ts2, bool is_negative);
135449
135451 static interval_t GetDifference(timestamp_t timestamp_1, timestamp_t timestamp_2);
135452
135454 static interval_t Invert(interval_t interval);
135455
135457 static date_t Add(date_t left, interval_t right);
135459 static timestamp_t Add(timestamp_t left, interval_t right);
135462 static dtime_t Add(dtime_t left, interval_t right, date_t &date);
135463 static dtime_tz_t Add(dtime_tz_t left, interval_t right, date_t &date);
135464
135466 inline static bool Equals(const interval_t &left, const interval_t &right) {
135467 return left == right;
135468 }
135469 inline static bool GreaterThan(const interval_t &left, const interval_t &right) {
135470 return left > right;
135471 }
135472};
135473
135474void interval_t::Normalize(int64_t &months, int64_t &days, int64_t µs) const {
135475 auto &input = *this;
135476
135477
135478 micros = input.micros;
135479 int64_t carry_days = micros / Interval::MICROS_PER_DAY;
135480 micros -= carry_days * Interval::MICROS_PER_DAY;
135481
135482 days = input.days;
135483 days += carry_days;
135484 int64_t carry_months = days / Interval::DAYS_PER_MONTH;
135485 days -= carry_months * Interval::DAYS_PER_MONTH;
135486
135487 months = input.months;
135488 months += carry_months;
135489}
135490
135491void interval_t::Borrow(const int64_t msf, int64_t &lsf, int32_t &f, const int64_t scale) {
135492 if (msf > NumericLimits<int32_t>::Maximum()) {
135493 f = NumericLimits<int32_t>::Maximum();
135494 lsf += (msf - f) * scale;
135495 } else if (msf < NumericLimits<int32_t>::Minimum()) {
135496 f = NumericLimits<int32_t>::Minimum();
135497 lsf += (msf - f) * scale;
135498 } else {
135499 f = UnsafeNumericCast<int32_t>(msf);
135500 }
135501}
135502
135503interval_t interval_t::Normalize() const {
135504 interval_t result;
135505
135508 Normalize(mm, dd, result.micros);
135509
135510
135511 Borrow(mm, dd, result.months, Interval::DAYS_PER_MONTH);
135512 Borrow(dd, result.micros, result.days, Interval::MICROS_PER_DAY);
135513
135514 return result;
135515}
135516
135517}
135518
135519namespace std {
135520template <>
135521struct hash<duckdb::interval_t> {
135522 size_t operator()(
const duckdb::interval_t &val)
const {
135523 int64_t months, days, micros;
135524 val.Normalize(months, days, micros);
135525 using std::hash;
135526
135527 return hash<int32_t> {}(duckdb::UnsafeNumericCast<int32_t>(days)) ^
135528 hash<int32_t> {}(duckdb::UnsafeNumericCast<int32_t>(months)) ^ hash<int64_t> {}(micros);
135529 }
135530};
135531}
135532
135533
135534
135535
135536
135537
135538
135539
135540
135541
135542
135543
135544
135545
135546
135547
135548
135549
135550
135551
135552
135553
135554
135555
135556
135557
135558
135559
135560
135561
135562
135563
135564
135565#include <unordered_set>
135566
135567namespace duckdb {
135568using std::unordered_set;
135569}
135570
135571
135572
135573
135574
135575
135576
135577
135578
135579
135580
135581
135582
135583
135584#include <map>
135585
135586namespace duckdb {
135587using std::map;
135588using std::multimap;
135589}
135590
135591
135592namespace duckdb {
135593
135594struct CaseInsensitiveStringHashFunction {
135597 }
135598};
135599
135600struct CaseInsensitiveStringEquality {
135601 bool operator()(
const string &a,
const string &b)
const {
135603 }
135604};
135605
135606template <typename T>
135607using case_insensitive_map_t =
135608 unordered_map<string, T, CaseInsensitiveStringHashFunction, CaseInsensitiveStringEquality>;
135609
135610using case_insensitive_set_t = unordered_set<string, CaseInsensitiveStringHashFunction, CaseInsensitiveStringEquality>;
135611
135612struct CaseInsensitiveStringCompare {
135613 bool operator()(
const string &s1,
const string &s2)
const {
135615 }
135616};
135617
135618template <typename T>
135619using case_insensitive_tree_t = map<string, T, CaseInsensitiveStringCompare>;
135620
135621}
135622
135623
135624
135625
135626
135627
135628
135629
135630namespace duckdb {
135631
135632template <typename V>
135633class InsertionOrderPreservingMap {
135634public:
135635 typedef vector<pair<string, V>> VECTOR_TYPE;
135636 typedef string key_type;
135637
135638public:
135639 InsertionOrderPreservingMap() {
135640 }
135641
135642private:
135643 VECTOR_TYPE map;
135644 case_insensitive_map_t<idx_t> map_idx;
135645
135646public:
135647 vector<string> Keys() const {
135648 vector<string> keys;
135649 keys.resize(this->
size());
135650 for (auto &kv : map_idx) {
135651 keys[kv.second] = kv.first;
135652 }
135653
135654 return keys;
135655 }
135656
135657 typename VECTOR_TYPE::iterator begin() {
135658 return map.begin();
135659 }
135660
135661 typename VECTOR_TYPE::iterator end() {
135662 return map.end();
135663 }
135664
135665 typename VECTOR_TYPE::const_iterator begin() const {
135666 return map.begin();
135667 }
135668
135669 typename VECTOR_TYPE::const_iterator end() const {
135670 return map.end();
135671 }
135672
135673 typename VECTOR_TYPE::reverse_iterator rbegin() {
135674 return map.rbegin();
135675 }
135676
135677 typename VECTOR_TYPE::reverse_iterator rend() {
135678 return map.rend();
135679 }
135680
135681 typename VECTOR_TYPE::iterator find(const string &key) {
135682 auto entry = map_idx.find(key);
135683 if (entry == map_idx.end()) {
135684 return map.end();
135685 }
135686 return map.begin() + static_cast<typename VECTOR_TYPE::difference_type>(entry->second);
135687 }
135688
135689 typename VECTOR_TYPE::const_iterator find(const string &key) const {
135690 auto entry = map_idx.find(key);
135691 if (entry == map_idx.end()) {
135692 return map.end();
135693 }
135694 return map.begin() + static_cast<typename VECTOR_TYPE::difference_type>(entry->second);
135695 }
135696
135698 return map_idx.size();
135699 }
135700
135701 bool empty() const {
135702 return map_idx.empty();
135703 }
135704
135705 void resize(idx_t nz) {
135706 map.resize(nz);
135707 }
135708
135709 void clear() {
135710 map.clear();
135711 }
135712
135713 void insert(const string &key, V &&value) {
135714 if (contains(key)) {
135715 return;
135716 }
135717 map.emplace_back(key, std::move(value));
135718 map_idx[key] = map.size() - 1;
135719 }
135720
135721 void insert(const string &key, const V &value) {
135722 if (contains(key)) {
135723 return;
135724 }
135725 map.emplace_back(key, value);
135726 map_idx[key] = map.size() - 1;
135727 }
135728
135729 void insert(pair<string, V> &&value) {
135730 auto &key = value.first;
135731 if (contains(key)) {
135732 return;
135733 }
135734 map_idx[key] = map.size();
135735 map.push_back(std::move(value));
135736 }
135737
135738 void erase(typename VECTOR_TYPE::iterator it) {
135739 auto key = it->first;
135740 auto idx = map_idx[key];
135741 map.erase(it);
135742 map_idx.erase(key);
135743 for (auto &kv : map_idx) {
135744 if (kv.second > idx) {
135745 kv.second--;
135746 }
135747 }
135748 }
135749
135750 bool contains(const string &key) const {
135751 return map_idx.find(key) != map_idx.end();
135752 }
135753
135754 const V &
at(
const string &key)
const {
135755 return map[map_idx.at(key)].second;
135756 }
135757
135758 V &operator[](const string &key) {
135759 if (!contains(key)) {
135761 insert(key, std::move(
v));
135762 }
135763 return map[map_idx[key]].second;
135764 }
135765
135766 bool operator==(
const InsertionOrderPreservingMap &other)
const {
135767 return map == other.map && map_idx == other.map_idx;
135768 }
135769
135770 bool operator!=(
const InsertionOrderPreservingMap &other)
const {
135771 return !(*this == other);
135772 }
135773};
135774
135775}
135776
135777
135778namespace duckdb {
135779
135781class CastFunctionSet;
135782struct GetCastFunctionInput;
135783struct ExtraValueInfo;
135784
135787class Value {
135788 friend struct StringValue;
135789 friend struct StructValue;
135790 friend struct ListValue;
135791 friend struct UnionValue;
135792 friend struct ArrayValue;
135793 friend struct MapValue;
135794 friend struct TypeValue;
135795
135796public:
135798 DUCKDB_API explicit Value(LogicalType type = LogicalType::SQLNULL);
135800 DUCKDB_API Value(int32_t val);
135802 explicit DUCKDB_API Value(bool val);
135804 DUCKDB_API Value(int64_t val);
135806 DUCKDB_API Value(float val);
135808 DUCKDB_API Value(double val);
135810 DUCKDB_API Value(const char *val);
135812 DUCKDB_API Value(std::nullptr_t val);
135814 DUCKDB_API Value(string_t val);
135816 DUCKDB_API Value(string val);
135818 DUCKDB_API Value(
String val);
135820 DUCKDB_API Value(const Value &other);
135822 DUCKDB_API Value(Value &&other) noexcept;
135824 DUCKDB_API ~Value();
135825
135826
135827 DUCKDB_API Value &
operator=(
const Value &other);
135828
135829 DUCKDB_API Value &
operator=(Value &&other)
noexcept;
135830
135831 inline LogicalType &GetTypeMutable() {
135832 return type_;
135833 }
135834 inline const LogicalType &type() const {
135835 return type_;
135836 }
135837 inline bool IsNull() const {
135838 return is_null;
135839 }
135840
135842 DUCKDB_API static Value MinimumValue(const LogicalType &type);
135844 DUCKDB_API static Value MaximumValue(const LogicalType &type);
135846 DUCKDB_API static Value NegativeInfinity(const LogicalType &type);
135848 DUCKDB_API static Value Infinity(const LogicalType &type);
135850 DUCKDB_API static Value Numeric(const LogicalType &type, int64_t value);
135851 DUCKDB_API static Value Numeric(const LogicalType &type, hugeint_t value);
135852 DUCKDB_API static Value Numeric(const LogicalType &type, uhugeint_t value);
135853
135855 DUCKDB_API
static Value
BOOLEAN(
bool value);
135857 DUCKDB_API static Value TINYINT(int8_t value);
135859 DUCKDB_API static Value SMALLINT(int16_t value);
135861 DUCKDB_API static Value INTEGER(int32_t value);
135863 DUCKDB_API static Value BIGINT(int64_t value);
135865 DUCKDB_API static Value UTINYINT(uint8_t value);
135867 DUCKDB_API static Value USMALLINT(uint16_t value);
135869 DUCKDB_API static Value UINTEGER(uint32_t value);
135871 DUCKDB_API static Value UBIGINT(uint64_t value);
135873 DUCKDB_API static Value HUGEINT(hugeint_t value);
135875 DUCKDB_API static Value UHUGEINT(uhugeint_t value);
135877 DUCKDB_API static Value UUID(const string &value);
135879 DUCKDB_API static Value UUID(hugeint_t value);
135881 DUCKDB_API static Value HASH(hash_t value);
135883 DUCKDB_API static Value POINTER(uintptr_t value);
135885 DUCKDB_API static Value DATE(date_t date);
135887 DUCKDB_API static Value DATE(int32_t year, int32_t month, int32_t day);
135889 DUCKDB_API static Value TIME(dtime_t time);
135890 DUCKDB_API static Value TIME_NS(dtime_ns_t time);
135891 DUCKDB_API static Value TIMETZ(dtime_tz_t time);
135893 DUCKDB_API
static Value TIME(int32_t hour, int32_t
min, int32_t sec, int32_t micros);
135895 DUCKDB_API static Value TIMESTAMP(date_t date, dtime_t time);
135897 DUCKDB_API static Value TIMESTAMP(timestamp_t timestamp);
135899 DUCKDB_API static Value TIMESTAMPSEC(timestamp_sec_t timestamp);
135901 DUCKDB_API static Value TIMESTAMPMS(timestamp_ms_t timestamp);
135903 DUCKDB_API static Value TIMESTAMPNS(timestamp_ns_t timestamp);
135905 DUCKDB_API static Value TIMESTAMPTZ(timestamp_tz_t timestamp);
135907 DUCKDB_API
static Value TIMESTAMP(int32_t year, int32_t month, int32_t day, int32_t hour, int32_t
min, int32_t sec,
135908 int32_t micros);
135909 DUCKDB_API static Value INTERVAL(int32_t months, int32_t days, int64_t micros);
135910 DUCKDB_API static Value INTERVAL(interval_t interval);
135911
135912
135913 DUCKDB_API static Value ENUM(uint64_t value, const LogicalType &original_type);
135914
135915
135916 DUCKDB_API static Value DECIMAL(int16_t value, uint8_t width, uint8_t scale);
135917 DUCKDB_API static Value DECIMAL(int32_t value, uint8_t width, uint8_t scale);
135918 DUCKDB_API static Value DECIMAL(int64_t value, uint8_t width, uint8_t scale);
135919 DUCKDB_API static Value DECIMAL(hugeint_t value, uint8_t width, uint8_t scale);
135921 DUCKDB_API
static Value
FLOAT(
float value);
135923 DUCKDB_API
static Value
DOUBLE(
double value);
135925 DUCKDB_API static Value STRUCT(child_list_t<Value> values);
135926 DUCKDB_API static Value STRUCT(const LogicalType &type, vector<Value> struct_values);
135928 DUCKDB_API static Value VARIANT(vector<Value> children);
135930 DUCKDB_API
static Value
LIST(
const LogicalType &child_type, vector<Value> values);
135933 DUCKDB_API
static Value
LIST(vector<Value> values);
135934
135935 DUCKDB_API static Value ARRAY(const LogicalType &type, vector<Value> values);
135937 DUCKDB_API static Value MAP(const LogicalType &child_type, vector<Value> values);
135939 DUCKDB_API
static Value MAP(
const LogicalType &key_type,
const LogicalType &
value_type, vector<Value> keys,
135940 vector<Value> values);
135942 DUCKDB_API static Value MAP(const InsertionOrderPreservingMap<string> &kv_pairs);
135943
135945 DUCKDB_API static Value UNION(child_list_t<LogicalType> members, uint8_t tag, Value value);
135946
135948 DUCKDB_API static Value BLOB(const_data_ptr_t data, idx_t len);
135949 static Value BLOB_RAW(const string &data) {
135950 return Value::BLOB(const_data_ptr_cast(data.c_str()), data.size());
135951 }
135953 DUCKDB_API static Value BLOB(const string &data);
135955 DUCKDB_API static Value BIT(const_data_ptr_t data, idx_t len);
135956 DUCKDB_API static Value BIT(const string &data);
135957 DUCKDB_API static Value BIGNUM(const_data_ptr_t data, idx_t len);
135958 DUCKDB_API static Value BIGNUM(const string &data);
135959
135960 DUCKDB_API static Value GEOMETRY(const_data_ptr_t data, idx_t len);
135961 DUCKDB_API static Value GEOMETRY(const_data_ptr_t data, idx_t len, const CoordinateReferenceSystem &crs);
135962
135963 DUCKDB_API
static Value
TYPE(
const LogicalType &type);
135964 DUCKDB_API
static Value
TYPE(
const string_t &serialized_type);
135965
135967 DUCKDB_API static Value AGGREGATE_STATE(const LogicalType &type, const_data_ptr_t data, idx_t len);
135968
135969 template <class T>
135970 T GetValue() const;
135971 template <class T>
135972 static Value CreateValue(T value) {
135973 static_assert(AlwaysFalse<T>::VALUE, "No specialization exists for this type");
135974 return Value(nullptr);
135975 }
135976
135977
135978 template <class T>
135979 T GetValueUnsafe() const;
135980
135982 Value Copy() const {
135983 return Value(*this);
135984 }
135985
135987 DUCKDB_API
hash_t Hash()
const;
135989 DUCKDB_API string ToString() const;
135991 DUCKDB_API string ToSQLString() const;
135992
135993 DUCKDB_API uintptr_t GetPointer() const;
135994
135996 DUCKDB_API Value CastAs(CastFunctionSet &set, GetCastFunctionInput &get_input, const LogicalType &target_type,
135997 bool strict = false) const;
135998 DUCKDB_API Value CastAs(ClientContext &context, const LogicalType &target_type, bool strict = false) const;
135999 DUCKDB_API Value DefaultCastAs(const LogicalType &target_type, bool strict = false) const;
136001 DUCKDB_API bool TryCastAs(CastFunctionSet &set, GetCastFunctionInput &get_input, const LogicalType &target_type,
136002 Value &new_value, string *error_message, bool strict = false) const;
136003 DUCKDB_API bool TryCastAs(ClientContext &context, const LogicalType &target_type, Value &new_value,
136004 string *error_message, bool strict = false) const;
136005 DUCKDB_API bool DefaultTryCastAs(const LogicalType &target_type, Value &new_value, string *error_message,
136006 bool strict = false) const;
136008 DUCKDB_API bool TryCastAs(CastFunctionSet &set, GetCastFunctionInput &get_input, const LogicalType &target_type,
136009 bool strict = false);
136010 DUCKDB_API bool TryCastAs(ClientContext &context, const LogicalType &target_type, bool strict = false);
136011 DUCKDB_API bool DefaultTryCastAs(const LogicalType &target_type, bool strict = false);
136012
136013 DUCKDB_API void Reinterpret(LogicalType new_type);
136014
136016 DUCKDB_API void Serialize(Serializer &serializer) const;
136018 DUCKDB_API static Value Deserialize(Deserializer &deserializer);
136019
136020
136021
136022
136023 DUCKDB_API
bool operator==(
const Value &rhs)
const;
136024 DUCKDB_API
bool operator!=(
const Value &rhs)
const;
136025 DUCKDB_API
bool operator<(
const Value &rhs)
const;
136026 DUCKDB_API
bool operator>(
const Value &rhs)
const;
136027 DUCKDB_API
bool operator<=(
const Value &rhs)
const;
136028 DUCKDB_API
bool operator>=(
const Value &rhs)
const;
136029
136030 DUCKDB_API
bool operator==(
const int64_t &rhs)
const;
136031 DUCKDB_API
bool operator!=(
const int64_t &rhs)
const;
136032 DUCKDB_API
bool operator<(
const int64_t &rhs)
const;
136033 DUCKDB_API
bool operator>(
const int64_t &rhs)
const;
136034 DUCKDB_API
bool operator<=(
const int64_t &rhs)
const;
136035 DUCKDB_API
bool operator>=(
const int64_t &rhs)
const;
136036
136037 DUCKDB_API static bool FloatIsFinite(float value);
136038 DUCKDB_API static bool DoubleIsFinite(double value);
136039 template <class T>
136040 static bool IsNan(T value) {
136041 throw InternalException("Unimplemented template type for Value::IsNan");
136042 }
136043 template <class T>
136044 static bool IsFinite(T value) {
136045 return true;
136046 }
136047 DUCKDB_API static bool StringIsValid(const char *str, idx_t length);
136048 static bool StringIsValid(const string &str) {
136049 return StringIsValid(str.c_str(), str.size());
136050 }
136051
136054 DUCKDB_API static bool ValuesAreEqual(CastFunctionSet &set, GetCastFunctionInput &get_input,
136055 const Value &result_value, const Value &value);
136056 DUCKDB_API static bool ValuesAreEqual(ClientContext &context, const Value &result_value, const Value &value);
136057 DUCKDB_API static bool DefaultValuesAreEqual(const Value &result_value, const Value &value);
136059 DUCKDB_API static bool NotDistinctFrom(const Value &lvalue, const Value &rvalue);
136060
136061 friend std::ostream &
operator<<(std::ostream &out,
const Value &val) {
136063 return out;
136064 }
136065 DUCKDB_API void Print() const;
136066
136067private:
136068 void SerializeInternal(Serializer &serializer, bool serialize_type) const;
136069 static void SerializeChildren(Serializer &serializer, const vector<Value> &children,
136070 const LogicalType &parent_type);
136071
136072private:
136074 LogicalType type_;
136075
136077 bool is_null;
136078
136080 union Val {
136081 bool boolean;
136090 hugeint_t hugeint;
136091 uhugeint_t uhugeint;
136092 float float_;
136093 double double_;
136094 uintptr_t pointer;
136096 date_t date;
136097 dtime_t time;
136098 dtime_ns_t time_ns;
136099 dtime_tz_t timetz;
136101 timestamp_sec_t timestamp_s;
136102 timestamp_ms_t timestamp_ms;
136103 timestamp_ns_t timestamp_ns;
136104 timestamp_tz_t timestamp_tz;
136105 interval_t interval;
136106 } value_;
136107
136108 shared_ptr<ExtraValueInfo> value_info_;
136109
136110private:
136111 template <class T>
136112 T GetValueInternal() const;
136113};
136114
136115
136116
136117
136118
136119
136120struct BooleanValue {
136121 DUCKDB_API static bool Get(const Value &value);
136122};
136123
136124struct TinyIntValue {
136125 DUCKDB_API
static int8_t Get(
const Value &value);
136126};
136127
136128struct SmallIntValue {
136129 DUCKDB_API
static int16_t Get(
const Value &value);
136130};
136131
136132struct IntegerValue {
136133 DUCKDB_API
static int32_t Get(
const Value &value);
136134};
136135
136136struct BigIntValue {
136137 DUCKDB_API
static int64_t Get(
const Value &value);
136138};
136139
136140struct HugeIntValue {
136141 DUCKDB_API static hugeint_t Get(const Value &value);
136142};
136143
136144struct UTinyIntValue {
136145 DUCKDB_API
static uint8_t Get(
const Value &value);
136146};
136147
136148struct USmallIntValue {
136149 DUCKDB_API
static uint16_t Get(
const Value &value);
136150};
136151
136152struct UIntegerValue {
136153 DUCKDB_API
static uint32_t Get(
const Value &value);
136154};
136155
136156struct UBigIntValue {
136157 DUCKDB_API
static uint64_t Get(
const Value &value);
136158};
136159
136160struct UhugeIntValue {
136161 DUCKDB_API static uhugeint_t Get(const Value &value);
136162};
136163
136164struct FloatValue {
136165 DUCKDB_API static float Get(const Value &value);
136166};
136167
136168struct DoubleValue {
136169 DUCKDB_API static double Get(const Value &value);
136170};
136171
136172struct StringValue {
136173 DUCKDB_API static const string &Get(const Value &value);
136174};
136175
136176struct DateValue {
136177 DUCKDB_API static date_t Get(const Value &value);
136178};
136179
136180struct TimeValue {
136181 DUCKDB_API static dtime_t Get(const Value &value);
136182};
136183
136184struct TimestampValue {
136185 DUCKDB_API static timestamp_t Get(const Value &value);
136186};
136187
136188struct TimestampSValue {
136189 DUCKDB_API static timestamp_sec_t Get(const Value &value);
136190};
136191
136192struct TimestampMSValue {
136193 DUCKDB_API static timestamp_ms_t Get(const Value &value);
136194};
136195
136196struct TimestampNSValue {
136197 DUCKDB_API static timestamp_ns_t Get(const Value &value);
136198};
136199
136200struct TimestampTZValue {
136201 DUCKDB_API static timestamp_tz_t Get(const Value &value);
136202};
136203
136204struct IntervalValue {
136205 DUCKDB_API static interval_t Get(const Value &value);
136206};
136207
136208struct StructValue {
136209 DUCKDB_API static const vector<Value> &GetChildren(const Value &value);
136210};
136211
136212struct MapValue {
136213 DUCKDB_API static const vector<Value> &GetChildren(const Value &value);
136214};
136215
136216struct ListValue {
136217 DUCKDB_API static const vector<Value> &GetChildren(const Value &value);
136218};
136219
136220struct ArrayValue {
136221 DUCKDB_API static const vector<Value> &GetChildren(const Value &value);
136222};
136223
136224struct UnionValue {
136225 DUCKDB_API static const Value &GetValue(const Value &value);
136226 DUCKDB_API
static uint8_t GetTag(
const Value &value);
136227 DUCKDB_API static const LogicalType &GetType(const Value &value);
136228};
136229
136230struct TypeValue {
136231 DUCKDB_API static LogicalType GetType(const Value &value);
136232};
136233
136236struct IntegralValue {
136237 static hugeint_t Get(const Value &value);
136238};
136239
136240template <>
136241Value DUCKDB_API Value::CreateValue(bool value);
136242template <>
136243Value DUCKDB_API Value::CreateValue(uint8_t value);
136244template <>
136245Value DUCKDB_API Value::CreateValue(uint16_t value);
136246template <>
136247Value DUCKDB_API Value::CreateValue(uint32_t value);
136248template <>
136249Value DUCKDB_API Value::CreateValue(uint64_t value);
136250template <>
136251Value DUCKDB_API Value::CreateValue(int8_t value);
136252template <>
136253Value DUCKDB_API Value::CreateValue(int16_t value);
136254template <>
136255Value DUCKDB_API Value::CreateValue(int32_t value);
136256template <>
136257Value DUCKDB_API Value::CreateValue(int64_t value);
136258template <>
136259Value DUCKDB_API Value::CreateValue(hugeint_t value);
136260template <>
136261Value DUCKDB_API Value::CreateValue(uhugeint_t value);
136262template <>
136263Value DUCKDB_API Value::CreateValue(date_t value);
136264template <>
136265Value DUCKDB_API Value::CreateValue(dtime_t value);
136266template <>
136267Value DUCKDB_API Value::CreateValue(dtime_ns_t value);
136268template <>
136269Value DUCKDB_API Value::CreateValue(dtime_tz_t value);
136270template <>
136271Value DUCKDB_API Value::CreateValue(timestamp_t value);
136272template <>
136273Value DUCKDB_API Value::CreateValue(timestamp_sec_t value);
136274template <>
136275Value DUCKDB_API Value::CreateValue(timestamp_ms_t value);
136276template <>
136277Value DUCKDB_API Value::CreateValue(timestamp_ns_t value);
136278template <>
136279Value DUCKDB_API Value::CreateValue(timestamp_tz_t value);
136280template <>
136281Value DUCKDB_API Value::CreateValue(const char *value);
136282template <>
136283Value DUCKDB_API Value::CreateValue(string value);
136284template <>
136285Value DUCKDB_API Value::CreateValue(string_t value);
136286template <>
136287Value DUCKDB_API Value::CreateValue(float value);
136288template <>
136289Value DUCKDB_API Value::CreateValue(double value);
136290template <>
136291Value DUCKDB_API Value::CreateValue(interval_t value);
136292template <>
136293Value DUCKDB_API Value::CreateValue(Value value);
136294
136295template <>
136296DUCKDB_API bool Value::GetValue() const;
136297template <>
136298DUCKDB_API
int8_t Value::GetValue()
const;
136299template <>
136300DUCKDB_API
int16_t Value::GetValue()
const;
136301template <>
136302DUCKDB_API
int32_t Value::GetValue()
const;
136303template <>
136304DUCKDB_API
int64_t Value::GetValue()
const;
136305template <>
136306DUCKDB_API
uint8_t Value::GetValue()
const;
136307template <>
136308DUCKDB_API
uint16_t Value::GetValue()
const;
136309template <>
136310DUCKDB_API
uint32_t Value::GetValue()
const;
136311template <>
136312DUCKDB_API
uint64_t Value::GetValue()
const;
136313template <>
136314DUCKDB_API hugeint_t Value::GetValue() const;
136315template <>
136316DUCKDB_API uhugeint_t Value::GetValue() const;
136317template <>
136318DUCKDB_API string Value::GetValue() const;
136319template <>
136320DUCKDB_API float Value::GetValue() const;
136321template <>
136322DUCKDB_API double Value::GetValue() const;
136323template <>
136324DUCKDB_API date_t Value::GetValue() const;
136325template <>
136326DUCKDB_API dtime_t Value::GetValue() const;
136327template <>
136328DUCKDB_API dtime_ns_t Value::GetValue() const;
136329template <>
136330DUCKDB_API dtime_tz_t Value::GetValue() const;
136331template <>
136332DUCKDB_API timestamp_t Value::GetValue() const;
136333template <>
136334DUCKDB_API timestamp_sec_t Value::GetValue() const;
136335template <>
136336DUCKDB_API timestamp_ms_t Value::GetValue() const;
136337template <>
136338DUCKDB_API timestamp_ns_t Value::GetValue() const;
136339template <>
136340DUCKDB_API timestamp_tz_t Value::GetValue() const;
136341template <>
136342DUCKDB_API interval_t Value::GetValue() const;
136343template <>
136344DUCKDB_API Value Value::GetValue() const;
136345
136346template <>
136347DUCKDB_API bool Value::GetValueUnsafe() const;
136348template <>
136349DUCKDB_API
int8_t Value::GetValueUnsafe()
const;
136350template <>
136351DUCKDB_API
int16_t Value::GetValueUnsafe()
const;
136352template <>
136353DUCKDB_API
int32_t Value::GetValueUnsafe()
const;
136354template <>
136355DUCKDB_API
int64_t Value::GetValueUnsafe()
const;
136356template <>
136357DUCKDB_API hugeint_t Value::GetValueUnsafe() const;
136358template <>
136359DUCKDB_API uhugeint_t Value::GetValueUnsafe() const;
136360template <>
136361DUCKDB_API
uint8_t Value::GetValueUnsafe()
const;
136362template <>
136363DUCKDB_API
uint16_t Value::GetValueUnsafe()
const;
136364template <>
136365DUCKDB_API
uint32_t Value::GetValueUnsafe()
const;
136366template <>
136367DUCKDB_API
uint64_t Value::GetValueUnsafe()
const;
136368template <>
136369DUCKDB_API string Value::GetValueUnsafe() const;
136370template <>
136371DUCKDB_API string_t Value::GetValueUnsafe() const;
136372template <>
136373DUCKDB_API float Value::GetValueUnsafe() const;
136374template <>
136375DUCKDB_API double Value::GetValueUnsafe() const;
136376template <>
136377DUCKDB_API date_t Value::GetValueUnsafe() const;
136378template <>
136379DUCKDB_API dtime_t Value::GetValueUnsafe() const;
136380template <>
136381DUCKDB_API dtime_ns_t Value::GetValueUnsafe() const;
136382template <>
136383DUCKDB_API dtime_tz_t Value::GetValueUnsafe() const;
136384template <>
136385DUCKDB_API timestamp_t Value::GetValueUnsafe() const;
136386template <>
136387DUCKDB_API timestamp_sec_t Value::GetValueUnsafe() const;
136388template <>
136389DUCKDB_API timestamp_ms_t Value::GetValueUnsafe() const;
136390template <>
136391DUCKDB_API timestamp_ns_t Value::GetValueUnsafe() const;
136392template <>
136393DUCKDB_API timestamp_tz_t Value::GetValueUnsafe() const;
136394template <>
136395DUCKDB_API interval_t Value::GetValueUnsafe() const;
136396
136397template <>
136398DUCKDB_API bool Value::IsNan(float input);
136399template <>
136400DUCKDB_API bool Value::IsNan(double input);
136401
136402template <>
136403DUCKDB_API bool Value::IsFinite(float input);
136404template <>
136405DUCKDB_API bool Value::IsFinite(double input);
136406template <>
136407DUCKDB_API bool Value::IsFinite(date_t input);
136408template <>
136409DUCKDB_API bool Value::IsFinite(timestamp_t input);
136410template <>
136411DUCKDB_API bool Value::IsFinite(timestamp_sec_t input);
136412template <>
136413DUCKDB_API bool Value::IsFinite(timestamp_ms_t input);
136414template <>
136415DUCKDB_API bool Value::IsFinite(timestamp_ns_t input);
136416template <>
136417DUCKDB_API bool Value::IsFinite(timestamp_tz_t input);
136418
136419}
136420
136421#include <memory>
136422
136423namespace duckdb {
136424
136425class Catalog;
136426class CatalogSet;
136427class ClientContext;
136428class Deserializer;
136429class SchemaCatalogEntry;
136430class Serializer;
136431class Value;
136432
136433struct AlterInfo;
136434struct CatalogTransaction;
136435struct CreateInfo;
136436
136438class CatalogEntry {
136439public:
136440 CatalogEntry(CatalogType type, Catalog &catalog, string name);
136441 CatalogEntry(CatalogType type, string name, idx_t oid);
136442 virtual ~CatalogEntry();
136443
136447 CatalogType type;
136449 optional_ptr<CatalogSet> set;
136451 string name;
136453 bool deleted;
136455 bool temporary;
136457 bool internal;
136461 Value comment;
136463 InsertionOrderPreservingMap<string> tags;
136464
136465private:
136467 unique_ptr<CatalogEntry> child;
136469 optional_ptr<CatalogEntry> parent;
136470
136471public:
136472 virtual unique_ptr<CatalogEntry> AlterEntry(ClientContext &context, AlterInfo &info);
136473 virtual unique_ptr<CatalogEntry> AlterEntry(CatalogTransaction transaction, AlterInfo &info);
136474 virtual void UndoAlter(ClientContext &context, AlterInfo &info);
136475 virtual void Rollback(CatalogEntry &prev_entry);
136476 virtual void OnDrop();
136477
136478 virtual unique_ptr<CatalogEntry> Copy(ClientContext &context) const;
136479
136480 virtual unique_ptr<CreateInfo> GetInfo() const;
136481
136483
136484 virtual void SetAsRoot();
136485
136487 virtual string ToSQL() const;
136488
136489 virtual Catalog &ParentCatalog();
136490 virtual const Catalog &ParentCatalog() const;
136491 virtual SchemaCatalogEntry &ParentSchema();
136492 virtual const SchemaCatalogEntry &ParentSchema() const;
136493
136494 virtual void Verify(Catalog &catalog);
136495
136496 void Serialize(Serializer &serializer) const;
136497 static unique_ptr<CreateInfo> Deserialize(Deserializer &deserializer);
136498
136499public:
136500 void SetChild(unique_ptr<CatalogEntry> child);
136501 unique_ptr<CatalogEntry> TakeChild();
136502 bool HasChild() const;
136503 bool HasParent() const;
136504 CatalogEntry &Child();
136505 CatalogEntry &Parent();
136506 const CatalogEntry &Parent() const;
136507
136508public:
136509 template <class TARGET>
136510 TARGET &Cast() {
136511 DynamicCastCheck<TARGET>(this);
136512 return reinterpret_cast<TARGET &>(*this);
136513 }
136514 template <class TARGET>
136515 const TARGET &Cast() const {
136516 DynamicCastCheck<TARGET>(this);
136517 return reinterpret_cast<const TARGET &>(*this);
136518 }
136519};
136520
136521class InCatalogEntry : public CatalogEntry {
136522public:
136523 InCatalogEntry(CatalogType type, Catalog &catalog, string name);
136524 ~InCatalogEntry() override;
136525
136527 Catalog &catalog;
136528
136529public:
136530 Catalog &ParentCatalog() override {
136531 return catalog;
136532 }
136533 const Catalog &ParentCatalog() const override {
136534 return catalog;
136535 }
136536
136537 void Verify(Catalog &catalog) override;
136538};
136539
136540}
136541
136542
136543
136544
136545
136546
136547
136548
136549
136550
136551
136552
136553
136554
136555namespace duckdb {
136556class Catalog;
136557class ClientContext;
136558class DatabaseInstance;
136559class Transaction;
136560
136561struct CatalogTransaction {
136562 CatalogTransaction(Catalog &catalog, ClientContext &context);
136563 CatalogTransaction(DatabaseInstance &db, transaction_t transaction_id_p, transaction_t start_time_p);
136564
136565 optional_ptr<DatabaseInstance>
db;
136566 optional_ptr<ClientContext> context;
136567 optional_ptr<Transaction> transaction;
136570
136571 bool HasContext() const {
136572 return context;
136573 }
136574 ClientContext &GetContext();
136575
136576 static CatalogTransaction GetSystemCatalogTransaction(ClientContext &context);
136577 static CatalogTransaction GetSystemTransaction(DatabaseInstance &db);
136578};
136579
136580}
136581
136582
136583
136584
136585
136586
136587
136588
136589
136590
136591
136592
136593
136594
136595namespace duckdb {
136596
136598
136599
136600
136602
136603}
136604
136605
136606
136607
136608
136609
136610
136611
136612
136613
136614
136615
136616
136617namespace duckdb {
136618
136619enum class OnEntryNotFound :
uint8_t { THROW_EXCEPTION = 0, RETURN_NULL = 1 };
136620
136621}
136622
136623
136624
136625
136626
136627
136628
136629
136630
136631
136632
136633
136634
136635
136636namespace duckdb {
136637class ParsedExpression;
136638class TableRef;
136639
136640class ErrorData {
136641public:
136643 DUCKDB_API ErrorData();
136645 DUCKDB_API ErrorData(const std::exception &ex);
136647 DUCKDB_API ErrorData(ExceptionType type, const string &raw_message);
136649 DUCKDB_API explicit ErrorData(const string &raw_message);
136650
136651public:
136653 [[noreturn]] DUCKDB_API void Throw(const string &prepended_message = "") const;
136655 DUCKDB_API const ExceptionType &Type() const;
136657 DUCKDB_API const string &Message() const {
136658 return final_message;
136659 }
136660 DUCKDB_API const string &RawMessage() const {
136661 return raw_message;
136662 }
136663 DUCKDB_API void Merge(const ErrorData &other);
136664 DUCKDB_API
bool operator==(
const ErrorData &other)
const;
136665
136667 inline bool HasError() const {
136668 return initialized;
136669 }
136670 const unordered_map<string, string> &ExtraInfo() const {
136671 return extra_info;
136672 }
136673
136674 DUCKDB_API void FinalizeError();
136675 DUCKDB_API void AddErrorLocation(const string &query);
136676 DUCKDB_API void ConvertErrorToJSON();
136677
136678 DUCKDB_API void AddQueryLocation(optional_idx query_location);
136679 DUCKDB_API void AddQueryLocation(QueryErrorContext error_context);
136680 DUCKDB_API void AddQueryLocation(const ParsedExpression &ref);
136681 DUCKDB_API void AddQueryLocation(const TableRef &ref);
136682
136683private:
136685 bool initialized;
136687 ExceptionType type;
136689 string raw_message;
136691 string final_message;
136693 unordered_map<string, string> extra_info;
136694
136695private:
136696 DUCKDB_API static string SanitizeErrorMessage(string error);
136697 DUCKDB_API string ConstructFinalMessage() const;
136698};
136699
136700}
136701
136702
136703
136704
136705
136706
136707
136708
136709
136710
136711
136712
136713
136714#ifdef __MVS__
136715#include <time.h>
136716#endif
136717#include <mutex>
136718
136719namespace duckdb {
136720using std::lock_guard;
136721using std::mutex;
136722using std::unique_lock;
136723}
136724
136725
136726
136727
136728
136729
136730
136731
136732
136733
136734
136735
136736
136737
136738
136739
136740namespace duckdb {
136741class Expression;
136742
136743template <class T>
136744struct ReferenceHashFunction {
136746 return std::hash<void *>()((void *)&ref.get());
136747 }
136748};
136749
136750template <class T>
136751struct ReferenceEquality {
136752 bool operator()(
const reference<T> &a,
const reference<T> &b)
const {
136753 return &a.get() == &b.get();
136754 }
136755};
136756
136757template <typename T, typename TGT>
136758using reference_map_t = unordered_map<reference<T>, TGT, ReferenceHashFunction<T>, ReferenceEquality<T>>;
136759
136760template <typename T>
136761using reference_set_t = unordered_set<reference<T>, ReferenceHashFunction<T>, ReferenceEquality<T>>;
136762
136763}
136764
136765
136766
136767
136768
136769
136770
136771
136772
136773
136774
136775
136776
136777
136778
136779
136780namespace duckdb {
136781class BoundAtClause;
136782
136783struct EntryLookupInfo {
136784public:
136785 EntryLookupInfo(CatalogType catalog_type, const string &name,
136786 QueryErrorContext error_context = QueryErrorContext());
136787 EntryLookupInfo(CatalogType catalog_type, const string &name, optional_ptr<BoundAtClause> at_clause,
136788 QueryErrorContext error_context);
136789 EntryLookupInfo(const EntryLookupInfo &parent, const string &name);
136790 EntryLookupInfo(const EntryLookupInfo &parent, optional_ptr<BoundAtClause> at_clause);
136791
136792public:
136793 CatalogType GetCatalogType() const;
136794 const string &GetEntryName() const;
136795 const QueryErrorContext &GetErrorContext() const;
136796 const optional_ptr<BoundAtClause> GetAtClause() const;
136797
136798 static EntryLookupInfo SchemaLookup(const EntryLookupInfo &parent, const string &schema_name);
136799
136800private:
136801 CatalogType catalog_type;
136802 const string &name;
136803 optional_ptr<BoundAtClause> at_clause;
136804 QueryErrorContext error_context;
136805};
136806
136808struct CatalogEntryLookup {
136809 optional_ptr<SchemaCatalogEntry> schema;
136810 optional_ptr<CatalogEntry> entry;
136811 ErrorData error;
136812
136813 DUCKDB_API bool Found() const {
136814 return entry;
136815 }
136816};
136817
136818}
136819
136820
136821
136822
136823
136824
136825
136826
136827
136828
136829
136830#include <string>
136831#include <cstring>
136832
136833
136834
136835
136836
136837namespace duckdb {
136838
136840
136841
136842
136843
136844
136845
136846
136847
136848
136849
136850public:
136851
136852 String() : len(0), buf {0} {
136853 }
136854
136855 String(
const std::string &str) {
136856 AssignOwning(str.data(), SafeStrLen(str));
136857 }
136858
136859 String(
const char *str,
const uint32_t size) {
136860 AssignOwning(str, size);
136861 }
136862
136863 String(
const char *str)
136864 :
String(str, str ? SafeStrLen(str) : 0) {
136865 }
136866
136867public:
136868
136871
136872
136874 TransferOwnership(other);
136875 }
136876
136877
136879 if (this != &other) {
136880 Destroy();
136881 TransferOwnership(other);
136882 }
136883 return *this;
136884 }
136885
136886
136887 ~String() {
136888 Destroy();
136889 }
136890
136891public:
136892
136894 if (this == &other) {
136895 return true;
136896 }
136897
136898 if (
size() != other.size()) {
136899 return false;
136900 }
136901
136902 return memcmp(data(), other.data(),
size()) == 0;
136903 }
136904
136905 bool operator==(
const std::string &other)
const {
136906 if (SafeStrLen(other) !=
size()) {
136907 return false;
136908 }
136909 return memcmp(data(), other.data(),
size()) == 0;
136910 }
136911
136913 if (!other || SafeStrLen(other) !=
size()) {
136914 return false;
136915 }
136916
136917 if (this->data() == other) {
136918 return true;
136919 }
136920
136921 return memcmp(data(), other,
size()) == 0;
136922 }
136923
136925 const auto this_size =
size();
136926 const auto other_size = other.size();
136927 const auto min_size = MinValue<idx_t>(this_size, other_size);
136928
136929 auto memcmp_res = memcmp(data(), other.data(), min_size);
136930 return memcmp_res > 0 || (memcmp_res == 0 && this_size > other_size);
136931 }
136932
136934 return !(*this == other);
136935 }
136937 return other > *this;
136938 }
136940 return !(*this < other);
136941 }
136943 return !(*this > other);
136944 }
136945
136946 char operator[](const idx_t pos) const {
136947 D_ASSERT(pos <
size());
136948
136949 if (IsInlined()) {
136950 return buf[pos];
136951 }
136952 return ptr[pos];
136953 }
136954
136955public:
136956
136957
136959 return len & ~NON_OWNING_BIT;
136960 }
136961 bool empty() const {
136962 return len == 0;
136963 }
136964 const char *data() const {
136965 return IsInlined() ? buf : ptr;
136966 }
136967 const char *begin() const {
136968 return data();
136969 }
136970 const char *end() const {
136971 return data() +
size();
136972 }
136973 const char *c_str() const {
136974 return data();
136975 }
136976
136977
136978
136979 bool IsOwning() const {
136980 return (len & NON_OWNING_BIT) == 0;
136981 }
136982
136983 bool IsInlined() const {
136984 return len <= INLINE_MAX;
136985 }
136986
136987 static bool CanBeInlined(uint32_t size) {
136988 return size <= INLINE_MAX;
136989 }
136990
136991
136992 static String Copy(
const char *data, uint32_t size) {
136993 if (data == nullptr) {
136995 }
136996
136998 result.AssignOwning(data, size);
136999 return result;
137000 }
137001
137003 return Copy(other.data(), other.size());
137004 }
137005 static String Copy(
const char *data) {
137006 return Copy(data, data ? SafeStrLen(data) : 0);
137007 }
137008 static String Copy(
const std::string &str) {
137009 return Copy(str.data(), SafeStrLen(str));
137010 }
137012 return String::Copy(data(),
size());
137013 }
137014
137015
137016
137017 static String Reference(
const char *data, uint32_t size) {
137018 if (data == nullptr) {
137020 }
137021
137023
137024 if (size <= INLINE_MAX) {
137025 result.AssignOwning(data, size);
137026 } else {
137027 result.ptr = const_cast<char *>(data);
137028 result.len =
size | NON_OWNING_BIT;
137029 }
137030 return result;
137031 }
137032
137034 return Reference(other.data(), other.size());
137035 }
137036 static String Reference(
const char *data) {
137037 return Reference(data, data ? SafeStrLen(data) : 0);
137038 }
137039 static String Reference(
const std::string &str) {
137040 return Reference(str.data(), SafeStrLen(str));
137041 }
137042 String Reference()
const {
137043 return String::Reference(data(),
size());
137044 }
137045
137046 std::string ToStdString() const {
137047 if (IsInlined()) {
137048 return std::string(buf,
size());
137049 }
137050 return std::string(ptr,
size());
137051 }
137052
137053 static uint32_t SafeStrLen(
const char *data) {
137054 if (!data) {
137055 return 0;
137056 }
137057
137058 const auto len = strlen(data);
137059 D_ASSERT(len < NumericLimits<uint32_t>::Maximum());
137060 return static_cast<uint32_t>(len);
137061 }
137062
137063 static uint32_t SafeStrLen(
const std::string &data) {
137064 const auto len = data.size();
137065 D_ASSERT(len < NumericLimits<uint32_t>::Maximum());
137066 return static_cast<uint32_t>(len);
137067 }
137068
137069public:
137070 static char CharacterToLower(char c) {
137071 if (c >= 'A' && c <= 'Z') {
137072 return UnsafeNumericCast<char>(c + ('a' - 'A'));
137073 }
137074 return c;
137075 }
137076
137078 const auto str_data = data();
137079 const auto str_size =
size();
137080
137081 std::string lowercase_str;
137082 lowercase_str.reserve(str_size);
137083 for (idx_t i = 0; i < str_size; ++i) {
137084 lowercase_str.push_back(CharacterToLower(str_data[i]));
137085 }
137086 return String(lowercase_str);
137087 }
137088
137089private:
137090 static constexpr auto INLINE_CAP = sizeof(char *);
137091 static constexpr auto INLINE_MAX = INLINE_CAP - 1;
137092 static constexpr auto NON_OWNING_BIT = 1UL << (
sizeof(
uint32_t) * 8 - 1);
137093 static constexpr auto LENGTH_MAX = (1UL << (
sizeof(
uint32_t) * 8 - 1)) - 1;
137094
137095 void AssignOwning(const char *new_data, uint32_t new_size) {
137096 len = new_data ? new_size : 0;
137097
137098 if (len == 0) {
137099 buf[len] = '\0';
137100 return;
137101 }
137102
137103 if (len <= INLINE_MAX) {
137104 memcpy(buf, new_data, len);
137105 buf[len] = '\0';
137106 return;
137107 }
137108
137109 auto new_ptr = new char[len + 1];
137110 memcpy(new_ptr, new_data, len);
137111 new_ptr[len] = '\0';
137112
137113 ptr = new_ptr;
137114 }
137115
137116 void Destroy() {
137117 if (IsOwning() && !IsInlined()) {
137118 delete[] ptr;
137119 }
137120 }
137121
137122
137123 void ReleaseOwning() {
137124
137125 if (IsOwning() && !IsInlined()) {
137126 len |= NON_OWNING_BIT;
137127 }
137128 }
137129
137130 void TransferOwnership(
String &other) {
137131 len = other.len;
137132 if (IsInlined()) {
137133 AssignOwning(other.data(), other.size());
137134 } else {
137135 ptr = other.ptr;
137136 len = other.len;
137137 }
137138 other.ReleaseOwning();
137139 }
137140
137141private:
137143 union {
137144 const char *ptr;
137145 char buf[INLINE_CAP];
137146 };
137147};
137148
137150 return rhs == lhs;
137151}
137152
137154 return rhs == lhs;
137155}
137156
137157}
137158
137159
137160#include <functional>
137161
137162namespace duckdb {
137163struct AttachOptions;
137164struct CreateSchemaInfo;
137165struct DropInfo;
137166struct BoundCreateTableInfo;
137167struct AlterTableInfo;
137168struct CreateTableFunctionInfo;
137169struct CreateCopyFunctionInfo;
137170struct CreatePragmaFunctionInfo;
137171struct CreateFunctionInfo;
137172struct CreateViewInfo;
137173struct CreateSequenceInfo;
137174struct CreateCollationInfo;
137175struct CreateCoordinateSystemInfo;
137176struct CreateIndexInfo;
137177struct CreateTypeInfo;
137178struct CreateTableInfo;
137179struct DatabaseSize;
137180struct MetadataBlockInfo;
137181
137182class AttachedDatabase;
137183class ClientContext;
137184class QueryContext;
137185class Transaction;
137186
137187class AggregateFunctionCatalogEntry;
137188class CollateCatalogEntry;
137189class SchemaCatalogEntry;
137190class TableCatalogEntry;
137191class ViewCatalogEntry;
137192class SequenceCatalogEntry;
137193class TableFunctionCatalogEntry;
137194class CopyFunctionCatalogEntry;
137195class PragmaFunctionCatalogEntry;
137196class CatalogSet;
137197class DatabaseInstance;
137198class DependencyManager;
137199
137200struct CatalogLookup;
137201struct CatalogEntryLookup;
137202struct SimilarCatalogEntry;
137203
137204class Binder;
137205class LogicalOperator;
137206class LogicalMergeInto;
137207class PhysicalOperator;
137208class PhysicalPlanGenerator;
137209class LogicalCreateIndex;
137210class LogicalCreateTable;
137211class LogicalInsert;
137212class LogicalDelete;
137213class LogicalUpdate;
137214class CreateStatement;
137215class CatalogEntryRetriever;
137216
137218class Catalog {
137219public:
137220 explicit Catalog(AttachedDatabase &db);
137221 virtual ~Catalog();
137222
137223public:
137225 DUCKDB_API static Catalog &GetSystemCatalog(ClientContext &context);
137227 DUCKDB_API static Catalog &GetSystemCatalog(DatabaseInstance &db);
137229 DUCKDB_API static Catalog &GetCatalog(ClientContext &context, const string &catalog_name);
137231 DUCKDB_API static Catalog &GetCatalog(CatalogEntryRetriever &retriever, const string &catalog_name);
137233 DUCKDB_API static Catalog &GetCatalog(DatabaseInstance &db, const string &catalog_name);
137235 DUCKDB_API static optional_ptr<Catalog> GetCatalogEntry(ClientContext &context, const string &catalog_name);
137237 DUCKDB_API static optional_ptr<Catalog> GetCatalogEntry(CatalogEntryRetriever &retriever,
137238 const string &catalog_name);
137240 DUCKDB_API static Catalog &GetCatalog(AttachedDatabase &db);
137241
137242 DUCKDB_API AttachedDatabase &GetAttached();
137243 DUCKDB_API const AttachedDatabase &GetAttached() const;
137244 DUCKDB_API DatabaseInstance &GetDatabase();
137245
137246 virtual bool IsDuckCatalog() {
137247 return false;
137248 }
137249
137250 virtual void Initialize(bool load_builtin) = 0;
137251 virtual void Initialize(optional_ptr<ClientContext> context, bool load_builtin);
137252 virtual void FinalizeLoad(optional_ptr<ClientContext> context);
137253
137254 bool IsSystemCatalog() const;
137255 bool IsTemporaryCatalog() const;
137256
137261 DUCKDB_API virtual optional_idx GetCatalogVersion(ClientContext &context) {
137262 return {};
137263 }
137264
137266 DUCKDB_API const string &GetName() const;
137267 DUCKDB_API
idx_t GetOid();
137268 DUCKDB_API virtual string GetCatalogType() = 0;
137269
137270 DUCKDB_API CatalogTransaction GetCatalogTransaction(ClientContext &context);
137271
137273 DUCKDB_API virtual optional_ptr<CatalogEntry> CreateSchema(CatalogTransaction transaction,
137274 CreateSchemaInfo &info) = 0;
137275 DUCKDB_API optional_ptr<CatalogEntry> CreateSchema(ClientContext &context, CreateSchemaInfo &info);
137277 DUCKDB_API optional_ptr<CatalogEntry> CreateTable(CatalogTransaction transaction, BoundCreateTableInfo &info);
137278 DUCKDB_API optional_ptr<CatalogEntry> CreateTable(ClientContext &context, BoundCreateTableInfo &info);
137280 DUCKDB_API optional_ptr<CatalogEntry> CreateTable(ClientContext &context, unique_ptr<CreateTableInfo> info);
137282 DUCKDB_API optional_ptr<CatalogEntry> CreateTableFunction(CatalogTransaction transaction,
137283 CreateTableFunctionInfo &info);
137284 DUCKDB_API optional_ptr<CatalogEntry> CreateTableFunction(ClientContext &context, CreateTableFunctionInfo &info);
137285
137286 DUCKDB_API optional_ptr<CatalogEntry> CreateTableFunction(ClientContext &context,
137287 optional_ptr<CreateTableFunctionInfo> info);
137289 DUCKDB_API optional_ptr<CatalogEntry> CreateCopyFunction(CatalogTransaction transaction,
137290 CreateCopyFunctionInfo &info);
137291 DUCKDB_API optional_ptr<CatalogEntry> CreateCopyFunction(ClientContext &context, CreateCopyFunctionInfo &info);
137293 DUCKDB_API optional_ptr<CatalogEntry> CreatePragmaFunction(CatalogTransaction transaction,
137294 CreatePragmaFunctionInfo &info);
137295 DUCKDB_API optional_ptr<CatalogEntry> CreatePragmaFunction(ClientContext &context, CreatePragmaFunctionInfo &info);
137297 DUCKDB_API optional_ptr<CatalogEntry> CreateFunction(CatalogTransaction transaction, CreateFunctionInfo &info);
137298 DUCKDB_API optional_ptr<CatalogEntry> CreateFunction(ClientContext &context, CreateFunctionInfo &info);
137300 DUCKDB_API optional_ptr<CatalogEntry> CreateView(CatalogTransaction transaction, CreateViewInfo &info);
137301 DUCKDB_API optional_ptr<CatalogEntry> CreateView(ClientContext &context, CreateViewInfo &info);
137303 DUCKDB_API optional_ptr<CatalogEntry> CreateSequence(CatalogTransaction transaction, CreateSequenceInfo &info);
137304 DUCKDB_API optional_ptr<CatalogEntry> CreateSequence(ClientContext &context, CreateSequenceInfo &info);
137306 DUCKDB_API optional_ptr<CatalogEntry> CreateType(CatalogTransaction transaction, CreateTypeInfo &info);
137307 DUCKDB_API optional_ptr<CatalogEntry> CreateType(ClientContext &context, CreateTypeInfo &info);
137309 DUCKDB_API optional_ptr<CatalogEntry> CreateCollation(CatalogTransaction transaction, CreateCollationInfo &info);
137310 DUCKDB_API optional_ptr<CatalogEntry> CreateCollation(ClientContext &context, CreateCollationInfo &info);
137312 DUCKDB_API optional_ptr<CatalogEntry> CreateCoordinateSystem(CatalogTransaction transaction,
137313 CreateCoordinateSystemInfo &info);
137314 DUCKDB_API optional_ptr<CatalogEntry> CreateCoordinateSystem(ClientContext &context,
137315 CreateCoordinateSystemInfo &info);
137317 DUCKDB_API optional_ptr<CatalogEntry> CreateIndex(CatalogTransaction transaction, CreateIndexInfo &info);
137318 DUCKDB_API optional_ptr<CatalogEntry> CreateIndex(ClientContext &context, CreateIndexInfo &info);
137319
137321 DUCKDB_API optional_ptr<CatalogEntry> CreateTable(CatalogTransaction transaction, SchemaCatalogEntry &schema,
137322 BoundCreateTableInfo &info);
137324 DUCKDB_API optional_ptr<CatalogEntry>
137325 CreateTableFunction(CatalogTransaction transaction, SchemaCatalogEntry &schema, CreateTableFunctionInfo &info);
137327 DUCKDB_API optional_ptr<CatalogEntry> CreateCopyFunction(CatalogTransaction transaction, SchemaCatalogEntry &schema,
137328 CreateCopyFunctionInfo &info);
137330 DUCKDB_API optional_ptr<CatalogEntry>
137331 CreatePragmaFunction(CatalogTransaction transaction, SchemaCatalogEntry &schema, CreatePragmaFunctionInfo &info);
137333 DUCKDB_API optional_ptr<CatalogEntry> CreateFunction(CatalogTransaction transaction, SchemaCatalogEntry &schema,
137334 CreateFunctionInfo &info);
137336 DUCKDB_API optional_ptr<CatalogEntry> CreateView(CatalogTransaction transaction, SchemaCatalogEntry &schema,
137337 CreateViewInfo &info);
137339 DUCKDB_API optional_ptr<CatalogEntry> CreateSequence(CatalogTransaction transaction, SchemaCatalogEntry &schema,
137340 CreateSequenceInfo &info);
137342 DUCKDB_API optional_ptr<CatalogEntry> CreateType(CatalogTransaction transaction, SchemaCatalogEntry &schema,
137343 CreateTypeInfo &info);
137345 DUCKDB_API static optional_ptr<CatalogEntry> CreateCollation(CatalogTransaction transaction,
137346 SchemaCatalogEntry &schema, CreateCollationInfo &info);
137348 DUCKDB_API static optional_ptr<CatalogEntry> CreateCoordinateSystem(CatalogTransaction transaction,
137349 SchemaCatalogEntry &schema,
137350 CreateCoordinateSystemInfo &info);
137351
137353 DUCKDB_API void DropEntry(ClientContext &context, DropInfo &info);
137354
137355 DUCKDB_API virtual optional_ptr<SchemaCatalogEntry> LookupSchema(CatalogTransaction transaction,
137356 const EntryLookupInfo &schema_lookup,
137357 OnEntryNotFound if_not_found) = 0;
137358
137360 DUCKDB_API SchemaCatalogEntry &GetSchema(ClientContext &context, const EntryLookupInfo &schema_lookup);
137361 DUCKDB_API optional_ptr<SchemaCatalogEntry> GetSchema(ClientContext &context, const EntryLookupInfo &schema_lookup,
137362 OnEntryNotFound if_not_found);
137364 DUCKDB_API virtual bool CheckAmbiguousCatalogOrSchema(ClientContext &context, const string &schema);
137365
137366 DUCKDB_API SchemaCatalogEntry &GetSchema(ClientContext &context, const string &schema);
137367 DUCKDB_API SchemaCatalogEntry &GetSchema(CatalogTransaction transaction, const string &schema);
137368 DUCKDB_API SchemaCatalogEntry &GetSchema(CatalogTransaction transaction, const EntryLookupInfo &schema_lookup);
137369 DUCKDB_API static SchemaCatalogEntry &GetSchema(ClientContext &context, const string &catalog_name,
137370 const EntryLookupInfo &schema_lookup);
137371 DUCKDB_API optional_ptr<SchemaCatalogEntry> GetSchema(ClientContext &context, const string &schema,
137372 OnEntryNotFound if_not_found);
137373 DUCKDB_API optional_ptr<SchemaCatalogEntry> GetSchema(CatalogTransaction transaction, const string &schema,
137374 OnEntryNotFound if_not_found);
137375 DUCKDB_API static optional_ptr<SchemaCatalogEntry> GetSchema(ClientContext &context, const string &catalog_name,
137376 const EntryLookupInfo &schema_lookup,
137377 OnEntryNotFound if_not_found);
137378 DUCKDB_API static SchemaCatalogEntry &GetSchema(ClientContext &context, const string &catalog_name,
137379 const string &schema);
137380 DUCKDB_API static optional_ptr<SchemaCatalogEntry> GetSchema(ClientContext &context, const string &catalog_name,
137381 const string &schema, OnEntryNotFound if_not_found);
137382 DUCKDB_API static optional_ptr<SchemaCatalogEntry> GetSchema(CatalogEntryRetriever &retriever,
137383 const string &catalog_name,
137384 const EntryLookupInfo &schema_lookup,
137385 OnEntryNotFound if_not_found);
137387 DUCKDB_API virtual void ScanSchemas(ClientContext &context, std::function<void(SchemaCatalogEntry &)> callback) = 0;
137388
137390 DUCKDB_API optional_ptr<CatalogEntry> GetEntry(ClientContext &context, const string &schema,
137391 const EntryLookupInfo &lookup_info, OnEntryNotFound if_not_found);
137392 DUCKDB_API optional_ptr<CatalogEntry> GetEntry(ClientContext &context, CatalogType catalog_type,
137393 const string &schema, const string &name,
137394 OnEntryNotFound if_not_found);
137395 DUCKDB_API optional_ptr<CatalogEntry> GetEntry(CatalogEntryRetriever &retriever, const string &schema,
137396 const EntryLookupInfo &lookup_info, OnEntryNotFound if_not_found);
137397 DUCKDB_API CatalogEntry &GetEntry(ClientContext &context, const string &schema, const EntryLookupInfo &lookup_info);
137400 DUCKDB_API static optional_ptr<CatalogEntry> GetEntry(ClientContext &context, const string &catalog,
137401 const string &schema, const EntryLookupInfo &lookup_info,
137402 OnEntryNotFound if_not_found);
137403 DUCKDB_API static optional_ptr<CatalogEntry> GetEntry(CatalogEntryRetriever &retriever, const string &catalog,
137404 const string &schema, const EntryLookupInfo &lookup_info,
137405 OnEntryNotFound if_not_found);
137406 DUCKDB_API static CatalogEntry &GetEntry(ClientContext &context, const string &catalog, const string &schema,
137407 const EntryLookupInfo &lookup_info);
137408
137409 template <class T>
137410 optional_ptr<T> GetEntry(ClientContext &context, const string &schema_name, const string &name,
137411 OnEntryNotFound if_not_found, QueryErrorContext error_context = QueryErrorContext()) {
137412 EntryLookupInfo lookup_info(T::Type, name, error_context);
137413 auto entry = GetEntry(context, schema_name, lookup_info, if_not_found);
137414 if (!entry) {
137415 return nullptr;
137416 }
137417 if (entry->type != T::Type) {
137418 throw CatalogException(error_context, "%s is not an %s", name, T::Name);
137419 }
137420 return &entry->template Cast<T>();
137421 }
137422
137423 template <class T>
137424 T &GetEntry(ClientContext &context, const string &schema_name, const string &name,
137425 QueryErrorContext error_context = QueryErrorContext()) {
137426 auto entry = GetEntry<T>(context, schema_name, name, OnEntryNotFound::THROW_EXCEPTION, error_context);
137427 return *entry;
137428 }
137429
137430 static CatalogEntry &GetEntry(ClientContext &context, CatalogType catalog_type, const string &catalog_name,
137431 const string &schema_name, const string &name);
137432 CatalogEntry &GetEntry(ClientContext &context, CatalogType catalog_type, const string &schema_name,
137433 const string &name);
137434
137436 DUCKDB_API optional_ptr<CatalogEntry> AddFunction(ClientContext &context, CreateFunctionInfo &info);
137437
137439 DUCKDB_API void Alter(CatalogTransaction transaction, AlterInfo &info);
137440 DUCKDB_API void Alter(ClientContext &context, AlterInfo &info);
137441
137442 virtual PhysicalOperator &PlanCreateTableAs(ClientContext &context, PhysicalPlanGenerator &planner,
137443 LogicalCreateTable &op, PhysicalOperator &plan) = 0;
137444 virtual PhysicalOperator &PlanInsert(ClientContext &context, PhysicalPlanGenerator &planner, LogicalInsert &op,
137445 optional_ptr<PhysicalOperator> plan) = 0;
137446 virtual PhysicalOperator &PlanDelete(ClientContext &context, PhysicalPlanGenerator &planner, LogicalDelete &op,
137447 PhysicalOperator &plan) = 0;
137448 virtual PhysicalOperator &PlanDelete(ClientContext &context, PhysicalPlanGenerator &planner, LogicalDelete &op);
137449 virtual PhysicalOperator &PlanUpdate(ClientContext &context, PhysicalPlanGenerator &planner, LogicalUpdate &op,
137450 PhysicalOperator &plan) = 0;
137451 virtual PhysicalOperator &PlanUpdate(ClientContext &context, PhysicalPlanGenerator &planner, LogicalUpdate &op);
137452 virtual PhysicalOperator &PlanMergeInto(ClientContext &context, PhysicalPlanGenerator &planner,
137453 LogicalMergeInto &op, PhysicalOperator &plan);
137454 virtual unique_ptr<LogicalOperator> BindCreateIndex(Binder &binder, CreateStatement &stmt, TableCatalogEntry &table,
137455 unique_ptr<LogicalOperator> plan);
137456 virtual unique_ptr<LogicalOperator> BindAlterAddIndex(Binder &binder, TableCatalogEntry &table_entry,
137457 unique_ptr<LogicalOperator> plan,
137458 unique_ptr<CreateIndexInfo> create_info,
137459 unique_ptr<AlterTableInfo> alter_info);
137460
137461 virtual DatabaseSize GetDatabaseSize(ClientContext &context) = 0;
137462 virtual vector<MetadataBlockInfo> GetMetadataInfo(ClientContext &context);
137463
137464 virtual bool InMemory() = 0;
137465 virtual string GetDBPath() = 0;
137466 virtual bool SupportsTimeTravel() const {
137467 return false;
137468 }
137469 virtual bool IsEncrypted() const {
137470 return false;
137471 }
137472 virtual string GetEncryptionCipher() const {
137473 return string();
137474 }
137475 virtual ErrorData SupportsCreateTable(BoundCreateTableInfo &info);
137476
137479 return CatalogLookupBehavior::STANDARD;
137480 }
137481
137483 virtual string GetDefaultSchema() const;
137484
137487 DUCKDB_API bool HasDefaultTable() const;
137488 DUCKDB_API void SetDefaultTable(const string &schema, const string &name);
137489 DUCKDB_API string GetDefaultTable() const;
137490 DUCKDB_API string GetDefaultTableSchema() const;
137491
137493 virtual optional_ptr<DependencyManager> GetDependencyManager();
137494
137496 virtual bool HasConflictingAttachOptions(const string &path, const AttachOptions &options);
137497
137498public:
137499 template <class T>
137500 static optional_ptr<T> GetEntry(ClientContext &context, const string &catalog_name, const string &schema_name,
137501 const string &name, OnEntryNotFound if_not_found,
137502 QueryErrorContext error_context = QueryErrorContext()) {
137503 EntryLookupInfo lookup_info(T::Type, name, error_context);
137504 auto entry = GetEntry(context, catalog_name, schema_name, lookup_info, if_not_found);
137505 if (!entry) {
137506 return nullptr;
137507 }
137508 if (entry->type != T::Type) {
137509 throw CatalogException(error_context, "%s is not an %s", name, T::Name);
137510 }
137511 return &entry->template Cast<T>();
137512 }
137513 template <class T>
137514 static T &GetEntry(ClientContext &context, const string &catalog_name, const string &schema_name,
137515 const string &name, QueryErrorContext error_context = QueryErrorContext()) {
137516 auto entry =
137517 GetEntry<T>(context, catalog_name, schema_name, name, OnEntryNotFound::THROW_EXCEPTION, error_context);
137518 return *entry;
137519 }
137520
137521 DUCKDB_API vector<reference<SchemaCatalogEntry>> GetSchemas(ClientContext &context);
137522 DUCKDB_API static vector<reference<SchemaCatalogEntry>> GetSchemas(ClientContext &context,
137523 const string &catalog_name);
137524 DUCKDB_API static vector<reference<SchemaCatalogEntry>> GetSchemas(CatalogEntryRetriever &retriever,
137525 const string &catalog_name);
137526 DUCKDB_API static vector<reference<SchemaCatalogEntry>> GetAllSchemas(ClientContext &context);
137527
137528 static vector<reference<CatalogEntry>> GetAllEntries(ClientContext &context, CatalogType catalog_type);
137529
137530 virtual void Verify();
137531
137532 static CatalogException UnrecognizedConfigurationError(ClientContext &context, const string &name);
137533
137535 static String AutoloadExtensionByConfigName(ClientContext &context,
const String &configuration_name);
137537 static bool AutoLoadExtensionByCatalogEntry(DatabaseInstance &db, CatalogType type, const string &entry_name);
137538 DUCKDB_API static bool TryAutoLoad(ClientContext &context, const string &extension_name) noexcept;
137539
137541 DUCKDB_API virtual void OnDetach(ClientContext &context);
137542
137543protected:
137545 AttachedDatabase &
db;
137546
137548 string default_table;
137549 string default_table_schema;
137550
137551public:
137553 CatalogEntryLookup LookupEntry(CatalogEntryRetriever &retriever, const string &schema,
137554 const EntryLookupInfo &lookup_info, OnEntryNotFound if_not_found);
137555
137556private:
137558 virtual CatalogEntryLookup TryLookupEntryInternal(CatalogTransaction transaction, const string &schema,
137559 const EntryLookupInfo &lookup_info);
137562 CatalogEntryLookup TryLookupEntry(CatalogEntryRetriever &retriever, const string &schema,
137563 const EntryLookupInfo &lookup_info, OnEntryNotFound if_not_found);
137564 static CatalogEntryLookup TryLookupEntry(CatalogEntryRetriever &retriever, const vector<CatalogLookup> &lookups,
137565 const EntryLookupInfo &lookup_info, OnEntryNotFound if_not_found,
137566 bool allow_default_table_lookup);
137567 static CatalogEntryLookup TryLookupEntry(CatalogEntryRetriever &retriever, const string &catalog,
137568 const string &schema, const EntryLookupInfo &lookup_info,
137569 OnEntryNotFound if_not_found);
137570
137572 static CatalogEntryLookup TryLookupDefaultTable(CatalogEntryRetriever &retriever,
137573 const EntryLookupInfo &lookup_info,
137574 bool allow_ignore_at_clause = false);
137575
137577 static CatalogException CreateMissingEntryException(CatalogEntryRetriever &retriever,
137578 const EntryLookupInfo &lookup_info,
137579 const reference_set_t<SchemaCatalogEntry> &schemas);
137580
137582 static vector<SimilarCatalogEntry> SimilarEntriesInSchemas(ClientContext &context,
137583 const EntryLookupInfo &lookup_info,
137584 const reference_set_t<SchemaCatalogEntry> &schemas);
137585
137586 virtual void DropSchema(ClientContext &context, DropInfo &info) = 0;
137587
137588public:
137589 template <class TARGET>
137590 TARGET &Cast() {
137591 DynamicCastCheck<TARGET>(this);
137592 return reinterpret_cast<TARGET &>(*this);
137593 }
137594
137595 template <class TARGET>
137596 const TARGET &Cast() const {
137597 DynamicCastCheck<TARGET>(this);
137598 return reinterpret_cast<const TARGET &>(*this);
137599 }
137600};
137601
137602}
137603
137604
137605
137606
137607#include <type_traits>
137608
137609namespace duckdb {
137610
137611class WriteStream {
137612public:
137613
137614 virtual void WriteData(const_data_ptr_t buffer, idx_t write_size) = 0;
137615
137616
137617
137618 template <class T>
137619 void Write(T element) {
137620 static_assert(std::is_standard_layout<T>(), "Write element must be a standard layout data type");
137621 WriteData(const_data_ptr_cast(&element), sizeof(T));
137622 }
137623
137624 virtual ~WriteStream() {
137625 }
137626};
137627
137628}
137629
137630
137631
137632
137633
137634
137635
137636
137637
137638
137639
137640
137641
137642
137643
137644
137645
137646
137647
137648
137649
137650
137651
137652
137653namespace duckdb {
137654
137655enum class FileCompressionType :
uint8_t { AUTO_DETECT = 0, UNCOMPRESSED = 1, GZIP = 2, ZSTD = 3 };
137656
137657FileCompressionType FileCompressionTypeFromString(const string &input);
137658
137659string CompressionExtensionFromType(const FileCompressionType type);
137660
137661bool IsFileCompressed(string path, FileCompressionType type);
137662
137663}
137664
137665
137666
137667
137668
137669
137670
137671
137672
137673
137674
137675
137676
137677namespace duckdb {
137678
137679enum class FileGlobOptions :
uint8_t { DISALLOW_EMPTY = 0, ALLOW_EMPTY = 1, FALLBACK_GLOB = 2 };
137680
137681struct FileGlobInput {
137682 FileGlobInput(FileGlobOptions options)
137683 : behavior(options) {
137684 }
137685 FileGlobInput(FileGlobOptions options, string extension_p) : behavior(options), extension(std::move(extension_p)) {
137686 }
137687
137688 FileGlobOptions behavior;
137689 string extension;
137690};
137691
137692}
137693
137694
137695
137696
137697
137698
137699
137700
137701
137702
137703
137704
137705
137706
137707
137708
137709
137710
137711
137712
137713
137714
137715
137716
137717
137718
137719namespace duckdb {
137720
137721enum class DebugInitialize :
uint8_t { NO_INITIALIZE = 0, DEBUG_ZERO_INITIALIZE = 1, DEBUG_ONE_INITIALIZE = 2 };
137722
137723}
137724
137725
137726namespace duckdb {
137727
137728class BlockAllocator;
137729class BlockManager;
137730class QueryContext;
137731
137732struct FileHandle;
137733
137734enum class FileBufferType :
uint8_t { BLOCK = 1, MANAGED_BUFFER = 2, TINY_BUFFER = 3, EXTERNAL_FILE = 4 };
137735
137736static constexpr idx_t FILE_BUFFER_TYPE_COUNT = 4;
137737
137739class FileBuffer {
137740public:
137745 FileBuffer(BlockAllocator &allocator, FileBufferType type, uint64_t user_size, idx_t block_header_size);
137746 FileBuffer(BlockAllocator &allocator, FileBufferType type, BlockManager &block_manager);
137747 FileBuffer(FileBuffer &source, FileBufferType type, idx_t block_header_size);
137748
137749 virtual ~FileBuffer();
137750
137751 BlockAllocator &allocator;
137753 data_ptr_t buffer;
137757
137758public:
137760 void Read(QueryContext context, FileHandle &handle, uint64_t location);
137762 void Write(QueryContext context, FileHandle &handle, const uint64_t location);
137763
137764 void Clear();
137765
137766 FileBufferType GetBufferType() const {
137767 return type;
137768 }
137769
137770
137771
137772 void Resize(uint64_t user_size, idx_t block_header_size);
137773 void Resize(BlockManager &block_manager);
137774
137775 idx_t GetHeaderSize()
const {
137776 return internal_size -
size;
137777 }
137778
137780 return internal_size;
137781 }
137784 }
137785 data_ptr_t InternalBuffer() {
137786 return internal_buffer;
137787 }
137788
137789 struct MemoryRequirement {
137791 idx_t header_size;
137792 };
137793
137794 MemoryRequirement CalculateMemory(uint64_t user_size, uint64_t block_header_size) const;
137795 void Initialize(DebugInitialize info);
137796
137797protected:
137799 FileBufferType type;
137802 data_ptr_t internal_buffer;
137806
137807 void ReallocBuffer(idx_t new_size);
137808 void Init();
137809
137810private:
137811 void ResizeInternal(uint64_t user_size, uint64_t block_header_size);
137812};
137813
137814}
137815
137816
137817
137818
137819
137820
137821
137822
137823
137824
137825
137826
137827
137828
137829
137830
137831
137832
137833
137834
137835
137836
137837
137838#include <cstdint>
137839
137840namespace duckdb {
137841
137845
137846 ALWAYS_CACHE = 0,
137847
137848 CACHE_REMOTE_ONLY = 1,
137849
137850 NO_CACHING = 2,
137851};
137852
137853}
137854
137855
137856namespace duckdb {
137857
137858enum class FileLockType :
uint8_t { NO_LOCK = 0, READ_LOCK = 1, WRITE_LOCK = 2 };
137859
137860class FileOpenFlags {
137861public:
137862 static constexpr idx_t FILE_FLAGS_READ =
idx_t(1 << 0);
137863 static constexpr idx_t FILE_FLAGS_WRITE =
idx_t(1 << 1);
137864 static constexpr idx_t FILE_FLAGS_DIRECT_IO =
idx_t(1 << 2);
137865 static constexpr idx_t FILE_FLAGS_FILE_CREATE =
idx_t(1 << 3);
137866 static constexpr idx_t FILE_FLAGS_FILE_CREATE_NEW =
idx_t(1 << 4);
137867 static constexpr idx_t FILE_FLAGS_APPEND =
idx_t(1 << 5);
137868 static constexpr idx_t FILE_FLAGS_PRIVATE =
idx_t(1 << 6);
137869 static constexpr idx_t FILE_FLAGS_NULL_IF_NOT_EXISTS =
idx_t(1 << 7);
137870 static constexpr idx_t FILE_FLAGS_PARALLEL_ACCESS =
idx_t(1 << 8);
137871 static constexpr idx_t FILE_FLAGS_EXCLUSIVE_CREATE =
idx_t(1 << 9);
137872 static constexpr idx_t FILE_FLAGS_NULL_IF_EXISTS =
idx_t(1 << 10);
137873 static constexpr idx_t FILE_FLAGS_MULTI_CLIENT_ACCESS =
idx_t(1 << 11);
137874 static constexpr idx_t FILE_FLAGS_DISABLE_LOGGING =
idx_t(1 << 12);
137875 static constexpr idx_t FILE_FLAGS_ENABLE_EXTENSION_INSTALL =
idx_t(1 << 13);
137876
137877public:
137878 FileOpenFlags() = default;
137879 constexpr FileOpenFlags(idx_t flags) : flags(flags) {
137880 }
137881 constexpr FileOpenFlags(FileLockType lock) : lock(lock) {
137882 }
137883 constexpr FileOpenFlags(FileCompressionType compression)
137884 : compression(compression) {
137885 }
137886 constexpr FileOpenFlags(idx_t flags, FileLockType lock, FileCompressionType compression)
137887 : flags(flags), lock(lock), compression(compression) {
137888 }
137889
137890 static constexpr FileLockType MergeLock(FileLockType a, FileLockType b) {
137891 return a == FileLockType::NO_LOCK ? b : a;
137892 }
137893
137894 static constexpr FileCompressionType MergeCompression(FileCompressionType a, FileCompressionType b) {
137895 return a == FileCompressionType::UNCOMPRESSED ? b : a;
137896 }
137897
137898 static constexpr CachingMode MergeCachingMode(CachingMode a, CachingMode b) {
137899 return a == CachingMode::NO_CACHING ? b : a;
137900 }
137901
137902 inline constexpr FileOpenFlags
operator|(FileOpenFlags b)
const {
137903 return FileOpenFlags(flags | b.flags, MergeLock(lock, b.lock), MergeCompression(compression, b.compression));
137904 }
137905 inline FileOpenFlags &
operator|=(FileOpenFlags b) {
137906 flags |= b.flags;
137907 lock = MergeLock(lock, b.lock);
137908 compression = MergeCompression(compression, b.compression);
137909 caching_mode = MergeCachingMode(caching_mode, b.caching_mode);
137910 return *this;
137911 }
137912
137913 FileLockType Lock() {
137914 return lock;
137915 }
137916
137917 FileCompressionType Compression() {
137918 return compression;
137919 }
137920
137921 void SetCompression(FileCompressionType new_compression) {
137922 compression = new_compression;
137923 }
137924
137926 return caching_mode;
137927 }
137928 void SetCachingMode(CachingMode new_caching_mode) {
137929 caching_mode = new_caching_mode;
137930 }
137931
137932 void Verify();
137933
137934 inline bool OpenForReading() const {
137935 return flags & FILE_FLAGS_READ;
137936 }
137937 inline bool OpenForWriting() const {
137938 return flags & FILE_FLAGS_WRITE;
137939 }
137940 inline bool DirectIO() const {
137941 return flags & FILE_FLAGS_DIRECT_IO;
137942 }
137943 inline bool CreateFileIfNotExists() const {
137944 return flags & FILE_FLAGS_FILE_CREATE;
137945 }
137946 inline bool OverwriteExistingFile() const {
137947 return flags & FILE_FLAGS_FILE_CREATE_NEW;
137948 }
137949 inline bool OpenForAppending() const {
137950 return flags & FILE_FLAGS_APPEND;
137951 }
137952 inline bool CreatePrivateFile() const {
137953 return flags & FILE_FLAGS_PRIVATE;
137954 }
137955 inline bool ReturnNullIfNotExists() const {
137956 return flags & FILE_FLAGS_NULL_IF_NOT_EXISTS;
137957 }
137958 inline bool RequireParallelAccess() const {
137959 return flags & FILE_FLAGS_PARALLEL_ACCESS;
137960 }
137961 inline bool ExclusiveCreate() const {
137962 return flags & FILE_FLAGS_EXCLUSIVE_CREATE;
137963 }
137964 inline bool ReturnNullIfExists() const {
137965 return flags & FILE_FLAGS_NULL_IF_EXISTS;
137966 }
137967 inline bool MultiClientAccess() const {
137968 return flags & FILE_FLAGS_MULTI_CLIENT_ACCESS;
137969 }
137970 inline bool DisableLogging() const {
137971 return flags & FILE_FLAGS_DISABLE_LOGGING;
137972 }
137973 inline bool EnableExtensionInstall() const {
137974 return flags & FILE_FLAGS_ENABLE_EXTENSION_INSTALL;
137975 }
137976 inline idx_t GetFlagsInternal()
const {
137977 return flags;
137978 }
137979
137980private:
137982 FileLockType lock = FileLockType::NO_LOCK;
137983 CachingMode caching_mode = CachingMode::NO_CACHING;
137984 FileCompressionType compression = FileCompressionType::UNCOMPRESSED;
137985};
137986
137987class FileFlags {
137988public:
137990 static constexpr FileOpenFlags FILE_FLAGS_READ = FileOpenFlags(FileOpenFlags::FILE_FLAGS_READ);
137992 static constexpr FileOpenFlags FILE_FLAGS_WRITE = FileOpenFlags(FileOpenFlags::FILE_FLAGS_WRITE);
137994 static constexpr FileOpenFlags FILE_FLAGS_DIRECT_IO = FileOpenFlags(FileOpenFlags::FILE_FLAGS_DIRECT_IO);
137996 static constexpr FileOpenFlags FILE_FLAGS_FILE_CREATE = FileOpenFlags(FileOpenFlags::FILE_FLAGS_FILE_CREATE);
137998 static constexpr FileOpenFlags FILE_FLAGS_FILE_CREATE_NEW =
137999 FileOpenFlags(FileOpenFlags::FILE_FLAGS_FILE_CREATE_NEW);
138001 static constexpr FileOpenFlags FILE_FLAGS_APPEND = FileOpenFlags(FileOpenFlags::FILE_FLAGS_APPEND);
138003 static constexpr FileOpenFlags FILE_FLAGS_PRIVATE = FileOpenFlags(FileOpenFlags::FILE_FLAGS_PRIVATE);
138005 static constexpr FileOpenFlags FILE_FLAGS_NULL_IF_NOT_EXISTS =
138006 FileOpenFlags(FileOpenFlags::FILE_FLAGS_NULL_IF_NOT_EXISTS);
138008 static constexpr FileOpenFlags FILE_FLAGS_PARALLEL_ACCESS =
138009 FileOpenFlags(FileOpenFlags::FILE_FLAGS_PARALLEL_ACCESS);
138011 static constexpr FileOpenFlags FILE_FLAGS_EXCLUSIVE_CREATE =
138012 FileOpenFlags(FileOpenFlags::FILE_FLAGS_EXCLUSIVE_CREATE);
138014 static constexpr FileOpenFlags FILE_FLAGS_NULL_IF_EXISTS = FileOpenFlags(FileOpenFlags::FILE_FLAGS_NULL_IF_EXISTS);
138016 static constexpr FileOpenFlags FILE_FLAGS_MULTI_CLIENT_ACCESS =
138017 FileOpenFlags(FileOpenFlags::FILE_FLAGS_MULTI_CLIENT_ACCESS);
138019 static constexpr FileOpenFlags FILE_FLAGS_DISABLE_LOGGING =
138020 FileOpenFlags(FileOpenFlags::FILE_FLAGS_DISABLE_LOGGING);
138022 static constexpr FileOpenFlags FILE_FLAGS_ENABLE_EXTENSION_INSTALL =
138023 FileOpenFlags(FileOpenFlags::FILE_FLAGS_ENABLE_EXTENSION_INSTALL);
138024};
138025
138026}
138027
138028
138029
138030
138031
138032
138033
138034
138035
138036
138037
138038
138039
138040
138041
138042namespace duckdb {
138043
138044struct ExtendedOpenFileInfo {
138045 unordered_map<string, Value> options;
138046};
138047
138048struct OpenFileInfo {
138049 OpenFileInfo() = default;
138050 OpenFileInfo(string path_p)
138051 : path(std::move(path_p)) {
138052 }
138053
138054 string path;
138055 shared_ptr<ExtendedOpenFileInfo> extended_info;
138056
138057public:
138058 bool operator<(
const OpenFileInfo &rhs)
const {
138059 return path < rhs.path;
138060 }
138061};
138062
138063}
138064
138065
138066
138067
138068
138069
138070
138071
138072
138073
138074
138075
138076
138077
138078
138079
138080
138081
138082namespace duckdb {
138083
138084
138085
138086
138087
138088
138089
138090
138091
138092
138093
138094
138095
138096
138097
138098
138099
138100
138101
138102
138103
138104
138105
138106
138107
138108
138109
138110
138111
138112
138113
138114
138115
138116
138117class Path {
138118public:
138119
138120 static Path FromString(const string &raw);
138121
138122 string ToString() const;
138123
138124
138125 string GetBase() const;
138126 string GetPath() const;
138127 string GetTrailingSeparator() const {
138128 return !segments.empty() && has_trailing_separator ? string(1, separator) : "";
138129 }
138130 const string &GetScheme() const {
138131 return scheme;
138132 }
138133 const string &GetAuthority() const {
138134 return authority;
138135 }
138136 const string &GetAnchor() const {
138137 return anchor;
138138 }
138139 char GetSeparator() const {
138140 return separator;
138141 }
138142
138143 bool HasScheme() const {
138144 return !scheme.empty();
138145 }
138146 bool HasAuthority() const {
138147 return !authority.empty();
138148 }
138149 bool HasAnchor() const {
138150 return !anchor.empty();
138151 }
138152
138153 bool HasDrive() const;
138154 char GetDriveChar() const;
138155
138156 bool HasPathSegments() const {
138157 return !segments.empty();
138158 }
138159
138160 bool HasTrailingSeparator() const {
138161 return has_trailing_separator;
138162 }
138163
138164 bool IsAbsolute() const {
138165 return is_absolute;
138166 }
138167
138168
138169 bool IsLocal() const {
138170
138172 }
138173
138174 bool IsRemote() const {
138175 return !IsLocal();
138176 }
138177
138178 const vector<string> &GetPathSegments() const {
138179 return segments;
138180 }
138181
138182
138183 Path Join(const Path &rhs) const;
138184 Path Join(const string &rhs) const;
138185
138186 template <typename... Args>
138187 Path Join(const string &first, const Args &...rest) const {
138188 return Join(first).Join(rest...);
138189 }
138190
138191 Path Join(const vector<string> &paths) const {
138192 Path result = *this;
138193 for (const auto &rhs : paths) {
138194 result = result.Join(rhs);
138195 }
138196 return result;
138197 }
138198
138199 Path Parent(int n = 1) const;
138200
138201
138202 static string Normalize(const string &input) {
138203 return FromString(input).ToString();
138204 }
138205
138206 static string AddSuffixToPath(const string &path, const string &suffix);
138207
138208private:
138209 string scheme;
138210 string authority;
138211 string anchor;
138212 vector<string> segments;
138213
138214 char separator = '/';
138215 bool has_trailing_separator = false;
138216 bool is_absolute = false;
138217
138218 void NormalizeSegments(const string &raw, size_t path_offset);
138219
138220 static size_t ParseURIScheme(const string &input, Path &parsed);
138221 static size_t ParseFilePathTail(const string &input, size_t start, Path &parsed);
138222 static size_t ParseFileSchemes(const string &input, Path &parsed);
138223#if defined(_WIN32)
138224 static size_t ParseUNCScheme(const string &input, Path &parsed);
138225#endif
138226};
138227
138228}
138229
138230
138231
138232
138233#include <functional>
138234
138235#undef CreateDirectory
138236#undef MoveFile
138237#undef RemoveDirectory
138238
138239namespace duckdb {
138240
138241class AttachedDatabase;
138242class DatabaseInstance;
138243class FileOpener;
138244class FileSystem;
138245class Logger;
138246class ClientContext;
138247class QueryContext;
138248class MultiFileList;
138249
138267};
138268
138269struct FileMetadata {
138271 timestamp_t last_modification_time = timestamp_t::ninfinity();
138272 FileType file_type = FileType::FILE_TYPE_INVALID;
138273
138274
138275 unordered_map<string, Value> extended_file_info;
138276};
138277
138278struct FileHandle {
138279public:
138280 DUCKDB_API FileHandle(FileSystem &file_system, string path, FileOpenFlags flags);
138281 FileHandle(const FileHandle &) = delete;
138282 DUCKDB_API virtual ~FileHandle();
138283
138284
138285
138286 DUCKDB_API
int64_t Read(
void *buffer, idx_t nr_bytes);
138287 DUCKDB_API
int64_t Read(QueryContext context,
void *buffer, idx_t nr_bytes);
138288 DUCKDB_API
int64_t Write(
void *buffer, idx_t nr_bytes);
138289 DUCKDB_API
int64_t Write(QueryContext context,
void *buffer, idx_t nr_bytes);
138290
138291
138292 DUCKDB_API void Read(void *buffer, idx_t nr_bytes, idx_t location);
138293 DUCKDB_API void Read(QueryContext context, void *buffer, idx_t nr_bytes, idx_t location);
138294 DUCKDB_API void Write(QueryContext context, void *buffer, idx_t nr_bytes, idx_t location);
138295 DUCKDB_API void Seek(idx_t location);
138296 DUCKDB_API void Reset();
138297 DUCKDB_API
idx_t SeekPosition();
138298 DUCKDB_API
void Sync();
138299 DUCKDB_API void Truncate(int64_t new_size);
138300 DUCKDB_API string ReadLine();
138301 DUCKDB_API string ReadLine(QueryContext context);
138302 DUCKDB_API bool Trim(idx_t offset_bytes, idx_t length_bytes);
138303 DUCKDB_API
virtual idx_t GetProgress();
138304 DUCKDB_API virtual FileCompressionType GetFileCompressionType();
138305
138306 DUCKDB_API bool CanSeek();
138307 DUCKDB_API bool IsPipe();
138308 DUCKDB_API bool OnDiskFile();
138309 DUCKDB_API
idx_t GetFileSize();
138311 DUCKDB_API FileMetadata Stats();
138312
138313 DUCKDB_API void TryAddLogger(FileOpener &opener);
138314
138316 DUCKDB_API virtual void Close() = 0;
138317
138318 string GetPath() const {
138319 return path;
138320 }
138321
138322 FileOpenFlags GetFlags() const {
138323 return flags;
138324 }
138325
138326 template <class TARGET>
138327 TARGET &Cast() {
138328 DynamicCastCheck<TARGET>(this);
138329 return reinterpret_cast<TARGET &>(*this);
138330 }
138331 template <class TARGET>
138332 const TARGET &Cast() const {
138333 DynamicCastCheck<TARGET>(this);
138334 return reinterpret_cast<const TARGET &>(*this);
138335 }
138336
138337public:
138338 FileSystem &file_system;
138339 string path;
138340 FileOpenFlags flags;
138341
138342 shared_ptr<Logger> logger;
138343};
138344
138345class FileSystem {
138346public:
138347 DUCKDB_API virtual ~FileSystem();
138348
138349public:
138350 DUCKDB_API static FileSystem &GetFileSystem(ClientContext &context);
138351 DUCKDB_API static FileSystem &GetFileSystem(DatabaseInstance &db);
138352 DUCKDB_API static FileSystem &Get(AttachedDatabase &db);
138353
138354 DUCKDB_API virtual unique_ptr<FileHandle> OpenFile(const string &path, FileOpenFlags flags,
138355 optional_ptr<FileOpener> opener = nullptr);
138356 DUCKDB_API unique_ptr<FileHandle> OpenFile(const OpenFileInfo &path, FileOpenFlags flags,
138357 optional_ptr<FileOpener> opener = nullptr);
138358
138361 DUCKDB_API virtual void Read(FileHandle &handle, void *buffer, int64_t nr_bytes, idx_t location);
138364 DUCKDB_API virtual void Write(FileHandle &handle, void *buffer, int64_t nr_bytes, idx_t location);
138367 DUCKDB_API
virtual int64_t Read(FileHandle &handle,
void *buffer, int64_t nr_bytes);
138369 DUCKDB_API
virtual int64_t Write(FileHandle &handle,
void *buffer, int64_t nr_bytes);
138372 DUCKDB_API virtual bool Trim(FileHandle &handle, idx_t offset_bytes, idx_t length_bytes);
138373
138375 DUCKDB_API
virtual int64_t GetFileSize(FileHandle &handle);
138377 DUCKDB_API virtual timestamp_t GetLastModifiedTime(FileHandle &handle);
138380 DUCKDB_API virtual string GetVersionTag(FileHandle &handle);
138382 DUCKDB_API
virtual FileType GetFileType(FileHandle &handle);
138384 DUCKDB_API virtual FileMetadata Stats(FileHandle &handle);
138387 DUCKDB_API virtual void Truncate(FileHandle &handle, int64_t new_size);
138388
138390 DUCKDB_API virtual bool DirectoryExists(const string &directory, optional_ptr<FileOpener> opener = nullptr);
138392 DUCKDB_API virtual void CreateDirectory(const string &directory, optional_ptr<FileOpener> opener = nullptr);
138394 DUCKDB_API virtual void CreateDirectoriesRecursive(const string &path, optional_ptr<FileOpener> opener = nullptr);
138396 DUCKDB_API virtual void RemoveDirectory(const string &directory, optional_ptr<FileOpener> opener = nullptr);
138397
138399 DUCKDB_API virtual bool ListFiles(const string &directory,
138400 const std::function<void(const string &, bool)> &callback,
138401 FileOpener *opener = nullptr);
138402 DUCKDB_API bool ListFiles(const string &directory, const std::function<void(OpenFileInfo &info)> &callback,
138403 optional_ptr<FileOpener> opener = nullptr);
138404
138407 DUCKDB_API virtual void MoveFile(const string &source, const string &target,
138408 optional_ptr<FileOpener> opener = nullptr);
138410 DUCKDB_API virtual bool FileExists(const string &filename, optional_ptr<FileOpener> opener = nullptr);
138412 DUCKDB_API virtual bool IsPipe(const string &filename, optional_ptr<FileOpener> opener = nullptr);
138414 DUCKDB_API virtual void RemoveFile(const string &filename, optional_ptr<FileOpener> opener = nullptr);
138416 DUCKDB_API virtual bool TryRemoveFile(const string &filename, optional_ptr<FileOpener> opener = nullptr);
138418 DUCKDB_API virtual void RemoveFiles(const vector<string> &filenames, optional_ptr<FileOpener> opener = nullptr);
138420 DUCKDB_API virtual void FileSync(FileHandle &handle);
138422 DUCKDB_API static void SetWorkingDirectory(const string &path);
138424 DUCKDB_API static string GetWorkingDirectory();
138426 DUCKDB_API static string GetHomeDirectory(optional_ptr<FileOpener> opener);
138428 DUCKDB_API virtual string GetHomeDirectory();
138430 DUCKDB_API static string ExpandPath(const string &path, optional_ptr<FileOpener> opener);
138432 DUCKDB_API virtual string ExpandPath(const string &path);
138434 DUCKDB_API static optional_idx GetAvailableMemory();
138436 DUCKDB_API static optional_idx GetAvailableDiskSpace(const string &path);
138438 DUCKDB_API virtual string PathSeparator(const string &path);
138440 DUCKDB_API virtual bool IsPathAbsolute(const string &path);
138442 DUCKDB_API string JoinPath(const string &a, const string &path);
138443
138444 template <typename... ARGS>
138445 string JoinPath(const string &a, const string &b, ARGS... args) {
138446 return JoinPath(JoinPath(a, b), args...);
138447 }
138449 DUCKDB_API string ConvertSeparators(const string &path);
138451 DUCKDB_API string ExtractBaseName(const string &path);
138453 DUCKDB_API string ExtractExtension(const string &path);
138455 DUCKDB_API string ExtractName(const string &path);
138456
138458 DUCKDB_API static string GetEnvVariable(const string &name);
138459
138461 DUCKDB_API static bool HasGlob(const string &str);
138463 DUCKDB_API virtual vector<OpenFileInfo> Glob(const string &path, FileOpener *opener = nullptr);
138464 DUCKDB_API unique_ptr<MultiFileList> Glob(const string &path, const FileGlobInput &input,
138465 optional_ptr<FileOpener> opener);
138466 DUCKDB_API unique_ptr<MultiFileList> GlobFileList(const string &path,
138467 const FileGlobInput &input = FileGlobOptions::DISALLOW_EMPTY);
138468 DUCKDB_API vector<OpenFileInfo> GlobFiles(const string &pattern,
138469 const FileGlobInput &input = FileGlobOptions::DISALLOW_EMPTY);
138470
138472 DUCKDB_API virtual void RegisterSubSystem(unique_ptr<FileSystem> sub_fs);
138473 DUCKDB_API virtual void RegisterSubSystem(FileCompressionType compression_type, unique_ptr<FileSystem> fs);
138474
138476 DUCKDB_API virtual void UnregisterSubSystem(const string &name);
138477
138478
138479
138480 DUCKDB_API virtual unique_ptr<FileSystem> ExtractSubSystem(const string &name);
138481
138483 DUCKDB_API virtual vector<string> ListSubSystems();
138484
138486 DUCKDB_API virtual bool CanHandleFile(const string &fpath);
138487
138489 DUCKDB_API virtual void Seek(FileHandle &handle, idx_t location);
138491 DUCKDB_API virtual void Reset(FileHandle &handle);
138492 DUCKDB_API
virtual idx_t SeekPosition(FileHandle &handle);
138493
138495 DUCKDB_API virtual bool IsManuallySet();
138497 DUCKDB_API virtual bool CanSeek();
138500 DUCKDB_API virtual bool OnDiskFile(FileHandle &handle);
138501
138502 DUCKDB_API virtual unique_ptr<FileHandle> OpenCompressedFile(QueryContext context, unique_ptr<FileHandle> handle,
138503 bool write);
138504
138506 DUCKDB_API static unique_ptr<FileSystem> CreateLocal();
138507
138509 DUCKDB_API virtual std::string GetName() const = 0;
138510
138512 DUCKDB_API static bool IsRemoteFile(const string &path);
138513 DUCKDB_API static bool IsRemoteFile(const string &path, string &extension);
138514
138515 DUCKDB_API virtual void SetDisabledFileSystems(const vector<string> &names);
138516 DUCKDB_API virtual bool SubSystemIsDisabled(const string &name);
138518 DUCKDB_API virtual bool IsDisabledForPath(const string &path);
138519
138520 DUCKDB_API static bool IsDirectory(const OpenFileInfo &info);
138521
138523 DUCKDB_API virtual string CanonicalizePath(const string &path, optional_ptr<FileOpener> opener = nullptr);
138524
138525protected:
138526 DUCKDB_API virtual unique_ptr<FileHandle> OpenFileExtended(const OpenFileInfo &path, FileOpenFlags flags,
138527 optional_ptr<FileOpener> opener);
138528 DUCKDB_API virtual bool SupportsOpenFileExtended() const;
138529
138530 DUCKDB_API virtual bool ListFilesExtended(const string &directory,
138531 const std::function<void(OpenFileInfo &info)> &callback,
138532 optional_ptr<FileOpener> opener);
138533 DUCKDB_API virtual bool SupportsListFilesExtended() const;
138534
138535 DUCKDB_API virtual unique_ptr<MultiFileList> GlobFilesExtended(const string &path, const FileGlobInput &input,
138536 optional_ptr<FileOpener> opener = nullptr);
138537 DUCKDB_API virtual bool SupportsGlobExtended() const;
138538
138539public:
138540 template <class TARGET>
138541 TARGET &Cast() {
138542 DynamicCastCheck<TARGET>(this);
138543 return reinterpret_cast<TARGET &>(*this);
138544 }
138545
138546 template <class TARGET>
138547 const TARGET &Cast() const {
138548 DynamicCastCheck<TARGET>(this);
138549 return reinterpret_cast<const TARGET &>(*this);
138550 }
138551};
138552
138553}
138554
138555
138556namespace duckdb {
138557
138558#define FILE_BUFFER_SIZE 4096
138559
138560class BufferedFileWriter : public WriteStream {
138561public:
138562 static constexpr FileOpenFlags DEFAULT_OPEN_FLAGS = FileFlags::FILE_FLAGS_WRITE | FileFlags::FILE_FLAGS_FILE_CREATE;
138563
138566 DUCKDB_API BufferedFileWriter(FileSystem &fs, const string &path, FileOpenFlags open_flags = DEFAULT_OPEN_FLAGS);
138567
138568 FileSystem &fs;
138569 string path;
138570 unsafe_unique_array<data_t> data;
138572 idx_t total_written;
138573 unique_ptr<FileHandle> handle;
138574
138575public:
138576 DUCKDB_API void WriteData(const_data_ptr_t buffer, idx_t write_size) override;
138578 DUCKDB_API void Close();
138580 DUCKDB_API
void Sync();
138582 DUCKDB_API void Flush();
138584 DUCKDB_API
idx_t GetFileSize();
138586 DUCKDB_API void Truncate(idx_t size);
138587
138588 DUCKDB_API
idx_t GetTotalWritten()
const;
138589};
138590
138591}
138592
138593
138594
138595
138596
138597
138598
138599
138600
138601
138602
138603
138604
138605
138606
138607
138608
138609
138610
138611
138612
138613
138614
138615
138616
138617
138618
138619
138620
138621
138622
138623
138624
138625
138626
138627
138628
138629
138630
138631
138632
138633
138634
138635
138636
138637
138638
138639
138640
138641
138642
138643
138644
138645#include <bitset>
138646
138647namespace duckdb {
138648using std::bitset;
138649}
138650
138651
138652
138653
138654
138655
138656
138657
138658
138659
138660
138661
138662
138663
138664namespace duckdb {
138665
138666enum class VectorType :
uint8_t {
138667 FLAT_VECTOR,
138668 FSST_VECTOR,
138669 CONSTANT_VECTOR,
138670 DICTIONARY_VECTOR,
138671 SEQUENCE_VECTOR
138672};
138673
138674string VectorTypeToString(VectorType type);
138675
138676}
138677
138678
138679
138680
138681
138682
138683
138684
138685
138686
138687
138688
138689
138690
138691
138692
138693
138694
138695
138696
138697
138698
138699
138700
138701
138702
138703
138704
138705namespace duckdb {
138706class Allocator;
138707class AttachedDatabase;
138708class ClientContext;
138709class DatabaseInstance;
138710class ExecutionContext;
138711class ThreadContext;
138712
138713struct AllocatorDebugInfo;
138714
138715enum class AllocatorFreeType { REQUIRES_FREE, DOES_NOT_REQUIRE_FREE };
138716
138717struct PrivateAllocatorData {
138718 PrivateAllocatorData();
138719 virtual ~PrivateAllocatorData();
138720
138721 AllocatorFreeType free_type = AllocatorFreeType::REQUIRES_FREE;
138725 unique_ptr<AllocatorDebugInfo> debug_info;
138726
138727 template <class TARGET>
138728 TARGET &Cast() {
138729 DynamicCastCheck<TARGET>(this);
138730 return reinterpret_cast<TARGET &>(*this);
138731 }
138732 template <class TARGET>
138733 const TARGET &Cast() const {
138734 DynamicCastCheck<TARGET>(this);
138735 return reinterpret_cast<const TARGET &>(*this);
138736 }
138737};
138738
138739typedef data_ptr_t (*allocate_function_ptr_t)(PrivateAllocatorData *private_data,
idx_t size);
138740typedef void (*free_function_ptr_t)(PrivateAllocatorData *private_data, data_ptr_t pointer,
idx_t size);
138741typedef data_ptr_t (*reallocate_function_ptr_t)(PrivateAllocatorData *private_data, data_ptr_t pointer,
idx_t old_size,
138743
138744class AllocatedData {
138745public:
138746 DUCKDB_API AllocatedData();
138747 DUCKDB_API AllocatedData(Allocator &allocator, data_ptr_t pointer, idx_t allocated_size);
138748 DUCKDB_API ~AllocatedData();
138749
138750 AllocatedData(const AllocatedData &other) = delete;
138751 AllocatedData &
operator=(
const AllocatedData &) =
delete;
138753 DUCKDB_API AllocatedData(AllocatedData &&other) noexcept;
138754 DUCKDB_API AllocatedData &
operator=(AllocatedData &&) noexcept;
138755
138756 data_ptr_t
get() {
138757 return pointer;
138758 }
138759 operator bool() const {
138760 return pointer != nullptr;
138761 }
138762 const_data_ptr_t
get()
const {
138763 return pointer;
138764 }
138765 idx_t GetSize()
const {
138766 return allocated_size;
138767 }
138768 bool IsSet() {
138769 return pointer;
138770 }
138771 optional_ptr<Allocator> GetAllocator() const {
138772 return allocator;
138773 }
138774 void Reset();
138775
138776private:
138777 optional_ptr<Allocator> allocator;
138778 data_ptr_t pointer;
138779 idx_t allocated_size;
138780};
138781
138782class Allocator {
138783
138784 static constexpr const idx_t MAXIMUM_ALLOC_SIZE = 281474976710656ULL;
138785
138786public:
138787 DUCKDB_API Allocator();
138788 DUCKDB_API Allocator(allocate_function_ptr_t allocate_function_p, free_function_ptr_t free_function_p,
138789 reallocate_function_ptr_t reallocate_function_p,
138790 unique_ptr<PrivateAllocatorData> private_data);
138791 Allocator &
operator=(Allocator &&allocator)
noexcept =
delete;
138792 DUCKDB_API ~Allocator();
138793
138794 DUCKDB_API data_ptr_t AllocateData(idx_t size);
138795 DUCKDB_API void FreeData(data_ptr_t pointer, idx_t size);
138796 DUCKDB_API data_ptr_t ReallocateData(data_ptr_t pointer, idx_t old_size, idx_t new_size);
138797
138798 AllocatedData Allocate(idx_t size) {
138799 return AllocatedData(*this, AllocateData(size), size);
138800 }
138801 static data_ptr_t DefaultAllocate(PrivateAllocatorData *private_data, idx_t size);
138802 static void DefaultFree(PrivateAllocatorData *private_data, data_ptr_t pointer, idx_t size);
138803 static data_ptr_t DefaultReallocate(PrivateAllocatorData *private_data, data_ptr_t pointer, idx_t old_size,
138804 idx_t size);
138805 static Allocator &Get(ClientContext &context);
138806 static Allocator &Get(DatabaseInstance &db);
138807 static Allocator &Get(AttachedDatabase &db);
138808
138809 PrivateAllocatorData *GetPrivateData() {
138810 return private_data.get();
138811 }
138812
138813 DUCKDB_API static Allocator &DefaultAllocator();
138814 DUCKDB_API static shared_ptr<Allocator> &DefaultAllocatorReference();
138815
138816 static bool SupportsFlush();
138817 static optional_idx DecayDelay();
138818 static void ThreadFlush(bool allocator_background_threads, idx_t threshold, idx_t thread_count);
138819 static void ThreadIdle();
138820 static void FlushAll();
138821 static void SetBackgroundThreads(bool enable);
138822
138823private:
138824 allocate_function_ptr_t allocate_function;
138825 free_function_ptr_t free_function;
138826 reallocate_function_ptr_t reallocate_function;
138827 unique_ptr<PrivateAllocatorData> private_data;
138828
138829 bool ShouldUseDebugInfo() const {
138830 return private_data && private_data->free_type != AllocatorFreeType::DOES_NOT_REQUIRE_FREE &&
138831 private_data->debug_info;
138832 }
138833};
138834
138835template <class T>
138836T *AllocateArray(idx_t size) {
138837 return (T *)Allocator::DefaultAllocator().AllocateData(size * sizeof(T));
138838}
138839
138840template <class T>
138841void DeleteArray(T *ptr, idx_t size) {
138842 Allocator::DefaultAllocator().FreeData(data_ptr_cast(ptr), size * sizeof(T));
138843}
138844
138845template <typename T, typename... ARGS>
138846T *AllocateObject(ARGS &&... args) {
138847 auto data = Allocator::DefaultAllocator().AllocateData(sizeof(T));
138848 return new (data) T(std::forward<ARGS>(args)...);
138849}
138850
138851template <typename T>
138852void DestroyObject(T *ptr) {
138853 ptr->~T();
138854 Allocator::DefaultAllocator().FreeData(data_ptr_cast(ptr), sizeof(T));
138855}
138856
138862struct BufferAllocator {
138863 DUCKDB_API static Allocator &Get(ClientContext &context);
138864 DUCKDB_API static Allocator &Get(DatabaseInstance &db);
138865 DUCKDB_API static Allocator &Get(AttachedDatabase &db);
138866};
138867
138868}
138869
138870
138871
138872
138873
138874
138875
138876
138877
138878
138879
138880
138881
138882
138883
138884
138885namespace duckdb {
138886
138888#define DEFAULT_STANDARD_VECTOR_SIZE 2048U
138889
138891#ifndef STANDARD_VECTOR_SIZE
138892#define STANDARD_VECTOR_SIZE DEFAULT_STANDARD_VECTOR_SIZE
138893#endif
138894
138895#if (STANDARD_VECTOR_SIZE & (STANDARD_VECTOR_SIZE - 1) != 0)
138896#error The vector size must be a power of two
138897#endif
138898
138899}
138900
138901
138902namespace duckdb {
138903class VectorBuffer;
138904
138905struct SelectionData {
138906 DUCKDB_API explicit SelectionData(idx_t count);
138907
138908 AllocatedData owned_data;
138909};
138910
138911struct SelectionVector {
138912 SelectionVector() : sel_vector(nullptr) {
138913 }
138914 explicit SelectionVector(sel_t *sel) {
138915 Initialize(sel);
138916 }
138917 explicit SelectionVector(idx_t count) {
138918 Initialize(count);
138919 }
138920 SelectionVector(idx_t start, idx_t count) {
138921 Initialize(MaxValue<idx_t>(count, STANDARD_VECTOR_SIZE));
138922 for (idx_t i = 0; i < count; i++) {
138923 set_index(i, start + i);
138924 }
138925 }
138926 SelectionVector(const SelectionVector &sel_vector) {
138927 Initialize(sel_vector);
138928 }
138929 explicit SelectionVector(buffer_ptr<SelectionData> data) {
138930 Initialize(std::move(data));
138931 }
138932 SelectionVector &
operator=(SelectionVector &&other)
noexcept {
138933 sel_vector = other.sel_vector;
138934 other.sel_vector = nullptr;
138935 selection_data = std::move(other.selection_data);
138936 return *this;
138937 }
138938
138939public:
138940 static idx_t Inverted(
const SelectionVector &src, SelectionVector &dst, idx_t source_size, idx_t count) {
138941 idx_t src_idx = 0;
138942 idx_t dst_idx = 0;
138943 for (idx_t i = 0; i < count; i++) {
138944 if (src_idx < source_size && src.get_index(src_idx) == i) {
138945 src_idx++;
138946
138947 continue;
138948 }
138949
138950 dst.set_index(dst_idx++, i);
138951 }
138952 return dst_idx;
138953 }
138954
138955 void Initialize(sel_t *sel) {
138956 selection_data.reset();
138957 sel_vector = sel;
138958 }
138959 void Initialize(idx_t count = STANDARD_VECTOR_SIZE) {
138960 selection_data = make_shared_ptr<SelectionData>(count);
138961 sel_vector =
reinterpret_cast<sel_t *
>(selection_data->owned_data.get());
138962 }
138963 void Initialize(buffer_ptr<SelectionData> data) {
138964 selection_data = std::move(data);
138965 sel_vector =
reinterpret_cast<sel_t *
>(selection_data->owned_data.get());
138966 }
138967 void Initialize(const SelectionVector &other) {
138968 selection_data = other.selection_data;
138969 sel_vector = other.sel_vector;
138970 }
138971
138972 inline void set_index(idx_t idx, idx_t loc) {
138973 sel_vector[idx] = UnsafeNumericCast<sel_t>(loc);
138974 }
138975 inline void swap(idx_t i, idx_t j) {
138976 sel_t tmp = sel_vector[i];
138977 sel_vector[i] = sel_vector[j];
138978 sel_vector[j] = tmp;
138979 }
138980 inline idx_t get_index(idx_t idx)
const {
138981 return sel_vector ? get_index_unsafe(idx) : idx;
138982 }
138983 inline idx_t get_index_unsafe(idx_t idx)
const {
138984 return sel_vector[idx];
138985 }
138987 return sel_vector;
138988 }
138989 const sel_t *data()
const {
138990 return sel_vector;
138991 }
138992 buffer_ptr<SelectionData> sel_data() {
138993 return selection_data;
138994 }
138995 buffer_ptr<SelectionData> Slice(const SelectionVector &sel, idx_t count) const;
138996 idx_t SliceInPlace(
const SelectionVector &sel, idx_t count);
138997
138998 string ToString(idx_t count = 0) const;
138999 void Print(idx_t count = 0) const;
139000
139001 inline const sel_t &operator[](idx_t index)
const {
139002 return sel_vector[
index];
139003 }
139004 inline sel_t &operator[](idx_t index) {
139005 return sel_vector[
index];
139006 }
139007 inline bool IsSet() const {
139008 return sel_vector;
139009 }
139010 void Verify(idx_t count, idx_t vector_size) const;
139011 void Sort(idx_t count);
139012
139013private:
139014 sel_t *sel_vector;
139015 buffer_ptr<SelectionData> selection_data;
139016};
139017
139018class OptionalSelection {
139019public:
139020 explicit OptionalSelection(SelectionVector *sel_p) {
139021 Initialize(sel_p);
139022 }
139023 void Initialize(SelectionVector *sel_p) {
139024 sel = sel_p;
139025 if (sel) {
139026 vec.Initialize(sel->data());
139027 sel = &vec;
139028 }
139029 }
139030
139031 inline operator SelectionVector *() {
139032 return sel;
139033 }
139034
139035 inline void Append(idx_t &count, const idx_t idx) {
139036 if (sel) {
139037 sel->set_index(count, idx);
139038 }
139039 ++count;
139040 }
139041
139042 inline void Advance(idx_t completed) {
139043 if (sel) {
139044 sel->Initialize(sel->data() + completed);
139045 }
139046 }
139047
139048private:
139049 SelectionVector *sel;
139050 SelectionVector vec;
139051};
139052
139053}
139054
139055
139056
139057
139058
139059
139060
139061
139062
139063
139064
139065
139066
139067
139068
139069
139070
139071
139072
139073
139074
139075
139076namespace duckdb {
139077using std::to_string;
139078}
139079
139080
139081
139082
139083namespace duckdb {
139084struct SelectionVector;
139085struct ValidityMask;
139086
139087template <typename V>
139088struct TemplatedValidityData {
139089 static constexpr const idx_t BITS_PER_VALUE =
sizeof(V) * 8;
139090 static constexpr const V MAX_ENTRY = V(~V(0));
139091
139092public:
139093 inline explicit TemplatedValidityData(idx_t count) {
139094 auto entry_count = EntryCount(count);
139095 owned_data = make_unsafe_uniq_array_uninitialized<V>(entry_count);
139096 for (idx_t entry_idx = 0; entry_idx < entry_count; entry_idx++) {
139097 owned_data[entry_idx] = MAX_ENTRY;
139098 }
139099 }
139100 inline TemplatedValidityData(const V *validity_mask, idx_t count) {
139101 D_ASSERT(validity_mask);
139102 auto entry_count = EntryCount(count);
139103 owned_data = make_unsafe_uniq_array_uninitialized<V>(entry_count);
139104 for (idx_t entry_idx = 0; entry_idx < entry_count; entry_idx++) {
139105 owned_data[entry_idx] = validity_mask[entry_idx];
139106 }
139107 }
139108
139109 unsafe_unique_array<V> owned_data;
139110
139111public:
139112 static inline idx_t EntryCount(idx_t count) {
139113 return (count + (BITS_PER_VALUE - 1)) / BITS_PER_VALUE;
139114 }
139115};
139116
139118
139119struct ValidityData : TemplatedValidityData<validity_t> {
139120public:
139121 DUCKDB_API explicit ValidityData(idx_t count);
139122 DUCKDB_API ValidityData(const ValidityMask &original, idx_t count);
139123};
139124
139126template <typename V>
139127struct TemplatedValidityMask {
139128 using ValidityBuffer = TemplatedValidityData<V>;
139129
139130public:
139131 static constexpr const idx_t BITS_PER_VALUE = ValidityBuffer::BITS_PER_VALUE;
139132 static constexpr const idx_t STANDARD_ENTRY_COUNT = (STANDARD_VECTOR_SIZE + (BITS_PER_VALUE - 1)) / BITS_PER_VALUE;
139133 static constexpr const idx_t STANDARD_MASK_SIZE = STANDARD_ENTRY_COUNT *
sizeof(V);
139134
139135public:
139136 inline TemplatedValidityMask() : validity_mask(nullptr), capacity(STANDARD_VECTOR_SIZE) {
139137 }
139138 inline explicit TemplatedValidityMask(idx_t target_count) : validity_mask(nullptr), capacity(target_count) {
139139 }
139140 inline explicit TemplatedValidityMask(V *ptr, idx_t capacity) : validity_mask(ptr), capacity(capacity) {
139141 }
139142 inline TemplatedValidityMask(const TemplatedValidityMask &original, idx_t count) {
139143 Copy(original, count);
139144 }
139145
139146 static inline idx_t ValidityMaskSize(idx_t count = STANDARD_VECTOR_SIZE) {
139147 return ValidityBuffer::EntryCount(count) * sizeof(V);
139148 }
139149 inline bool AllValid() const {
139150 return !validity_mask;
139151 }
139152 inline bool CheckAllValid(idx_t count) const {
139153 return CountValid(count) == count;
139154 }
139155 inline bool CheckAllInvalid(idx_t count) const {
139156 return CountValid(count) == 0;
139157 }
139158
139159 inline bool CheckAllValid(idx_t to, idx_t from) const {
139160 if (AllValid()) {
139161 return true;
139162 }
139163 for (idx_t i = from; i < to; i++) {
139164 if (!RowIsValid(i)) {
139165 return false;
139166 }
139167 }
139168 return true;
139169 }
139170
139171 idx_t CountValid(
const idx_t count)
const {
139172 if (AllValid() || count == 0) {
139173 return count;
139174 }
139175
139177 const auto entry_count = EntryCount(count);
139178 for (idx_t entry_idx = 0; entry_idx < entry_count;) {
139179 auto entry = GetValidityEntry(entry_idx++);
139180
139181 if (entry_idx == entry_count && count % BITS_PER_VALUE != 0) {
139182 const auto shift = BITS_PER_VALUE - (count % BITS_PER_VALUE);
139183 const auto mask = ValidityBuffer::MAX_ENTRY >> shift;
139185 } else if (AllValid(entry)) {
139186
139187 valid += BITS_PER_VALUE;
139188 continue;
139189 }
139190
139191
139192 while (entry) {
139193 entry &= (entry - 1);
139194 ++valid;
139195 }
139196 }
139197
139198 return valid;
139199 }
139200
139201 inline V *GetData() const {
139202 return validity_mask;
139203 }
139204 inline void Reset(idx_t target_count_p = STANDARD_VECTOR_SIZE) {
139205 validity_mask = nullptr;
139206 validity_data.reset();
139207 capacity = target_count_p;
139208 }
139209
139210 static inline idx_t EntryCount(idx_t count) {
139211 return ValidityBuffer::EntryCount(count);
139212 }
139213 inline V GetValidityEntry(idx_t entry_idx) const {
139214 if (!validity_mask) {
139215 return ValidityBuffer::MAX_ENTRY;
139216 }
139217 return GetValidityEntryUnsafe(entry_idx);
139218 }
139219 inline V &GetValidityEntryUnsafe(idx_t entry_idx) const {
139220 return validity_mask[entry_idx];
139221 }
139222 static inline bool AllValid(V entry) {
139223
139224 return entry == ValidityBuffer::MAX_ENTRY;
139225 }
139226 static inline bool NoneValid(V entry) {
139227 return entry == 0;
139228 }
139229 static inline bool RowIsValid(const V &entry, const idx_t &idx_in_entry) {
139230 return entry & (V(1) << V(idx_in_entry));
139231 }
139232 static inline void GetEntryIndex(idx_t row_idx, idx_t &entry_idx, idx_t &idx_in_entry) {
139233 entry_idx = row_idx / BITS_PER_VALUE;
139234 idx_in_entry = row_idx % BITS_PER_VALUE;
139235 }
139237 static inline V EntryWithValidBits(idx_t n) {
139238 if (n == 0) {
139239 return V(0);
139240 }
139241 return ValidityBuffer::MAX_ENTRY >> (BITS_PER_VALUE - n);
139242 }
139243 static inline idx_t SizeInBytes(idx_t n) {
139244 return (n + BITS_PER_VALUE - 1) / BITS_PER_VALUE;
139245 }
139246
139249 inline bool RowIsValidUnsafe(idx_t row_idx) const {
139250 D_ASSERT(validity_mask);
139251 idx_t entry_idx, idx_in_entry;
139252 GetEntryIndex(row_idx, entry_idx, idx_in_entry);
139253 auto entry = GetValidityEntryUnsafe(entry_idx);
139254 return RowIsValid(entry, idx_in_entry);
139255 }
139256
139258 inline bool RowIsValid(idx_t row_idx) const {
139259#ifdef DEBUG
139260 if (row_idx >= capacity) {
139261 throw InternalException("ValidityMask::RowIsValid - row_idx %d is out-of-range for mask with capacity %llu",
139262 row_idx, capacity);
139263 }
139264#endif
139265 if (!validity_mask) {
139266 return true;
139267 }
139268 return RowIsValidUnsafe(row_idx);
139269 }
139270
139272 inline void SetValidUnsafe(idx_t row_idx) {
139273 D_ASSERT(validity_mask);
139274 idx_t entry_idx, idx_in_entry;
139275 GetEntryIndex(row_idx, entry_idx, idx_in_entry);
139276 validity_mask[entry_idx] |= (V(1) << V(idx_in_entry));
139277 }
139278
139280 inline void SetValid(idx_t row_idx) {
139281#ifdef DEBUG
139282 if (row_idx >= capacity) {
139283 throw InternalException("ValidityMask::SetValid - row_idx %d is out-of-range for mask with capacity %llu",
139284 row_idx, capacity);
139285 }
139286#endif
139287 if (!validity_mask) {
139288
139289
139290 return;
139291 }
139292 SetValidUnsafe(row_idx);
139293 }
139294
139296 inline void SetInvalidUnsafe(idx_t entry_idx, idx_t idx_in_entry) {
139297 D_ASSERT(validity_mask);
139298 validity_mask[entry_idx] &= ~(V(1) << V(idx_in_entry));
139299 }
139300
139302 inline void SetInvalidUnsafe(idx_t row_idx) {
139303 idx_t entry_idx, idx_in_entry;
139304 GetEntryIndex(row_idx, entry_idx, idx_in_entry);
139305 SetInvalidUnsafe(entry_idx, idx_in_entry);
139306 }
139307
139309 inline void SetInvalid(idx_t row_idx) {
139310#ifdef DEBUG
139311 if (row_idx >= capacity) {
139312 throw InternalException("ValidityMask::SetInvalid - row_idx %d is out-of-range for mask with capacity %llu",
139313 row_idx, capacity);
139314 }
139315#endif
139316 if (!validity_mask) {
139317 Initialize(capacity);
139318 }
139319 SetInvalidUnsafe(row_idx);
139320 }
139321
139323 inline void Set(idx_t row_idx, bool valid) {
139324 if (valid) {
139325 SetValid(row_idx);
139326 } else {
139327 SetInvalid(row_idx);
139328 }
139329 }
139330
139332 inline void EnsureWritable() {
139333 if (!validity_mask) {
139334 Initialize();
139335 }
139336 }
139337
139340 inline void SetRangeInvalid(const idx_t count, const idx_t begin_entry, const idx_t end_entry) {
139341 EnsureWritable();
139342 if (count == 0) {
139343 return;
139344 }
139345 const auto last_entry_index = ValidityBuffer::EntryCount(count) - 1;
139346 for (idx_t i = begin_entry; i < MinValue(last_entry_index, end_entry); i++) {
139347 validity_mask[i] = 0;
139348 }
139349 if (end_entry <= last_entry_index) {
139350 return;
139351 }
139352 const auto last_entry_bits = count % BITS_PER_VALUE;
139353 validity_mask[last_entry_index] =
139354 (last_entry_bits == 0) ? 0 : static_cast<V>(ValidityBuffer::MAX_ENTRY << (last_entry_bits));
139355 }
139356
139358 inline void SetAllInvalid(idx_t count) {
139359 SetRangeInvalid(count, 0, EntryCount(count));
139360 }
139361
139363 inline void SetAllValid(idx_t count) {
139364 EnsureWritable();
139365 if (count == 0) {
139366 return;
139367 }
139368 auto last_entry_index = ValidityBuffer::EntryCount(count) - 1;
139369 for (idx_t i = 0; i < last_entry_index; i++) {
139370 validity_mask[i] = ValidityBuffer::MAX_ENTRY;
139371 }
139372 auto last_entry_bits = count % BITS_PER_VALUE;
139373 validity_mask[last_entry_index] |= (last_entry_bits == 0)
139374 ? ValidityBuffer::MAX_ENTRY
139375 : ~static_cast<V>(ValidityBuffer::MAX_ENTRY << (last_entry_bits));
139376 }
139377
139378 inline bool IsMaskSet() const {
139379 if (validity_mask) {
139380 return true;
139381 }
139382 return false;
139383 }
139384
139385public:
139386 inline void Initialize(validity_t *validity, idx_t new_capacity) {
139387 validity_data.reset();
139388 validity_mask = validity;
139389 capacity = new_capacity;
139390 }
139391 inline void Initialize(const TemplatedValidityMask &other) {
139392 validity_mask = other.validity_mask;
139393 validity_data = other.validity_data;
139394 capacity = other.capacity;
139395 }
139396 inline void Initialize(idx_t count) {
139397 capacity = count;
139398 validity_data = make_buffer<ValidityBuffer>(count);
139399 validity_mask = validity_data->owned_data.get();
139400 }
139401 inline void Initialize() {
139402 Initialize(capacity);
139403 }
139404 inline void Copy(const TemplatedValidityMask &other, idx_t count) {
139405 capacity = count;
139406 if (other.AllValid()) {
139407 validity_data = nullptr;
139408 validity_mask = nullptr;
139409 } else {
139410 validity_data = make_buffer<ValidityBuffer>(other.validity_mask, count);
139411 validity_mask = validity_data->owned_data.get();
139412 }
139413 }
139414
139415protected:
139416 V *validity_mask;
139417 buffer_ptr<ValidityBuffer> validity_data;
139419};
139420
139421struct ValidityMask : public TemplatedValidityMask<validity_t> {
139422public:
139423 inline ValidityMask() : TemplatedValidityMask(nullptr, STANDARD_VECTOR_SIZE) {
139424 }
139425 inline explicit ValidityMask(idx_t capacity) : TemplatedValidityMask(capacity) {
139426 }
139427 inline explicit ValidityMask(validity_t *ptr, idx_t capacity) : TemplatedValidityMask(ptr, capacity) {
139428 }
139429 inline ValidityMask(const ValidityMask &original, idx_t count) : TemplatedValidityMask(original, count) {
139430 }
139431
139432public:
139433 DUCKDB_API void Resize(idx_t new_size);
139434 DUCKDB_API
idx_t Capacity()
const;
139435 DUCKDB_API void SliceInPlace(const ValidityMask &other, idx_t target_offset, idx_t source_offset, idx_t count);
139436 DUCKDB_API void Slice(const ValidityMask &other, idx_t source_offset, idx_t count);
139437 DUCKDB_API void CopySel(const ValidityMask &other, const SelectionVector &sel, idx_t source_offset,
139438 idx_t target_offset, idx_t count);
139439 DUCKDB_API void Combine(const ValidityMask &other, idx_t count);
139440 DUCKDB_API string ToString(idx_t count) const;
139441 DUCKDB_API string ToString() const;
139442
139443 DUCKDB_API static bool IsAligned(idx_t count);
139444
139445 void Write(WriteStream &writer, idx_t count);
139446 void Read(ReadStream &reader, idx_t count);
139447};
139448
139449
139450
139451
139452struct ValidityArray {
139453 inline ValidityArray() {
139454 }
139455
139456 inline bool AllValid() const {
139457 return !validity_mask;
139458 }
139459
139460 inline void Initialize(idx_t count, bool initial = true) {
139461 capacity = count;
139462 validity_data = make_unsafe_uniq_array<bool>(count);
139463 validity_mask = validity_data.get();
139464 memset(validity_mask, initial, sizeof(bool) * count);
139465 }
139466 inline void InitializeEmpty(idx_t count) {
139467 capacity = count;
139468 }
139469
139470 idx_t Capacity()
const {
139471 return capacity;
139472 }
139473
139476 inline bool RowIsValidUnsafe(idx_t row_idx) const {
139477 D_ASSERT(validity_mask);
139478 return validity_mask[row_idx];
139479 }
139480
139482 inline bool RowIsValid(idx_t row_idx) const {
139483#ifdef DEBUG
139484 if (row_idx >= capacity) {
139485 throw InternalException("ValidityData::RowIsValid - row_idx %d is out-of-range for mask with capacity %llu",
139486 row_idx, capacity);
139487 }
139488#endif
139489 if (!validity_mask) {
139490 return true;
139491 }
139492 return RowIsValidUnsafe(row_idx);
139493 }
139494
139496 inline void SetValidUnsafe(idx_t row_idx) {
139497 D_ASSERT(validity_mask);
139498 validity_mask[row_idx] = true;
139499 }
139500
139502 inline void SetValid(idx_t row_idx) {
139503#ifdef DEBUG
139504 if (row_idx >= capacity) {
139505 throw InternalException("ValidityData::SetValid - row_idx %d is out-of-range for mask with capacity %llu",
139506 row_idx, capacity);
139507 }
139508#endif
139509 if (!validity_mask) {
139510
139511
139512 return;
139513 }
139514
139515 SetValidUnsafe(row_idx);
139516 }
139517
139518 inline void Pack(ValidityMask &mask, const idx_t count) const {
139519 if (AllValid()) {
139520 mask.Reset(count);
139521 return;
139522 }
139523 mask.Initialize(count);
139524
139525 const auto entire_entries = count / ValidityMask::BITS_PER_VALUE;
139526 const auto ragged = count % ValidityMask::BITS_PER_VALUE;
139527 auto bits =
mask.GetData();
139528 idx_t row_idx = 0;
139529 for (idx_t i = 0; i < entire_entries; ++i) {
139530 validity_t entry = 0;
139531 for (idx_t j = 0; j < ValidityMask::BITS_PER_VALUE; ++j) {
139532 if (RowIsValidUnsafe(row_idx++)) {
139533 entry |= validity_t(1) << j;
139534 }
139535 }
139536 *bits++ = entry;
139537 }
139538 if (ragged) {
139539 validity_t entry = 0;
139540 for (idx_t j = 0; j < ragged; ++j) {
139541 if (RowIsValidUnsafe(row_idx++)) {
139542 entry |= validity_t(1) << j;
139543 }
139544 }
139545 *bits++ = entry;
139546 }
139547 }
139548
139549private:
139550 bool *validity_mask = nullptr;
139551 unsafe_unique_array<bool> validity_data;
139552 idx_t capacity = 0;
139553};
139554
139555}
139556
139557
139558
139559
139560
139561
139562
139563
139564
139565
139566
139567
139568
139569
139570
139571
139572
139573
139574
139575
139576
139577
139578
139579
139580
139581
139582
139583
139584
139585
139586
139587
139588
139589
139590
139591
139592
139593
139594
139595
139596
139597
139598
139599
139600
139601
139602
139603
139604
139605
139606
139607namespace duckdb {
139608
139610template <class T>
139611struct arena_deleter {
139613 pointer->~T();
139614 }
139615};
139616
139617template <class T>
139618using arena_ptr = unique_ptr<T, arena_deleter<T>>;
139619
139620template <class T>
139621using unsafe_arena_ptr = unique_ptr<T, arena_deleter<T>, false>;
139622
139623}
139624
139625
139626namespace duckdb {
139627
139628struct ArenaChunk {
139629 ArenaChunk(Allocator &allocator, idx_t size);
139630 ~ArenaChunk();
139631
139632 AllocatedData data;
139633 idx_t current_position;
139634 idx_t maximum_size;
139635 unsafe_unique_ptr<ArenaChunk> next;
139636 ArenaChunk *prev;
139637};
139638
139639class ArenaAllocator {
139640public:
139641 static constexpr const idx_t ARENA_ALLOCATOR_INITIAL_CAPACITY = 2048;
139642 static constexpr const idx_t ARENA_ALLOCATOR_MAX_CAPACITY = 1ULL << 24ULL;
139643
139644public:
139645 DUCKDB_API explicit ArenaAllocator(Allocator &allocator, idx_t initial_capacity = ARENA_ALLOCATOR_INITIAL_CAPACITY);
139646 DUCKDB_API ~ArenaAllocator();
139647
139648 data_ptr_t Allocate(idx_t len) {
139649 D_ASSERT(!head || head->current_position <= head->maximum_size);
139650 if (!head || head->current_position + len > head->maximum_size) {
139651 AllocateNewBlock(len);
139652 }
139653 D_ASSERT(head->current_position + len <= head->maximum_size);
139654 auto result = head->data.get() + head->current_position;
139655 head->current_position += len;
139656 return result;
139657 }
139658 DUCKDB_API data_ptr_t Reallocate(data_ptr_t pointer, idx_t old_size, idx_t size);
139659
139660 DUCKDB_API data_ptr_t AllocateAligned(idx_t size);
139661 DUCKDB_API data_ptr_t ReallocateAligned(data_ptr_t pointer, idx_t old_size, idx_t size);
139662
139664 DUCKDB_API void AlignNext();
139665
139668 DUCKDB_API void ShrinkHead(idx_t shrink_size) const {
139669 D_ASSERT(head && head->current_position >= shrink_size);
139670 head->current_position -= shrink_size;
139671 }
139672
139674 DUCKDB_API void Reset();
139675 DUCKDB_API void Destroy();
139676 DUCKDB_API void Move(ArenaAllocator &allocator);
139677
139678 DUCKDB_API ArenaChunk *GetHead();
139679 DUCKDB_API ArenaChunk *GetTail();
139680
139681 DUCKDB_API bool IsEmpty() const;
139683 DUCKDB_API
idx_t SizeInBytes()
const;
139685 DUCKDB_API
idx_t AllocationSize()
const;
139686
139688 Allocator &GetAllocator() {
139689 return arena_allocator;
139690 }
139691
139692 template <class T, class... ARGS>
139693 T *Make(ARGS &&... args) {
139694 auto mem = AllocateAligned(sizeof(T));
139695 return new (mem) T(std::forward<ARGS>(args)...);
139696 }
139697
139698 template <class T, class... ARGS>
139699 arena_ptr<T> MakePtr(ARGS &&... args) {
139700 return arena_ptr<T>(Make<T>(std::forward<ARGS>(args)...));
139701 }
139702
139703 template <class T, class... ARGS>
139704 unsafe_arena_ptr<T> MakeUnsafePtr(ARGS &&... args) {
139705 return unsafe_arena_ptr<T>(Make<T>(std::forward<ARGS>(args)...));
139706 }
139707
139708 String MakeString(
const char *data,
const size_t len) {
139709 data_ptr_t mem = nullptr;
139710
139711 D_ASSERT(len < NumericLimits<uint32_t>::Maximum());
139713 if (!String::CanBeInlined(size)) {
139714
139715 mem = AllocateAligned(sizeof(char) * size + 1);
139716 memcpy(mem, data, size);
139718 }
139719
139720 return String::Reference(mem ? reinterpret_cast<char *>(mem) : data, size);
139721 }
139722
139723 String MakeString(
const std::string &data) {
139724 return MakeString(data.c_str(), data.size());
139725 }
139726
139727private:
139728 void AllocateNewBlock(idx_t min_size);
139729
139730private:
139732 Allocator &allocator;
139733 idx_t initial_capacity;
139734 unsafe_unique_ptr<ArenaChunk> head;
139735 ArenaChunk *tail;
139737 Allocator arena_allocator;
139739 idx_t allocated_size = 0;
139740};
139741
139742}
139743
139744
139745namespace duckdb {
139749class StringHeap {
139750public:
139751 DUCKDB_API explicit StringHeap(Allocator &allocator = Allocator::DefaultAllocator());
139752
139753 DUCKDB_API void Destroy();
139754 DUCKDB_API void Move(StringHeap &other);
139755
139757 DUCKDB_API string_t AddString(const char *data, idx_t len);
139759 DUCKDB_API string_t AddString(const char *data);
139761 DUCKDB_API string_t AddString(const string &data);
139763 DUCKDB_API string_t AddString(const string_t &data);
139765 DUCKDB_API string_t AddBlob(const string_t &data);
139767 DUCKDB_API string_t AddBlob(const char *data, idx_t len);
139769 DUCKDB_API string_t EmptyString(idx_t len);
139770
139772 DUCKDB_API
idx_t SizeInBytes()
const;
139774 DUCKDB_API
idx_t AllocationSize()
const;
139775
139776 DUCKDB_API ArenaAllocator &GetAllocator() {
139777 return allocator;
139778 }
139779
139780private:
139781 ArenaAllocator allocator;
139782};
139783
139784}
139785
139786
139787
139788
139789
139790
139791
139792
139793
139794
139795
139796
139797
139798
139799
139800
139801
139802
139803
139804
139805
139806
139807
139808
139809
139810
139811
139812namespace duckdb {
139813
139814struct FileHandle;
139815class QueryContext;
139816
139818#define DEFAULT_ROW_GROUP_SIZE 122880ULL
139820#define INVALID_BLOCK (-1)
139822#define MAXIMUM_BLOCK 4611686018427388000LL
139823
139825#define DEFAULT_BLOCK_ALLOC_SIZE 262144ULL
139827#define DEFAULT_BLOCK_HEADER_STORAGE_SIZE 8ULL
139829#define DEFAULT_ENCRYPTION_BLOCK_HEADER_SIZE 40ULL
139831
139832
139833#ifndef DUCKDB_BLOCK_HEADER_STORAGE_SIZE
139834#define DUCKDB_BLOCK_HEADER_STORAGE_SIZE DEFAULT_BLOCK_HEADER_STORAGE_SIZE
139835#endif
139836
139837#ifndef DEFAULT_ENCRYPTED_BUFFER_HEADER_SIZE
139838#define DEFAULT_ENCRYPTED_BUFFER_HEADER_SIZE 32ULL
139839#endif
139840
139842
139843struct Storage {
139845 constexpr static idx_t SECTOR_SIZE = 4096U;
139848 constexpr static idx_t FILE_HEADER_SIZE = 4096U;
139850 constexpr static const idx_t MAX_ROW_GROUP_SIZE = 1ULL << 30ULL;
139852 constexpr static idx_t MIN_BLOCK_ALLOC_SIZE = 16384ULL;
139854 constexpr static idx_t MAX_BLOCK_ALLOC_SIZE = 262144ULL;
139856 constexpr static idx_t DEFAULT_BLOCK_HEADER_SIZE =
sizeof(
idx_t);
139858 constexpr static idx_t MAX_BLOCK_HEADER_SIZE = 128ULL;
139860 constexpr static idx_t DEFAULT_BLOCK_SIZE = DEFAULT_BLOCK_ALLOC_SIZE - DEFAULT_BLOCK_HEADER_SIZE;
139861
139863 static void VerifyBlockAllocSize(const idx_t block_alloc_size);
139864 static void VerifyBlockHeaderSize(const idx_t block_header_size);
139865};
139866
139869extern const uint64_t VERSION_NUMBER_LOWER;
139870extern const uint64_t VERSION_NUMBER_UPPER;
139871string GetDuckDBVersions(const idx_t version_number);
139872optional_idx GetStorageVersion(const char *version_string);
139873string GetStorageVersionName(const idx_t serialization_version, const bool add_suffix);
139874optional_idx GetSerializationVersion(const char *version_string);
139875vector<string> GetSerializationCandidates();
139876
139879class MainHeader {
139880public:
139881 static constexpr idx_t MAX_VERSION_SIZE = 32;
139882 static constexpr idx_t MAGIC_BYTE_SIZE = 4;
139883 static constexpr idx_t MAGIC_BYTE_OFFSET = Storage::DEFAULT_BLOCK_HEADER_SIZE;
139884 static constexpr idx_t FLAG_COUNT = 4;
139885
139887 static constexpr uint64_t ENCRYPTED_DATABASE_FLAG = 1;
139889 static constexpr uint64_t DEFAULT_ENCRYPTION_KEY_LENGTH = 32;
139891 static const char MAGIC_BYTES[];
139893 static const char CANARY[];
139894
139901
139903 static constexpr idx_t DB_IDENTIFIER_LEN = 16;
139905 static constexpr idx_t ENCRYPTION_METADATA_LEN = 8;
139907 static constexpr idx_t CANARY_BYTE_SIZE = 8;
139909 static constexpr uint64_t AES_NONCE_LEN = 12;
139910 static constexpr uint64_t AES_COUNTER_BYTES = 4;
139911 static constexpr uint64_t AES_NONCE_LEN_DEPRECATED = 16;
139912 static constexpr uint64_t AES_IV_LEN = 16;
139913 static constexpr uint64_t AES_TAG_LEN = 16;
139914
139915 static void CheckMagicBytes(QueryContext context, FileHandle &handle);
139916
139917 string LibraryGitDesc() {
139918 return string(char_ptr_cast(library_git_desc), 0, MAX_VERSION_SIZE);
139919 }
139920 string LibraryGitHash() {
139921 return string(char_ptr_cast(library_git_hash), 0, MAX_VERSION_SIZE);
139922 }
139923
139924 bool IsEncrypted() const {
139926 }
139927 void SetEncrypted() {
139929 }
139930 void SetEncryptionVersion(uint8_t version) {
139931 encryption_version = version;
139932 }
139933
139934 void SetEncryptionMetadata(data_ptr_t source) {
139935 memset(encryption_metadata, 0, ENCRYPTION_METADATA_LEN);
139936 memcpy(encryption_metadata, source, ENCRYPTION_METADATA_LEN);
139937 }
139938
139939 uint8_t GetEncryptionCipher()
const {
139940 return encryption_metadata[2];
139941 }
139942
139943 uint8_t GetEncryptionVersion()
const {
139944 return encryption_metadata[3];
139945 }
139946
139947 void SetDBIdentifier(data_ptr_t source) {
139948 memset(db_identifier, 0, DB_IDENTIFIER_LEN);
139949 memcpy(db_identifier, source, DB_IDENTIFIER_LEN);
139950 }
139951
139952 void SetEncryptedCanary(data_ptr_t source) {
139953 memset(encrypted_canary, 0, CANARY_BYTE_SIZE);
139954 memcpy(encrypted_canary, source, CANARY_BYTE_SIZE);
139955 }
139956
139957 void SetCanaryIV(data_ptr_t source) {
139958 memset(canary_iv, 0, AES_NONCE_LEN);
139959 memcpy(canary_iv, source, AES_NONCE_LEN);
139960 }
139961
139962 void SetCanaryTag(data_ptr_t source) {
139963 memset(canary_tag, 0, AES_TAG_LEN);
139964 memcpy(canary_tag, source, AES_TAG_LEN);
139965 }
139966
139967 data_ptr_t GetDBIdentifier() {
139968 return db_identifier;
139969 }
139970
139971 data_ptr_t GetIV() {
139972 return canary_iv;
139973 }
139974
139975 data_ptr_t GetTag() {
139976 return canary_tag;
139977 }
139978
139979 static bool CompareDBIdentifiers(const data_ptr_t db_identifier_1, const data_ptr_t db_identifier_2) {
139980 for (idx_t i = 0; i < DB_IDENTIFIER_LEN; i++) {
139981 if (db_identifier_1[i] != db_identifier_2[i]) {
139982 return false;
139983 }
139984 }
139985 return true;
139986 }
139987
139988 data_ptr_t GetEncryptedCanary() {
139989 return encrypted_canary;
139990 }
139991
139992 void Write(WriteStream &ser);
139993 static MainHeader Read(ReadStream &source);
139994
139995private:
139996 data_t library_git_desc[MAX_VERSION_SIZE];
139997 data_t library_git_hash[MAX_VERSION_SIZE];
139998 data_t encryption_metadata[ENCRYPTION_METADATA_LEN];
140000 data_t db_identifier[DB_IDENTIFIER_LEN];
140001 data_t encrypted_canary[CANARY_BYTE_SIZE];
140002 data_t canary_iv[AES_NONCE_LEN];
140003 data_t canary_tag[AES_TAG_LEN];
140004};
140005
140010struct DatabaseHeader {
140014 idx_t meta_block = 0;
140016 idx_t free_list = 0;
140021 idx_t block_alloc_size = 0;
140023 idx_t vector_size = 0;
140025 idx_t serialization_compatibility = 0;
140026
140027 void Write(WriteStream &ser);
140028 static DatabaseHeader Read(const MainHeader &header, ReadStream &source);
140029};
140030
140032
140033#if (DEFAULT_ROW_GROUP_SIZE % STANDARD_VECTOR_SIZE != 0)
140034#error The row group size must be a multiple of the vector size
140035#endif
140036#if (DEFAULT_ROW_GROUP_SIZE < STANDARD_VECTOR_SIZE)
140037#error Row groups must be able to hold at least one vector
140038#endif
140039#if (DEFAULT_BLOCK_ALLOC_SIZE & (DEFAULT_BLOCK_ALLOC_SIZE - 1) != 0)
140040#error The default block allocation size must be a power of two
140041#endif
140042
140043}
140044
140045
140046
140047namespace duckdb {
140048class BlockHandle;
140049class FileBuffer;
140050
140051class BufferHandle {
140052public:
140053 DUCKDB_API BufferHandle();
140054 DUCKDB_API explicit BufferHandle(shared_ptr<BlockHandle> handle, optional_ptr<FileBuffer> node);
140055 DUCKDB_API ~BufferHandle();
140056
140057 BufferHandle(const BufferHandle &other) = delete;
140058 BufferHandle &
operator=(
const BufferHandle &) =
delete;
140060 DUCKDB_API BufferHandle(BufferHandle &&other) noexcept;
140061 DUCKDB_API BufferHandle &
operator=(BufferHandle &&) noexcept;
140062
140063public:
140065 DUCKDB_API bool IsValid() const;
140067 inline data_ptr_t
Ptr()
const {
140068 D_ASSERT(IsValid());
140069 return node->buffer;
140070 }
140072 inline data_ptr_t
Ptr() {
140073 D_ASSERT(IsValid());
140074 return node->buffer;
140075 }
140077 DUCKDB_API FileBuffer &GetFileBuffer();
140079 DUCKDB_API void Destroy();
140080
140081 const shared_ptr<BlockHandle> &GetBlockHandle() const {
140082 return handle;
140083 }
140084
140085private:
140087 shared_ptr<BlockHandle> handle;
140089 optional_ptr<FileBuffer> node;
140090};
140091
140092}
140093
140094
140095namespace duckdb {
140096
140097class BufferHandle;
140098class VectorBuffer;
140099class Vector;
140100
140101enum class VectorBufferType :
uint8_t {
140102 STANDARD_BUFFER,
140103 DICTIONARY_BUFFER,
140104 VECTOR_CHILD_BUFFER,
140105 STRING_BUFFER,
140106 FSST_BUFFER,
140107 STRUCT_BUFFER,
140108 LIST_BUFFER,
140109 MANAGED_BUFFER,
140110 OPAQUE_BUFFER,
140111 ARRAY_BUFFER
140112};
140113
140114enum class VectorAuxiliaryDataType :
uint8_t {
140115 ARROW_AUXILIARY
140116};
140117
140118struct VectorAuxiliaryData {
140119 explicit VectorAuxiliaryData(VectorAuxiliaryDataType type_p)
140120 : type(type_p) {
140121
140122 };
140123 VectorAuxiliaryDataType type;
140124
140125 virtual ~VectorAuxiliaryData() {
140126 }
140127
140128public:
140129 template <class TARGET>
140130 TARGET &Cast() {
140131 if (type != TARGET::TYPE) {
140132 throw InternalException("Failed to cast vector auxiliary data to type - type mismatch");
140133 }
140134 return reinterpret_cast<TARGET &>(*this);
140135 }
140136
140137 template <class TARGET>
140138 const TARGET &Cast() const {
140139 if (type != TARGET::TYPE) {
140140 throw InternalException("Failed to cast vector auxiliary data to type - type mismatch");
140141 }
140142 return reinterpret_cast<const TARGET &>(*this);
140143 }
140144};
140145
140147class VectorBuffer {
140148public:
140149 explicit VectorBuffer(VectorBufferType type) : buffer_type(type) {
140150 }
140151 explicit VectorBuffer(idx_t data_size) : buffer_type(VectorBufferType::STANDARD_BUFFER) {
140152 if (data_size > 0) {
140153 data = Allocator::DefaultAllocator().Allocate(data_size);
140154 }
140155 }
140156 explicit VectorBuffer(AllocatedData &&data_p)
140157 : buffer_type(VectorBufferType::STANDARD_BUFFER), data(std::move(data_p)) {
140158 }
140159 virtual ~VectorBuffer() {
140160 }
140161 VectorBuffer() {
140162 }
140163
140164public:
140165 data_ptr_t GetData() {
140166 return data.get();
140167 }
140168
140169 void SetData(AllocatedData &&new_data) {
140170 data = std::move(new_data);
140171 }
140172
140173 VectorAuxiliaryData *GetAuxiliaryData() {
140174 return aux_data.get();
140175 }
140176
140177 void SetAuxiliaryData(unique_ptr<VectorAuxiliaryData> aux_data_p) {
140178 aux_data = std::move(aux_data_p);
140179 }
140180
140181 void MoveAuxiliaryData(VectorBuffer &source_buffer) {
140182 SetAuxiliaryData(std::move(source_buffer.aux_data));
140183 }
140184
140185 virtual optional_ptr<Allocator> GetAllocator() const {
140186 return data.GetAllocator();
140187 }
140188
140189 static buffer_ptr<VectorBuffer> CreateStandardVector(PhysicalType type, idx_t capacity = STANDARD_VECTOR_SIZE);
140190 static buffer_ptr<VectorBuffer> CreateConstantVector(PhysicalType type);
140191 static buffer_ptr<VectorBuffer> CreateConstantVector(const LogicalType &logical_type);
140192 static buffer_ptr<VectorBuffer> CreateStandardVector(const LogicalType &logical_type,
140193 idx_t capacity = STANDARD_VECTOR_SIZE);
140194
140195 inline VectorBufferType GetBufferType() const {
140196 return buffer_type;
140197 }
140198
140199 inline VectorAuxiliaryDataType GetAuxiliaryDataType() const {
140200 return aux_data->type;
140201 }
140202
140203protected:
140204 VectorBufferType buffer_type;
140205 unique_ptr<VectorAuxiliaryData> aux_data;
140206 AllocatedData data;
140207
140208public:
140209 template <class TARGET>
140210 TARGET &Cast() {
140211 DynamicCastCheck<TARGET>(this);
140212 return reinterpret_cast<TARGET &>(*this);
140213 }
140214 template <class TARGET>
140215 const TARGET &Cast() const {
140216 DynamicCastCheck<TARGET>(this);
140217 return reinterpret_cast<const TARGET &>(*this);
140218 }
140219};
140220
140222class DictionaryBuffer : public VectorBuffer {
140223public:
140224 explicit DictionaryBuffer(const SelectionVector &sel)
140225 : VectorBuffer(VectorBufferType::DICTIONARY_BUFFER), sel_vector(sel) {
140226 }
140227 explicit DictionaryBuffer(buffer_ptr<SelectionData> data)
140228 : VectorBuffer(VectorBufferType::DICTIONARY_BUFFER), sel_vector(std::move(data)) {
140229 }
140230 explicit DictionaryBuffer(idx_t count = STANDARD_VECTOR_SIZE)
140231 : VectorBuffer(VectorBufferType::DICTIONARY_BUFFER), sel_vector(count) {
140232 }
140233
140234public:
140235 const SelectionVector &GetSelVector() const {
140236 return sel_vector;
140237 }
140238 SelectionVector &GetSelVector() {
140239 return sel_vector;
140240 }
140241 void SetSelVector(const SelectionVector &vector) {
140242 this->sel_vector.Initialize(vector);
140243 }
140244 void SetDictionarySize(idx_t dict_size) {
140245 dictionary_size = dict_size;
140246 }
140247 optional_idx GetDictionarySize() const {
140248 return dictionary_size;
140249 }
140250 void SetDictionaryId(string id) {
140251 dictionary_id = std::move(id);
140252 }
140253 const string &GetDictionaryId() const {
140254 return dictionary_id;
140255 }
140256
140257private:
140258 SelectionVector sel_vector;
140259 optional_idx dictionary_size;
140261 string dictionary_id;
140262};
140263
140264class VectorStringBuffer : public VectorBuffer {
140265public:
140266 VectorStringBuffer();
140267 explicit VectorStringBuffer(Allocator &allocator);
140268 explicit VectorStringBuffer(VectorBufferType type);
140269
140270public:
140271 string_t AddString(const char *data, idx_t len) {
140272 return heap.AddString(data, len);
140273 }
140274 string_t AddString(string_t data) {
140275 return heap.AddString(data);
140276 }
140277 string_t AddBlob(string_t data) {
140278 return heap.AddBlob(data.GetData(), data.GetSize());
140279 }
140280 string_t EmptyString(idx_t len) {
140281 return heap.EmptyString(len);
140282 }
140283
140284 ArenaAllocator &GetStringAllocator() {
140285 return heap.GetAllocator();
140286 }
140290 data_ptr_t AllocateShrinkableBuffer(idx_t alloc_len) {
140291 auto &allocator = heap.GetAllocator();
140292 return allocator.Allocate(alloc_len);
140293 }
140296 string_t FinalizeShrinkableBuffer(data_ptr_t buffer, idx_t alloc_len, idx_t str_len) {
140297 auto &allocator = heap.GetAllocator();
140298 D_ASSERT(str_len <= alloc_len);
140299 D_ASSERT(buffer == allocator.GetHead()->data.get() + allocator.GetHead()->current_position - alloc_len);
140300 bool is_not_inlined = str_len > string_t::INLINE_LENGTH;
140301 idx_t shrink_count = alloc_len - (str_len * is_not_inlined);
140302 allocator.ShrinkHead(shrink_count);
140303 return string_t(const_char_ptr_cast(buffer), UnsafeNumericCast<uint32_t>(str_len));
140304 }
140305
140306 void AddHeapReference(buffer_ptr<VectorBuffer> heap) {
140307 references.push_back(std::move(heap));
140308 }
140309
140310private:
140312 StringHeap heap;
140314 vector<buffer_ptr<VectorBuffer>> references;
140315};
140316
140317class VectorFSSTStringBuffer : public VectorStringBuffer {
140318public:
140319 VectorFSSTStringBuffer();
140320
140321public:
140322 void AddDecoder(buffer_ptr<void> &duckdb_fsst_decoder_p, const idx_t string_block_limit) {
140323 duckdb_fsst_decoder = duckdb_fsst_decoder_p;
140324 decompress_buffer.resize(string_block_limit + 1);
140325 }
140326 void *GetDecoder() {
140327 return duckdb_fsst_decoder.get();
140328 }
140329 vector<unsigned char> &GetDecompressBuffer() {
140330 return decompress_buffer;
140331 }
140332 void SetCount(idx_t count) {
140333 total_string_count = count;
140334 }
140335 idx_t GetCount() {
140336 return total_string_count;
140337 }
140338
140339private:
140340 buffer_ptr<void> duckdb_fsst_decoder;
140341 idx_t total_string_count = 0;
140342 vector<unsigned char> decompress_buffer;
140343};
140344
140345class VectorStructBuffer : public VectorBuffer {
140346public:
140347 VectorStructBuffer();
140348 explicit VectorStructBuffer(const LogicalType &struct_type, idx_t capacity = STANDARD_VECTOR_SIZE);
140349 VectorStructBuffer(Vector &other, const SelectionVector &sel, idx_t count);
140350 ~VectorStructBuffer() override;
140351
140352public:
140353 const vector<unique_ptr<Vector>> &GetChildren() const {
140354 return children;
140355 }
140356 vector<unique_ptr<Vector>> &GetChildren() {
140357 return children;
140358 }
140359
140360private:
140362 vector<unique_ptr<Vector>> children;
140363};
140364
140365class VectorListBuffer : public VectorBuffer {
140366public:
140367 explicit VectorListBuffer(unique_ptr<Vector> vector, idx_t initial_capacity = STANDARD_VECTOR_SIZE);
140368 explicit VectorListBuffer(const LogicalType &list_type, idx_t initial_capacity = STANDARD_VECTOR_SIZE);
140369 ~VectorListBuffer() override;
140370
140371public:
140372 Vector &GetChild() {
140373 return *child;
140374 }
140375 void Reserve(idx_t to_reserve);
140376
140377 void Append(const Vector &to_append, idx_t to_append_size, idx_t source_offset = 0);
140378 void Append(const Vector &to_append, const SelectionVector &sel, idx_t to_append_size, idx_t source_offset = 0);
140379
140380 void PushBack(const Value &insert);
140381
140384 }
140385
140386 idx_t GetCapacity() {
140387 return capacity;
140388 }
140389
140390 void SetCapacity(idx_t new_capacity);
140391 void SetSize(idx_t new_size);
140392
140393private:
140395 unique_ptr<Vector> child;
140396 idx_t capacity = 0;
140398};
140399
140400class VectorArrayBuffer : public VectorBuffer {
140401public:
140402 explicit VectorArrayBuffer(unique_ptr<Vector> child_vector, idx_t array_size, idx_t initial_capacity);
140403 explicit VectorArrayBuffer(const LogicalType &array, idx_t initial = STANDARD_VECTOR_SIZE);
140404 ~VectorArrayBuffer() override;
140405
140406public:
140407 Vector &GetChild();
140408 idx_t GetArraySize();
140409 idx_t GetChildSize();
140410
140411private:
140412 unique_ptr<Vector> child;
140413
140414 idx_t array_size = 0;
140415
140416
140418};
140419
140421class ManagedVectorBuffer : public VectorBuffer {
140422public:
140423 explicit ManagedVectorBuffer(BufferHandle handle);
140424 ~ManagedVectorBuffer() override;
140425
140426private:
140427 BufferHandle handle;
140428};
140429
140430}
140431
140432
140433
140434
140435
140436
140437
140438
140439
140440
140441
140442
140443
140444
140445
140446
140447
140448
140449
140450
140451
140452
140453
140454
140455
140456
140457
140458
140459
140460#include <cmath>
140461
140462namespace duckdb {
140463
140464
140465struct double_na_equal {
140466 double_na_equal() : val(0) {
140467 }
140468 explicit double_na_equal(const double val_p) : val(val_p) {
140469 }
140470
140471 operator double() const {
140472 return val;
140473 }
140474
140475 bool operator==(
const double &right)
const {
140476 if (std::isnan(val) && std::isnan(right)) {
140477 return true;
140478 }
140479 return val == right;
140480 }
140481
140482 bool operator!=(
const double &right)
const {
140483 return !(*this == right);
140484 }
140485
140486 double val;
140487};
140488
140489struct float_na_equal {
140490 float_na_equal() : val(0) {
140491 }
140492 explicit float_na_equal(const float val_p) : val(val_p) {
140493 }
140494
140495 operator float() const {
140496 return val;
140497 }
140498
140499 bool operator==(
const float &right)
const {
140500 if (std::isnan(val) && std::isnan(right)) {
140501 return true;
140502 }
140503 return val == right;
140504 }
140505
140506 bool operator!=(
const float &right)
const {
140507 return !(*this == right);
140508 }
140509
140510 float val;
140511};
140512
140513}
140514
140515
140516namespace duckdb {
140517struct bignum_t;
140518
140520template <class T>
140522 using TYPE =
typename std::remove_cv<T>::type;
140523
140524 if (std::is_same<TYPE, bool>()) {
140525 return PhysicalType::BOOL;
140526 } else if (std::is_same<TYPE, int8_t>()) {
140527 return PhysicalType::INT8;
140528 } else if (std::is_same<TYPE, int16_t>()) {
140529 return PhysicalType::INT16;
140530 } else if (std::is_same<TYPE, int32_t>()) {
140531 return PhysicalType::INT32;
140532 } else if (std::is_same<TYPE, int64_t>()) {
140533 return PhysicalType::INT64;
140534 } else if (std::is_same<TYPE, uint8_t>()) {
140535 return PhysicalType::UINT8;
140536 } else if (std::is_same<TYPE, uint16_t>()) {
140537 return PhysicalType::UINT16;
140538 } else if (std::is_same<TYPE, uint32_t>()) {
140539 return PhysicalType::UINT32;
140540 } else if (std::is_same<TYPE, uint64_t>()) {
140541 return PhysicalType::UINT64;
140542 } else if (std::is_same<TYPE, idx_t>() || std::is_same<TYPE, const idx_t>()) {
140543 return PhysicalType::UINT64;
140544 } else if (std::is_same<TYPE, hugeint_t>()) {
140545 return PhysicalType::INT128;
140546 } else if (std::is_same<TYPE, uhugeint_t>()) {
140547 return PhysicalType::UINT128;
140548 } else if (std::is_same<TYPE, date_t>()) {
140549 return PhysicalType::INT32;
140550 } else if (std::is_same<TYPE, dtime_t>()) {
140551 return PhysicalType::INT64;
140552 } else if (std::is_same<TYPE, dtime_tz_t>()) {
140553 return PhysicalType::INT64;
140554 } else if (std::is_same<TYPE, dtime_ns_t>()) {
140555 return PhysicalType::INT64;
140556 } else if (std::is_same<TYPE, timestamp_t>()) {
140557 return PhysicalType::INT64;
140558 } else if (std::is_same<TYPE, timestamp_sec_t>()) {
140559 return PhysicalType::INT64;
140560 } else if (std::is_same<TYPE, timestamp_ms_t>()) {
140561 return PhysicalType::INT64;
140562 } else if (std::is_same<TYPE, timestamp_ns_t>()) {
140563 return PhysicalType::INT64;
140564 } else if (std::is_same<TYPE, timestamp_tz_t>()) {
140565 return PhysicalType::INT64;
140566 } else if (std::is_same<TYPE, float>() || std::is_same<TYPE, float_na_equal>()) {
140567 return PhysicalType::FLOAT;
140568 } else if (std::is_same<TYPE, double>() || std::is_same<TYPE, double_na_equal>()) {
140569 return PhysicalType::DOUBLE;
140570 } else if (std::is_same<TYPE, const char *>() || std::is_same<TYPE, char *>() || std::is_same<TYPE, string_t>() ||
140571 std::is_same<TYPE, bignum_t>()) {
140572 return PhysicalType::VARCHAR;
140573 } else if (std::is_same<TYPE, interval_t>()) {
140574 return PhysicalType::INTERVAL;
140575 } else if (std::is_same<TYPE, list_entry_t>()) {
140576 return PhysicalType::LIST;
140577 } else if (std::is_pointer<TYPE>() || std::is_same<TYPE, uintptr_t>()) {
140578 if (sizeof(uintptr_t) == sizeof(uint32_t)) {
140579 return PhysicalType::UINT32;
140580 } else if (sizeof(uintptr_t) == sizeof(uint64_t)) {
140581 return PhysicalType::UINT64;
140582 } else {
140583 throw InternalException("Unsupported pointer size in GetTypeId");
140584 }
140585 } else {
140586 throw InternalException("Unsupported type in GetTypeId");
140587 }
140588}
140589
140590template <class T>
140591bool StorageTypeCompatible(PhysicalType type) {
140592 using TYPE =
typename std::remove_cv<T>::type;
140593
140594 if (std::is_same<TYPE, int8_t>()) {
140595 return type == PhysicalType::INT8 || type == PhysicalType::BOOL;
140596 }
140597 if (std::is_same<TYPE, uint8_t>()) {
140598 return type == PhysicalType::UINT8 || type == PhysicalType::BOOL;
140599 }
140600 return type == GetTypeId<T>();
140601}
140602
140603template <class T>
140604bool TypeIsNumber() {
140605 using TYPE =
typename std::remove_cv<T>::type;
140606
140607 return std::is_integral<TYPE>() || std::is_floating_point<TYPE>() || std::is_same<TYPE, hugeint_t>() ||
140608 std::is_same<TYPE, uhugeint_t>();
140609}
140610
140611template <class T>
140612bool IsValidType() {
140613 return GetTypeId<T>() != PhysicalType::INVALID;
140614}
140615
140616template <class T>
140617bool IsIntegerType() {
140618 return TypeIsIntegral(GetTypeId<T>());
140619}
140620
140621}
140622
140623
140624namespace duckdb {
140625
140626class VectorCache;
140627class VectorChildBuffer;
140628class VectorStringBuffer;
140629class VectorStructBuffer;
140630class VectorListBuffer;
140631struct SelCache;
140632
140633struct UnifiedVectorFormat {
140634 DUCKDB_API UnifiedVectorFormat();
140635
140636 UnifiedVectorFormat(const UnifiedVectorFormat &other) = delete;
140637 UnifiedVectorFormat &
operator=(
const UnifiedVectorFormat &) =
delete;
140639 DUCKDB_API UnifiedVectorFormat(UnifiedVectorFormat &&other) noexcept;
140640 DUCKDB_API UnifiedVectorFormat &
operator=(UnifiedVectorFormat &&) noexcept;
140641
140642 const SelectionVector *sel;
140643 data_ptr_t data;
140644 ValidityMask validity;
140645 SelectionVector owned_sel;
140646 PhysicalType physical_type;
140647
140648 template <class T>
140649 void VerifyVectorType() const {
140650#ifdef DUCKDB_DEBUG_NO_SAFETY
140651 D_ASSERT(StorageTypeCompatible<T>(physical_type));
140652#else
140653 if (!StorageTypeCompatible<T>(physical_type)) {
140654 throw InternalException("Expected unified vector format of type %s, but found type %s", GetTypeId<T>(),
140655 physical_type);
140656 }
140657#endif
140658 }
140659
140660 template <class T>
140661 static inline const T *GetDataUnsafe(
const UnifiedVectorFormat &
format) {
140662 return reinterpret_cast<const T *
>(
format.data);
140663 }
140664 template <class T>
140665 static inline const T *GetData(
const UnifiedVectorFormat &
format) {
140666 return format.GetData<T>();
140667 }
140668 template <class T>
140669 inline const T *GetData() const {
140670 VerifyVectorType<T>();
140671 return GetDataUnsafe<T>(*this);
140672 }
140673 template <class T>
140674 static inline T *GetDataNoConst(UnifiedVectorFormat &
format) {
140675 format.VerifyVectorType<T>();
140676 return reinterpret_cast<T *
>(
format.data);
140677 }
140678};
140679
140680struct RecursiveUnifiedVectorFormat {
140681 UnifiedVectorFormat unified;
140682 vector<RecursiveUnifiedVectorFormat> children;
140683 LogicalType logical_type;
140684};
140685
140686struct UnifiedVariantVector {
140688 DUCKDB_API static const UnifiedVectorFormat &GetKeys(const RecursiveUnifiedVectorFormat &vec);
140690 DUCKDB_API static const UnifiedVectorFormat &GetKeysEntry(const RecursiveUnifiedVectorFormat &vec);
140692 DUCKDB_API static const UnifiedVectorFormat &GetChildren(const RecursiveUnifiedVectorFormat &vec);
140694 DUCKDB_API static const UnifiedVectorFormat &GetChildrenKeysIndex(const RecursiveUnifiedVectorFormat &vec);
140696 DUCKDB_API static const UnifiedVectorFormat &GetChildrenValuesIndex(const RecursiveUnifiedVectorFormat &vec);
140698 DUCKDB_API static const UnifiedVectorFormat &GetValues(const RecursiveUnifiedVectorFormat &vec);
140700 DUCKDB_API static const UnifiedVectorFormat &GetValuesTypeId(const RecursiveUnifiedVectorFormat &vec);
140702 DUCKDB_API static const UnifiedVectorFormat &GetValuesByteOffset(const RecursiveUnifiedVectorFormat &vec);
140704 DUCKDB_API static const UnifiedVectorFormat &GetData(const RecursiveUnifiedVectorFormat &vec);
140705};
140706
140708struct ResizeInfo {
140709 ResizeInfo(Vector &vec, data_ptr_t data, optional_ptr<VectorBuffer> buffer, const idx_t multiplier)
140710 : vec(vec), data(data), buffer(buffer), multiplier(multiplier) {
140711 }
140712
140713 Vector &vec;
140714 data_ptr_t data;
140715 optional_ptr<VectorBuffer> buffer;
140717};
140718
140719struct ConsecutiveChildListInfo {
140720 ConsecutiveChildListInfo() : is_constant(true), needs_slicing(false), child_list_info(list_entry_t(0, 0)) {
140721 }
140722 bool is_constant;
140723 bool needs_slicing;
140724 list_entry_t child_list_info;
140725};
140726
140728class Vector {
140729 friend struct ConstantVector;
140730 friend struct DictionaryVector;
140731 friend struct FlatVector;
140732 friend struct ListVector;
140733 friend struct StringVector;
140734 friend struct FSSTVector;
140735 friend struct StructVector;
140736 friend struct UnionVector;
140737 friend struct SequenceVector;
140738 friend struct ArrayVector;
140739
140740 friend class DataChunk;
140741 friend class VectorCacheBuffer;
140742
140743public:
140745 DUCKDB_API Vector(Vector &other);
140747 DUCKDB_API explicit Vector(const Vector &other, const SelectionVector &sel, idx_t count);
140749 DUCKDB_API explicit Vector(const Vector &other, idx_t offset, idx_t end);
140751 DUCKDB_API explicit Vector(const Value &value);
140753 DUCKDB_API explicit Vector(LogicalType type, idx_t capacity = STANDARD_VECTOR_SIZE);
140755 DUCKDB_API explicit Vector(const VectorCache &cache);
140757 DUCKDB_API Vector(LogicalType type, data_ptr_t dataptr);
140759
140764 DUCKDB_API Vector(LogicalType type, bool create_data, bool initialize_to_zero,
140765 idx_t capacity = STANDARD_VECTOR_SIZE);
140766
140767 Vector(const Vector &) = delete;
140768
140769 DUCKDB_API Vector(Vector &&other) noexcept;
140770
140771public:
140773 DUCKDB_API void Reference(const Value &value);
140776 DUCKDB_API void Reference(const Vector &other);
140780 DUCKDB_API void Reinterpret(const Vector &other);
140781
140783 DUCKDB_API void ReferenceAndSetType(const Vector &other);
140784
140788 DUCKDB_API void ResetFromCache(const VectorCache &cache);
140789
140791 DUCKDB_API void Slice(const Vector &other, idx_t offset, idx_t end);
140793 DUCKDB_API void Slice(const Vector &other, const SelectionVector &sel, idx_t count);
140795 DUCKDB_API void Slice(const SelectionVector &sel, idx_t count);
140797 DUCKDB_API void Slice(const SelectionVector &sel, idx_t count, SelCache &cache);
140799 DUCKDB_API void Dictionary(idx_t dictionary_size, const SelectionVector &sel, idx_t count);
140801 DUCKDB_API void Dictionary(Vector &dict, idx_t dictionary_size, const SelectionVector &sel, idx_t count);
140803 DUCKDB_API void Dictionary(buffer_ptr<VectorChildBuffer> reusable_dict, const SelectionVector &sel);
140804
140807 DUCKDB_API void Initialize(bool initialize_to_zero = false, idx_t capacity = STANDARD_VECTOR_SIZE);
140808
140810 DUCKDB_API string ToString(idx_t count) const;
140811 DUCKDB_API void Print(idx_t count) const;
140812
140813 DUCKDB_API string ToString() const;
140814 DUCKDB_API void Print() const;
140815
140817 DUCKDB_API void Flatten(idx_t count);
140818 DUCKDB_API void Flatten(const SelectionVector &sel, idx_t count);
140825 DUCKDB_API void ToUnifiedFormat(idx_t count, UnifiedVectorFormat &data);
140827 static void RecursiveToUnifiedFormat(Vector &input, idx_t count, RecursiveUnifiedVectorFormat &data);
140828
140830 DUCKDB_API void Sequence(int64_t start, int64_t increment, idx_t count);
140831
140834 DUCKDB_API void Verify(idx_t count);
140836 DUCKDB_API static void VerifyMap(Vector &map, const SelectionVector &sel, idx_t count);
140837 DUCKDB_API static void VerifyUnion(Vector &map, const SelectionVector &sel, idx_t count);
140838 DUCKDB_API static void VerifyVariant(Vector &map, const SelectionVector &sel, idx_t count);
140839 DUCKDB_API static void Verify(Vector &vector, const SelectionVector &sel, idx_t count);
140840 DUCKDB_API void UTFVerify(idx_t count);
140841 DUCKDB_API void UTFVerify(const SelectionVector &sel, idx_t count);
140842
140844 DUCKDB_API Value GetValue(idx_t index) const;
140846 DUCKDB_API void SetValue(idx_t index, const Value &val);
140847
140848 inline void SetAuxiliary(buffer_ptr<VectorBuffer> new_buffer) {
140849 auxiliary = std::move(new_buffer);
140850 };
140851
140852 inline void CopyBuffer(Vector &other) {
140853 buffer = other.buffer;
140854 data = other.data;
140855 }
140856
140858 DUCKDB_API void Resize(idx_t cur_size, idx_t new_size);
140860 DUCKDB_API void FindResizeInfos(vector<ResizeInfo> &resize_infos, const idx_t multiplier);
140861
140862 DUCKDB_API void Serialize(Serializer &serializer, idx_t count, bool compressed_serialization = true);
140863 DUCKDB_API void Deserialize(Deserializer &deserializer, idx_t count);
140864
140865 idx_t GetAllocationSize(idx_t cardinality)
const;
140866
140867
140868 inline VectorType GetVectorType() const {
140869 return vector_type;
140870 }
140871 inline const LogicalType &GetType() const {
140872 return type;
140873 }
140874 inline data_ptr_t GetData() const {
140875 return data;
140876 }
140877
140878 inline buffer_ptr<VectorBuffer> GetAuxiliary() {
140879 return auxiliary;
140880 }
140881
140882 inline buffer_ptr<VectorBuffer> GetBuffer() {
140883 return buffer;
140884 }
140885
140886
140887 DUCKDB_API void SetVectorType(VectorType vector_type);
140888
140889
140890 static void DebugTransformToDictionary(Vector &vector, idx_t count);
140891
140892 static void DebugShuffleNestedVector(Vector &vector, idx_t count);
140893
140894private:
140896 static Value GetValue(
const Vector &
v, idx_t index);
140898 static Value GetValueInternal(
const Vector &
v, idx_t index);
140899
140900protected:
140903 VectorType vector_type;
140905 LogicalType type;
140907 data_ptr_t data;
140909 ValidityMask validity;
140911 buffer_ptr<VectorBuffer> buffer;
140914 buffer_ptr<VectorBuffer> auxiliary;
140915};
140916
140918class VectorChildBuffer : public VectorBuffer {
140919public:
140920 explicit VectorChildBuffer(Vector vector)
140921 : VectorBuffer(VectorBufferType::VECTOR_CHILD_BUFFER), data(std::move(vector)),
140922 cached_hashes(LogicalType::HASH, nullptr) {
140923 }
140924
140925public:
140926 Vector data;
140928 optional_idx
size;
140929 string id;
140931 mutex cached_hashes_lock;
140932 Vector cached_hashes;
140933};
140934
140935struct ConstantVector {
140936 template <class T>
140937 static void VerifyVectorType(const Vector &vector) {
140938#ifdef DUCKDB_DEBUG_NO_SAFETY
140939 D_ASSERT(StorageTypeCompatible<T>(vector.GetType().InternalType()));
140940#else
140941 if (!StorageTypeCompatible<T>(vector.GetType().InternalType())) {
140942 throw InternalException("Expected vector of type %s, but found vector of type %s", GetTypeId<T>(),
140943 vector.GetType().InternalType());
140944 }
140945#endif
140946 }
140947
140948 static inline const_data_ptr_t GetData(const Vector &vector) {
140949 D_ASSERT(vector.GetVectorType() == VectorType::CONSTANT_VECTOR ||
140950 vector.GetVectorType() == VectorType::FLAT_VECTOR);
140951 return vector.data;
140952 }
140953 static inline data_ptr_t GetData(Vector &vector) {
140954 D_ASSERT(vector.GetVectorType() == VectorType::CONSTANT_VECTOR ||
140955 vector.GetVectorType() == VectorType::FLAT_VECTOR);
140956 return vector.data;
140957 }
140958 template <class T>
140959 static inline const T *GetDataUnsafe(const Vector &vector) {
140960 return reinterpret_cast<const T *>(GetData(vector));
140961 }
140962 template <class T>
140963 static inline T *GetDataUnsafe(Vector &vector) {
140964 return reinterpret_cast<T *>(GetData(vector));
140965 }
140966 template <class T>
140967 static inline const T *GetData(const Vector &vector) {
140968 VerifyVectorType<T>(vector);
140969 return GetDataUnsafe<T>(vector);
140970 }
140971 template <class T>
140972 static inline T *GetData(Vector &vector) {
140973 VerifyVectorType<T>(vector);
140974 return GetDataUnsafe<T>(vector);
140975 }
140976 static inline bool IsNull(const Vector &vector) {
140977 D_ASSERT(vector.GetVectorType() == VectorType::CONSTANT_VECTOR);
140978 return !vector.validity.RowIsValid(0);
140979 }
140980 DUCKDB_API static void SetNull(Vector &vector, bool is_null);
140981 static inline ValidityMask &Validity(Vector &vector) {
140982 D_ASSERT(vector.GetVectorType() == VectorType::CONSTANT_VECTOR);
140983 return vector.validity;
140984 }
140985 DUCKDB_API static const SelectionVector *ZeroSelectionVector(idx_t count, SelectionVector &owned_sel);
140986 DUCKDB_API static const SelectionVector *ZeroSelectionVector();
140988 DUCKDB_API static void Reference(Vector &vector, Vector &source, idx_t position, idx_t count);
140989
140990 static const sel_t ZERO_VECTOR[STANDARD_VECTOR_SIZE];
140991};
140992
140993struct DictionaryVector {
140994 static void VerifyDictionary(const Vector &vector) {
140995#ifdef DUCKDB_DEBUG_NO_SAFETY
140996 D_ASSERT(vector.GetVectorType() == VectorType::DICTIONARY_VECTOR);
140997#else
140998 if (vector.GetVectorType() != VectorType::DICTIONARY_VECTOR) {
140999 throw InternalException(
141000 "Operation requires a dictionary vector but a non-dictionary vector was encountered");
141001 }
141002#endif
141003 }
141004 static inline const SelectionVector &SelVector(const Vector &vector) {
141005 VerifyDictionary(vector);
141006 return vector.buffer->Cast<DictionaryBuffer>().GetSelVector();
141007 }
141008 static inline SelectionVector &SelVector(Vector &vector) {
141009 VerifyDictionary(vector);
141010 return vector.buffer->Cast<DictionaryBuffer>().GetSelVector();
141011 }
141012 static inline const Vector &Child(const Vector &vector) {
141013 VerifyDictionary(vector);
141014 return vector.auxiliary->Cast<VectorChildBuffer>().data;
141015 }
141016 static inline Vector &Child(Vector &vector) {
141017 VerifyDictionary(vector);
141018 return vector.auxiliary->Cast<VectorChildBuffer>().data;
141019 }
141020 static inline optional_idx DictionarySize(const Vector &vector) {
141021 VerifyDictionary(vector);
141022 const auto &child_buffer = vector.auxiliary->Cast<VectorChildBuffer>();
141023 if (child_buffer.size.IsValid()) {
141024 return child_buffer.size;
141025 }
141026 return vector.buffer->Cast<DictionaryBuffer>().GetDictionarySize();
141027 }
141028 static inline const string &DictionaryId(const Vector &vector) {
141029 VerifyDictionary(vector);
141030 const auto &child_buffer = vector.auxiliary->Cast<VectorChildBuffer>();
141031 if (!child_buffer.id.empty()) {
141032 return child_buffer.id;
141033 }
141034 return vector.buffer->Cast<DictionaryBuffer>().GetDictionaryId();
141035 }
141036 static inline bool CanCacheHashes(const LogicalType &type) {
141037 return type.InternalType() == PhysicalType::VARCHAR;
141038 }
141039 static inline bool CanCacheHashes(const Vector &vector) {
141040 return DictionarySize(vector).IsValid() && CanCacheHashes(vector.GetType());
141041 }
141042 static buffer_ptr<VectorChildBuffer> CreateReusableDictionary(const LogicalType &type, const idx_t &size);
141043 static const Vector &GetCachedHashes(Vector &input);
141044};
141045
141046struct FlatVector {
141047 static void VerifyFlatVector(const Vector &vector) {
141048#ifdef DUCKDB_DEBUG_NO_SAFETY
141049 D_ASSERT(vector.GetVectorType() == VectorType::FLAT_VECTOR);
141050#else
141051 if (vector.GetVectorType() != VectorType::FLAT_VECTOR) {
141052 throw InternalException("Operation requires a flat vector but a non-flat vector was encountered");
141053 }
141054#endif
141055 }
141056
141057 static inline data_ptr_t GetData(Vector &vector) {
141058 return ConstantVector::GetData(vector);
141059 }
141060 template <class T>
141061 static inline const T *GetData(const Vector &vector) {
141062 return ConstantVector::GetData<T>(vector);
141063 }
141064 template <class T>
141065 static inline T *GetData(Vector &vector) {
141066 return ConstantVector::GetData<T>(vector);
141067 }
141068 template <class T>
141069 static inline const T *GetDataUnsafe(const Vector &vector) {
141070 return ConstantVector::GetDataUnsafe<T>(vector);
141071 }
141072 template <class T>
141073 static inline T *GetDataUnsafe(Vector &vector) {
141074 return ConstantVector::GetDataUnsafe<T>(vector);
141075 }
141076 static inline void SetData(Vector &vector, data_ptr_t data) {
141077 D_ASSERT(vector.GetVectorType() == VectorType::FLAT_VECTOR);
141078 vector.data = data;
141079 }
141080 template <class T>
141081 static inline T GetValue(Vector &vector, idx_t idx) {
141082 D_ASSERT(vector.GetVectorType() == VectorType::FLAT_VECTOR);
141083 return FlatVector::GetData<T>(vector)[idx];
141084 }
141085 static inline const ValidityMask &Validity(const Vector &vector) {
141086 VerifyFlatVector(vector);
141087 return vector.validity;
141088 }
141089 static inline ValidityMask &Validity(Vector &vector) {
141090 VerifyFlatVector(vector);
141091 return vector.validity;
141092 }
141093 static inline void SetValidity(Vector &vector, const ValidityMask &new_validity) {
141094 VerifyFlatVector(vector);
141095 vector.validity.Initialize(new_validity);
141096 }
141097 DUCKDB_API static void SetNull(Vector &vector, idx_t idx, bool is_null);
141098 static inline bool IsNull(const Vector &vector, idx_t idx) {
141099 D_ASSERT(vector.GetVectorType() == VectorType::FLAT_VECTOR);
141100 return !vector.validity.RowIsValid(idx);
141101 }
141102 DUCKDB_API static const SelectionVector *IncrementalSelectionVector();
141103};
141104
141105struct ListVector {
141106 static inline const list_entry_t *GetData(
const Vector &
v) {
141107 if (
v.GetVectorType() == VectorType::DICTIONARY_VECTOR) {
141108 auto &child = DictionaryVector::Child(
v);
141109 return GetData(child);
141110 }
141111 return FlatVector::GetData<const list_entry_t>(
v);
141112 }
141113 static inline list_entry_t *GetData(Vector &
v) {
141114 if (
v.GetVectorType() == VectorType::DICTIONARY_VECTOR) {
141115 auto &child = DictionaryVector::Child(
v);
141116 return GetData(child);
141117 }
141118 return FlatVector::GetData<list_entry_t>(
v);
141119 }
141121 DUCKDB_API static const Vector &GetEntry(const Vector &vector);
141123 DUCKDB_API static Vector &GetEntry(Vector &vector);
141125 DUCKDB_API
static idx_t GetListSize(
const Vector &vector);
141127 DUCKDB_API static void SetListSize(Vector &vec, idx_t size);
141129 DUCKDB_API
static idx_t GetListCapacity(
const Vector &vector);
141131 DUCKDB_API static void Reserve(Vector &vec, idx_t required_capacity);
141132 DUCKDB_API static void Append(Vector &target, const Vector &source, idx_t source_size, idx_t source_offset = 0);
141133 DUCKDB_API static void Append(Vector &target, const Vector &source, const SelectionVector &sel, idx_t source_size,
141134 idx_t source_offset = 0);
141135 DUCKDB_API static void PushBack(Vector &target, const Value &insert);
141137 DUCKDB_API
static idx_t GetConsecutiveChildList(Vector &list, Vector &result, idx_t offset, idx_t count);
141139 DUCKDB_API static ConsecutiveChildListInfo GetConsecutiveChildListInfo(Vector &list, idx_t offset, idx_t count);
141141 DUCKDB_API static void GetConsecutiveChildSelVector(Vector &list, SelectionVector &sel, idx_t offset, idx_t count);
141143 DUCKDB_API static void ReferenceEntry(Vector &vector, Vector &other);
141144
141145private:
141146 template <class T>
141147 static T &GetEntryInternal(T &vector);
141148};
141149
141150struct StringVector {
141152 DUCKDB_API static string_t AddString(Vector &vector, const char *data, idx_t len);
141155 DUCKDB_API static string_t AddStringOrBlob(Vector &vector, const char *data, idx_t len);
141157 DUCKDB_API static string_t AddString(Vector &vector, const char *data);
141159 DUCKDB_API static string_t AddString(Vector &vector, string_t data);
141161 DUCKDB_API static string_t AddString(Vector &vector, const string &data);
141164 DUCKDB_API static string_t AddStringOrBlob(Vector &vector, string_t data);
141167 DUCKDB_API static string_t EmptyString(Vector &vector, idx_t len);
141169 DUCKDB_API static VectorStringBuffer &GetStringBuffer(Vector &vector);
141171 DUCKDB_API static void AddHandle(Vector &vector, BufferHandle handle);
141173 DUCKDB_API static void AddBuffer(Vector &vector, buffer_ptr<VectorBuffer> buffer);
141175 DUCKDB_API static void AddHeapReference(Vector &vector, Vector &other);
141176};
141177
141178struct FSSTVector {
141179 static inline const ValidityMask &Validity(const Vector &vector) {
141180 D_ASSERT(vector.GetVectorType() == VectorType::FSST_VECTOR);
141181 return vector.validity;
141182 }
141183 static inline ValidityMask &Validity(Vector &vector) {
141184 D_ASSERT(vector.GetVectorType() == VectorType::FSST_VECTOR);
141185 return vector.validity;
141186 }
141187 static inline void SetValidity(Vector &vector, ValidityMask &new_validity) {
141188 D_ASSERT(vector.GetVectorType() == VectorType::FSST_VECTOR);
141189 vector.validity.Initialize(new_validity);
141190 }
141191 static inline const_data_ptr_t GetCompressedData(const Vector &vector) {
141192 D_ASSERT(vector.GetVectorType() == VectorType::FSST_VECTOR);
141193 return vector.data;
141194 }
141195 static inline data_ptr_t GetCompressedData(Vector &vector) {
141196 D_ASSERT(vector.GetVectorType() == VectorType::FSST_VECTOR);
141197 return vector.data;
141198 }
141199 template <class T>
141200 static inline const T *GetCompressedData(const Vector &vector) {
141201 return (const T *)FSSTVector::GetCompressedData(vector);
141202 }
141203 template <class T>
141204 static inline T *GetCompressedData(Vector &vector) {
141205 return (T *)FSSTVector::GetCompressedData(vector);
141206 }
141208 static void DecompressVector(const Vector &src, Vector &dst, idx_t src_offset, idx_t dst_offset, idx_t copy_count,
141209 const SelectionVector *sel);
141210
141211 DUCKDB_API static string_t AddCompressedString(Vector &vector, string_t data);
141212 DUCKDB_API static string_t AddCompressedString(Vector &vector, const char *data, idx_t len);
141213 DUCKDB_API static void RegisterDecoder(Vector &vector, buffer_ptr<void> &duckdb_fsst_decoder,
141214 const idx_t string_block_limit);
141215 DUCKDB_API static void *GetDecoder(const Vector &vector);
141216 DUCKDB_API static vector<unsigned char> &GetDecompressBuffer(const Vector &vector);
141218 DUCKDB_API static void SetCount(Vector &vector, idx_t count);
141219 DUCKDB_API
static idx_t GetCount(Vector &vector);
141220};
141221
141222enum class MapInvalidReason :
uint8_t { VALID, NULL_KEY, DUPLICATE_KEY, NOT_ALIGNED, INVALID_PARAMS };
141223
141224struct MapVector {
141225 DUCKDB_API static const Vector &GetKeys(const Vector &vector);
141226 DUCKDB_API static const Vector &GetValues(const Vector &vector);
141227 DUCKDB_API static Vector &GetKeys(Vector &vector);
141228 DUCKDB_API static Vector &GetValues(Vector &vector);
141229 DUCKDB_API static MapInvalidReason
141230 CheckMapValidity(Vector &map, idx_t count, const SelectionVector &sel = *FlatVector::IncrementalSelectionVector());
141231 DUCKDB_API static void EvalMapInvalidReason(MapInvalidReason reason);
141232 DUCKDB_API static void MapConversionVerify(Vector &vector, idx_t count);
141233};
141234
141235struct StructVector {
141236 DUCKDB_API static const vector<unique_ptr<Vector>> &GetEntries(const Vector &vector);
141237 DUCKDB_API static vector<unique_ptr<Vector>> &GetEntries(Vector &vector);
141238};
141239
141240struct ArrayVector {
141242 DUCKDB_API static const Vector &GetEntry(const Vector &vector);
141244 DUCKDB_API static Vector &GetEntry(Vector &vector);
141246 DUCKDB_API
static idx_t GetTotalSize(
const Vector &vector);
141247
141248private:
141249 template <class T>
141250 static T &GetEntryInternal(T &vector);
141251};
141252
141253struct VariantVector {
141255 DUCKDB_API static Vector &GetKeys(Vector &vec);
141256 DUCKDB_API static Vector &GetKeys(const Vector &vec);
141258 DUCKDB_API static Vector &GetChildren(Vector &vec);
141259 DUCKDB_API static Vector &GetChildren(const Vector &vec);
141261 DUCKDB_API static Vector &GetChildrenKeysIndex(Vector &vec);
141262 DUCKDB_API static Vector &GetChildrenKeysIndex(const Vector &vec);
141264 DUCKDB_API static Vector &GetChildrenValuesIndex(Vector &vec);
141265 DUCKDB_API static Vector &GetChildrenValuesIndex(const Vector &vec);
141267 DUCKDB_API static Vector &GetValues(Vector &vec);
141268 DUCKDB_API static Vector &GetValues(const Vector &vec);
141270 DUCKDB_API static Vector &GetValuesTypeId(Vector &vec);
141271 DUCKDB_API static Vector &GetValuesTypeId(const Vector &vec);
141273 DUCKDB_API static Vector &GetValuesByteOffset(Vector &vec);
141274 DUCKDB_API static Vector &GetValuesByteOffset(const Vector &vec);
141276 DUCKDB_API static Vector &GetData(Vector &vec);
141277 DUCKDB_API static Vector &GetData(const Vector &vec);
141278};
141279
141280enum class UnionInvalidReason :
uint8_t {
141281 VALID,
141282 TAG_OUT_OF_RANGE,
141283 NO_MEMBERS,
141284 VALIDITY_OVERLAP,
141285 TAG_MISMATCH,
141286 NULL_TAG
141287};
141288
141289struct UnionVector {
141290
141291
141292
141293
141294
141295
141296
141297
141298
141299
141300
141301
141302
141303
141304
141305
141306
141308 DUCKDB_API
static const Vector &GetTags(
const Vector &
v);
141309 DUCKDB_API
static Vector &GetTags(Vector &
v);
141310
141313 DUCKDB_API static bool TryGetTag(const Vector &vector, idx_t index, union_tag_t &tag);
141314
141316 DUCKDB_API static const Vector &GetMember(const Vector &vector, idx_t member_index);
141317 DUCKDB_API static Vector &GetMember(Vector &vector, idx_t member_index);
141318
141326 DUCKDB_API static void SetToMember(Vector &vector, union_tag_t tag, Vector &member_vector, idx_t count,
141327 bool keep_tags_for_null);
141328
141329 DUCKDB_API static UnionInvalidReason
141330 CheckUnionValidity(Vector &vector, idx_t count,
141331 const SelectionVector &sel = *FlatVector::IncrementalSelectionVector());
141332};
141333
141334struct SequenceVector {
141335 static void GetSequence(const Vector &vector, int64_t &start, int64_t &increment, int64_t &sequence_count) {
141336 D_ASSERT(vector.GetVectorType() == VectorType::SEQUENCE_VECTOR);
141337 auto data =
reinterpret_cast<int64_t *
>(vector.buffer->GetData());
141338 start = data[0];
141339 increment = data[1];
141340 sequence_count = data[2];
141341 }
141342 static void GetSequence(const Vector &vector, int64_t &start, int64_t &increment) {
141344 GetSequence(vector, start, increment, sequence_count);
141345 }
141346};
141347
141348}
141349
141350
141351
141352
141353
141354
141355
141356
141357
141358
141359
141360
141361
141362
141363
141364
141365
141366
141367
141368
141369
141370
141371
141372
141373
141374
141375
141376
141377
141378
141379
141380
141381
141382
141383
141384
141385
141386
141387
141388#ifndef ARROW_FLAG_DICTIONARY_ORDERED
141389
141390#include <stdint.h>
141391
141392#ifdef __cplusplus
141393extern "C" {
141394#endif
141395
141396#ifndef ARROW_C_DATA_INTERFACE
141397#define ARROW_C_DATA_INTERFACE
141398
141399#define ARROW_FLAG_DICTIONARY_ORDERED 1
141400#define ARROW_FLAG_NULLABLE 2
141401#define ARROW_FLAG_MAP_KEYS_SORTED 4
141402
141403struct ArrowSchema {
141406 const char *name;
141407 const char *metadata;
141410 struct ArrowSchema **children;
141411 struct ArrowSchema *dictionary;
141412
141414 void (*release)(struct ArrowSchema *);
141416 void *private_data;
141417
141419 void Init() {
141420 flags = 0;
141421 n_children = 0;
141422 release = nullptr;
141423 private_data = nullptr;
141424 }
141425};
141426
141427struct ArrowArray {
141434 const void **buffers;
141435 struct ArrowArray **children;
141436 struct ArrowArray *dictionary;
141437
141439 void (*release)(struct ArrowArray *);
141441 void *private_data;
141442
141444 void Init() {
141445 length = 0;
141446 null_count = 0;
141447 offset = 0;
141448 n_buffers = 0;
141449 n_children = 0;
141450 release = nullptr;
141451 private_data = nullptr;
141452 }
141453};
141454#endif
141455
141456#ifndef ARROW_C_STREAM_INTERFACE
141457#define ARROW_C_STREAM_INTERFACE
141458
141459struct ArrowArrayStream {
141460
141461
141462
141463 int (*get_schema)(struct ArrowArrayStream *, struct ArrowSchema *out);
141464
141465
141466
141467 int (*get_next)(struct ArrowArrayStream *, struct ArrowArray *out);
141468
141469
141470
141471
141472
141473
141474 const char *(*get_last_error)(struct ArrowArrayStream *);
141475
141476
141477
141478 void (*release)(struct ArrowArrayStream *);
141479
141480 void *private_data;
141481};
141482#endif
141483
141484#ifdef __cplusplus
141485}
141486#endif
141487
141488#endif
141489
141490
141491
141493namespace duckdb {
141494
141495class ArrowSchemaWrapper {
141496public:
141497 ArrowSchema arrow_schema;
141498
141499 ArrowSchemaWrapper() {
141500 arrow_schema.
release =
nullptr;
141501 }
141502
141503 ~ArrowSchemaWrapper();
141504};
141505class ArrowArrayWrapper {
141506public:
141507 ArrowArray arrow_array;
141508 ArrowArrayWrapper() {
141509 arrow_array.
length = 0;
141510 arrow_array.
release =
nullptr;
141511 }
141512 ArrowArrayWrapper(ArrowArrayWrapper &&other) noexcept : arrow_array(other.arrow_array) {
141513 other.arrow_array.release = nullptr;
141514 }
141515 ArrowArrayWrapper &
operator=(ArrowArrayWrapper &&other)
noexcept {
141516 if (this != &other) {
141518 arrow_array.
release(&arrow_array);
141519 }
141520 arrow_array = other.arrow_array;
141521 other.arrow_array.release = nullptr;
141522 }
141523 return *this;
141524 }
141525 ~ArrowArrayWrapper();
141526};
141527
141528class ArrowArrayStreamWrapper {
141529public:
141530 ArrowArrayStream arrow_array_stream;
141532
141533public:
141534 void GetSchema(ArrowSchemaWrapper &schema);
141535
141536 virtual shared_ptr<ArrowArrayWrapper> GetNextChunk();
141537
141538 const char *GetError();
141539
141540 virtual ~ArrowArrayStreamWrapper();
141541 ArrowArrayStreamWrapper() {
141542 arrow_array_stream.release = nullptr;
141543 }
141544};
141545
141546}
141547
141548
141549
141550
141551
141552namespace duckdb {
141553class Allocator;
141554class ClientContext;
141555class ExecutionContext;
141556class VectorCache;
141557class Serializer;
141558class Deserializer;
141559
141561
141578class DataChunk {
141579public:
141581 DUCKDB_API DataChunk();
141582 DUCKDB_API ~DataChunk();
141583
141585 vector<Vector> data;
141586
141587public:
141589 return count;
141590 }
141591 inline idx_t ColumnCount()
const {
141592 return data.size();
141593 }
141594 inline void SetCardinality(idx_t count_p) {
141595 D_ASSERT(count_p <= capacity);
141596 this->count = count_p;
141597 }
141598 inline void SetCardinality(const DataChunk &other) {
141599 SetCardinality(other.size());
141600 }
141601 inline idx_t GetCapacity()
const {
141602 return capacity;
141603 }
141604 inline void SetCapacity(idx_t capacity_p) {
141605 this->capacity = capacity_p;
141606 }
141607 inline void SetCapacity(const DataChunk &other) {
141609 }
141610
141611 DUCKDB_API Value GetValue(idx_t col_idx, idx_t index) const;
141612 DUCKDB_API void SetValue(idx_t col_idx, idx_t index, const Value &val);
141613
141614 idx_t GetAllocationSize()
const;
141615
141617 DUCKDB_API bool AllConstant() const;
141618
141620 DUCKDB_API void Reference(DataChunk &chunk);
141622 DUCKDB_API void Move(DataChunk &chunk);
141623
141625 DUCKDB_API void InitializeEmpty(const vector<LogicalType> &types);
141626
141629 DUCKDB_API void Initialize(ClientContext &context, const vector<LogicalType> &types,
141630 idx_t capacity = STANDARD_VECTOR_SIZE);
141631 DUCKDB_API void Initialize(Allocator &allocator, const vector<LogicalType> &types,
141632 idx_t capacity = STANDARD_VECTOR_SIZE);
141633 DUCKDB_API void Initialize(ClientContext &context, const vector<LogicalType> &types, const vector<bool> &initialize,
141634 idx_t capacity = STANDARD_VECTOR_SIZE);
141635 DUCKDB_API void Initialize(Allocator &allocator, const vector<LogicalType> &types, const vector<bool> &initialize,
141636 idx_t capacity = STANDARD_VECTOR_SIZE);
141637
141641 DUCKDB_API void Append(const DataChunk &other, bool resize = false, SelectionVector *sel = nullptr,
141642 idx_t count = 0);
141643
141645 DUCKDB_API void Destroy();
141646
141648 DUCKDB_API void Copy(DataChunk &other, idx_t offset = 0) const;
141649 DUCKDB_API void Copy(DataChunk &other, const SelectionVector &sel, const idx_t source_count,
141650 const idx_t offset = 0) const;
141651
141653 DUCKDB_API void Split(DataChunk &other, idx_t split_idx);
141654
141656 DUCKDB_API void Fuse(DataChunk &other);
141657
141659 DUCKDB_API void ReferenceColumns(DataChunk &other, const vector<column_t> &column_ids);
141660
141662 DUCKDB_API void Flatten();
141663
141664
141665 DUCKDB_API unsafe_unique_array<UnifiedVectorFormat> ToUnifiedFormat();
141666
141667 DUCKDB_API void Slice(const SelectionVector &sel_vector, idx_t count);
141668
141671 DUCKDB_API void Slice(const DataChunk &other, const SelectionVector &sel, idx_t count, idx_t col_offset = 0);
141672
141674 DUCKDB_API void Slice(idx_t offset, idx_t count);
141675
141679 DUCKDB_API void Reset();
141680
141681 DUCKDB_API void Serialize(Serializer &serializer, bool compressed_serialization = true) const;
141682 DUCKDB_API void Deserialize(Deserializer &source);
141683
141685 DUCKDB_API void Hash(Vector &result);
141687 DUCKDB_API void Hash(vector<idx_t> &column_ids, Vector &result);
141688
141690 DUCKDB_API vector<LogicalType> GetTypes() const;
141691
141693 DUCKDB_API string ToString() const;
141694 DUCKDB_API void Print() const;
141695
141696 DataChunk(const DataChunk &) = delete;
141697
141700 DUCKDB_API void Verify();
141701
141702private:
141708 idx_t initial_capacity;
141710 vector<VectorCache> vector_caches;
141711};
141712}
141713
141714
141715
141716#include <functional>
141717
141718namespace duckdb {
141719class CastFunctionSet;
141720struct GetCastFunctionInput;
141721
141722
141723
141724
141725
141726
141727
141728
141729struct VectorOperations {
141730
141731
141732
141734 static void AddInPlace(Vector &left, int64_t delta, idx_t count);
141735
141736
141737
141738
141740 static void IsNotNull(Vector &
arg, Vector &result, idx_t count);
141742 static void IsNull(Vector &input, Vector &result, idx_t count);
141743
141744 static bool HasNull(Vector &input, idx_t count);
141745 static bool HasNotNull(Vector &input, idx_t count);
141747 static idx_t CountNotNull(Vector &input,
const idx_t count);
141748
141749
141750
141751
141752
141753 static void And(Vector &left, Vector &right, Vector &result, idx_t count);
141754
141755 static void Or(Vector &left, Vector &right, Vector &result, idx_t count);
141756
141757 static void Not(Vector &left, Vector &result, idx_t count);
141758
141759
141760
141761
141762
141763 static void Equals(Vector &left, Vector &right, Vector &result, idx_t count);
141764
141765 static void NotEquals(Vector &left, Vector &right, Vector &result, idx_t count);
141766
141767 static void GreaterThan(Vector &left, Vector &right, Vector &result, idx_t count);
141768
141769 static void GreaterThanEquals(Vector &left, Vector &right, Vector &result, idx_t count);
141770
141771 static void LessThan(Vector &left, Vector &right, Vector &result, idx_t count);
141772
141773 static void LessThanEquals(Vector &left, Vector &right, Vector &result, idx_t count);
141774
141775
141776 static void DistinctFrom(Vector &left, Vector &right, Vector &result, idx_t count);
141777
141778 static void NotDistinctFrom(Vector &left, Vector &right, Vector &result, idx_t count);
141779
141780 static void DistinctGreaterThan(Vector &left, Vector &right, Vector &result, idx_t count);
141781
141782 static void DistinctGreaterThanEquals(Vector &left, Vector &right, Vector &result, idx_t count);
141783
141784 static void DistinctLessThan(Vector &left, Vector &right, Vector &result, idx_t count);
141785
141786 static void DistinctLessThanEquals(Vector &left, Vector &right, Vector &result, idx_t count);
141787
141788
141789
141790
141791 static idx_t Equals(Vector &left, Vector &right, optional_ptr<const SelectionVector> sel, idx_t count,
141792 optional_ptr<SelectionVector> true_sel, optional_ptr<SelectionVector> false_sel,
141793 optional_ptr<ValidityMask> null_mask = nullptr);
141794 static idx_t NotEquals(Vector &left, Vector &right, optional_ptr<const SelectionVector> sel, idx_t count,
141795 optional_ptr<SelectionVector> true_sel, optional_ptr<SelectionVector> false_sel,
141796 optional_ptr<ValidityMask> null_mask = nullptr);
141797 static idx_t GreaterThan(Vector &left, Vector &right, optional_ptr<const SelectionVector> sel, idx_t count,
141798 optional_ptr<SelectionVector> true_sel, optional_ptr<SelectionVector> false_sel,
141799 optional_ptr<ValidityMask> null_mask = nullptr);
141800 static idx_t GreaterThanEquals(Vector &left, Vector &right, optional_ptr<const SelectionVector> sel, idx_t count,
141801 optional_ptr<SelectionVector> true_sel, optional_ptr<SelectionVector> false_sel,
141802 optional_ptr<ValidityMask> null_mask = nullptr);
141803 static idx_t LessThan(Vector &left, Vector &right, optional_ptr<const SelectionVector> sel, idx_t count,
141804 optional_ptr<SelectionVector> true_sel, optional_ptr<SelectionVector> false_sel,
141805 optional_ptr<ValidityMask> null_mask = nullptr);
141806 static idx_t LessThanEquals(Vector &left, Vector &right, optional_ptr<const SelectionVector> sel, idx_t count,
141807 optional_ptr<SelectionVector> true_sel, optional_ptr<SelectionVector> false_sel,
141808 optional_ptr<ValidityMask> null_mask = nullptr);
141809
141810
141811 static idx_t DistinctFrom(Vector &left, Vector &right, optional_ptr<const SelectionVector> sel, idx_t count,
141812 optional_ptr<SelectionVector> true_sel, optional_ptr<SelectionVector> false_sel);
141813
141814 static idx_t NotDistinctFrom(Vector &left, Vector &right, optional_ptr<const SelectionVector> sel, idx_t count,
141815 optional_ptr<SelectionVector> true_sel, optional_ptr<SelectionVector> false_sel);
141816
141817 static idx_t DistinctGreaterThan(Vector &left, Vector &right, optional_ptr<const SelectionVector> sel, idx_t count,
141818 optional_ptr<SelectionVector> true_sel, optional_ptr<SelectionVector> false_sel,
141819 optional_ptr<ValidityMask> null_mask = nullptr);
141820
141821 static idx_t DistinctGreaterThanEquals(Vector &left, Vector &right, optional_ptr<const SelectionVector> sel,
141822 idx_t count, optional_ptr<SelectionVector> true_sel,
141823 optional_ptr<SelectionVector> false_sel,
141824 optional_ptr<ValidityMask> null_mask = nullptr);
141825
141826 static idx_t DistinctLessThan(Vector &left, Vector &right, optional_ptr<const SelectionVector> sel, idx_t count,
141827 optional_ptr<SelectionVector> true_sel, optional_ptr<SelectionVector> false_sel,
141828 optional_ptr<ValidityMask> null_mask = nullptr);
141829
141830 static idx_t DistinctLessThanEquals(Vector &left, Vector &right, optional_ptr<const SelectionVector> sel,
141831 idx_t count, optional_ptr<SelectionVector> true_sel,
141832 optional_ptr<SelectionVector> false_sel,
141833 optional_ptr<ValidityMask> null_mask = nullptr);
141834
141835 static idx_t DistinctGreaterThanNullsFirst(Vector &left, Vector &right, optional_ptr<const SelectionVector> sel,
141836 idx_t count, optional_ptr<SelectionVector> true_sel,
141837 optional_ptr<SelectionVector> false_sel,
141838 optional_ptr<ValidityMask> null_mask = nullptr);
141839
141840 static idx_t DistinctLessThanNullsFirst(Vector &left, Vector &right, optional_ptr<const SelectionVector> sel,
141841 idx_t count, optional_ptr<SelectionVector> true_sel,
141842 optional_ptr<SelectionVector> false_sel,
141843 optional_ptr<ValidityMask> null_mask = nullptr);
141844
141845
141846
141847
141848
141849 static idx_t NestedNotEquals(Vector &left, Vector &right, optional_ptr<const SelectionVector> sel, idx_t count,
141850 optional_ptr<SelectionVector> true_sel, optional_ptr<SelectionVector> false_sel,
141851 optional_ptr<ValidityMask> null_mask = nullptr);
141852
141853 static idx_t NestedEquals(Vector &left, Vector &right, optional_ptr<const SelectionVector> sel, idx_t count,
141854 optional_ptr<SelectionVector> true_sel, optional_ptr<SelectionVector> false_sel,
141855 optional_ptr<ValidityMask> null_mask = nullptr);
141856
141857
141858
141859
141860
141861 static void Hash(Vector &input, Vector &hashes, idx_t count);
141862 static void Hash(Vector &input, Vector &hashes, const SelectionVector &rsel, idx_t count);
141863
141864 static void CombineHash(Vector &hashes, Vector &input, idx_t count);
141865 static void CombineHash(Vector &hashes, Vector &input,
const SelectionVector &rsel, idx_t count);
141866
141867
141868
141869
141870 static void GenerateSequence(Vector &result, idx_t count, int64_t start = 0, int64_t increment = 1);
141871 static void GenerateSequence(Vector &result, idx_t count, const SelectionVector &sel, int64_t start = 0,
141872 int64_t increment = 1);
141873
141874
141875
141879 DUCKDB_API static bool TryCast(CastFunctionSet &set, GetCastFunctionInput &input, Vector &source, Vector &result,
141880 idx_t count, string *error_message, bool strict = false,
141881 const bool nullify_parent = false);
141882 DUCKDB_API static bool DefaultTryCast(Vector &source, Vector &result, idx_t count, string *error_message,
141883 bool strict = false);
141884 DUCKDB_API static bool TryCast(ClientContext &context, Vector &source, Vector &result, idx_t count,
141885 string *error_message, bool strict = false, const bool nullify_parent = false);
141887 DUCKDB_API static void Cast(ClientContext &context, Vector &source, Vector &result, idx_t count,
141888 bool strict = false);
141889 DUCKDB_API static void DefaultCast(Vector &source, Vector &result, idx_t count, bool strict = false);
141890
141891
141892 static void Copy(const Vector &source, Vector &target, idx_t source_count, idx_t source_offset,
141893 idx_t target_offset);
141894 static void Copy(const Vector &source, Vector &target, const SelectionVector &sel, idx_t source_count,
141895 idx_t source_offset, idx_t target_offset);
141896 static void Copy(const Vector &source, Vector &target, const SelectionVector &sel, idx_t source_count,
141897 idx_t source_offset, idx_t target_offset, idx_t copy_count);
141898
141899
141900
141901 static void WriteToStorage(Vector &source, idx_t count, data_ptr_t target);
141902
141903
141904 static void ReadFromStorage(data_ptr_t source, idx_t count, Vector &result);
141905};
141906}
141907
141908
141909#include <functional>
141910
141911namespace duckdb {
141912
141913struct DefaultNullCheckOperator {
141914 template <class LEFT_TYPE, class RIGHT_TYPE>
141915 static inline bool Operation(LEFT_TYPE left, RIGHT_TYPE right) {
141916 return false;
141917 }
141918};
141919
141920struct BinaryStandardOperatorWrapper {
141921 template <class FUNC, class OP, class LEFT_TYPE, class RIGHT_TYPE, class RESULT_TYPE>
141922 static inline RESULT_TYPE Operation(FUNC fun, LEFT_TYPE left, RIGHT_TYPE right, ValidityMask &mask, idx_t idx) {
141923 return OP::template Operation<LEFT_TYPE, RIGHT_TYPE, RESULT_TYPE>(left, right);
141924 }
141925
141926 static bool AddsNulls() {
141927 return false;
141928 }
141929};
141930
141931struct BinarySingleArgumentOperatorWrapper {
141932 template <class FUNC, class OP, class LEFT_TYPE, class RIGHT_TYPE, class RESULT_TYPE>
141933 static inline RESULT_TYPE Operation(FUNC fun, LEFT_TYPE left, RIGHT_TYPE right, ValidityMask &mask, idx_t idx) {
141934 return OP::template Operation<LEFT_TYPE>(left, right);
141935 }
141936
141937 static bool AddsNulls() {
141938 return false;
141939 }
141940};
141941
141942struct BinaryLambdaWrapper {
141943 template <class FUNC, class OP, class LEFT_TYPE, class RIGHT_TYPE, class RESULT_TYPE>
141944 static inline RESULT_TYPE Operation(FUNC fun, LEFT_TYPE left, RIGHT_TYPE right, ValidityMask &mask, idx_t idx) {
141945 return fun(left, right);
141946 }
141947
141948 static bool AddsNulls() {
141949 return false;
141950 }
141951};
141952
141953struct BinaryLambdaWrapperWithNulls {
141954 template <class FUNC, class OP, class LEFT_TYPE, class RIGHT_TYPE, class RESULT_TYPE>
141955 static inline RESULT_TYPE Operation(FUNC fun, LEFT_TYPE left, RIGHT_TYPE right, ValidityMask &mask, idx_t idx) {
141956 return fun(left, right, mask, idx);
141957 }
141958
141959 static bool AddsNulls() {
141960 return true;
141961 }
141962};
141963
141964struct BinaryExecutor {
141965#ifndef DUCKDB_SMALLER_BINARY
141966 template <class LEFT_TYPE, class RIGHT_TYPE, class RESULT_TYPE, class OPWRAPPER, class OP, class FUNC,
141967 bool LEFT_CONSTANT, bool RIGHT_CONSTANT>
141968 static void ExecuteFlatLoop(const LEFT_TYPE *__restrict ldata, const RIGHT_TYPE *__restrict rdata,
141969 RESULT_TYPE *__restrict result_data, idx_t count, ValidityMask &mask, FUNC fun) {
141970 if (!LEFT_CONSTANT) {
141971 ASSERT_RESTRICT(ldata, ldata + count, result_data, result_data + count);
141972 }
141973 if (!RIGHT_CONSTANT) {
141974 ASSERT_RESTRICT(rdata, rdata + count, result_data, result_data + count);
141975 }
141976
141977 if (!
mask.AllValid()) {
141978 idx_t base_idx = 0;
141979 auto entry_count = ValidityMask::EntryCount(count);
141980 for (idx_t entry_idx = 0; entry_idx < entry_count; entry_idx++) {
141981 auto validity_entry =
mask.GetValidityEntry(entry_idx);
141982 idx_t next = MinValue<idx_t>(base_idx + ValidityMask::BITS_PER_VALUE, count);
141983 if (ValidityMask::AllValid(validity_entry)) {
141984
141985 for (; base_idx < next; base_idx++) {
141986 auto lentry = ldata[LEFT_CONSTANT ? 0 : base_idx];
141987 auto rentry = rdata[RIGHT_CONSTANT ? 0 : base_idx];
141988 result_data[base_idx] =
141989 OPWRAPPER::template Operation<FUNC, OP, LEFT_TYPE, RIGHT_TYPE, RESULT_TYPE>(
141990 fun, lentry, rentry, mask, base_idx);
141991 }
141992 } else if (ValidityMask::NoneValid(validity_entry)) {
141993
141994 base_idx = next;
141995 continue;
141996 } else {
141997
141998 idx_t start = base_idx;
141999 for (; base_idx < next; base_idx++) {
142000 if (ValidityMask::RowIsValid(validity_entry, base_idx - start)) {
142001 auto lentry = ldata[LEFT_CONSTANT ? 0 : base_idx];
142002 auto rentry = rdata[RIGHT_CONSTANT ? 0 : base_idx];
142003 result_data[base_idx] =
142004 OPWRAPPER::template Operation<FUNC, OP, LEFT_TYPE, RIGHT_TYPE, RESULT_TYPE>(
142005 fun, lentry, rentry, mask, base_idx);
142006 }
142007 }
142008 }
142009 }
142010 } else {
142011 for (idx_t i = 0; i < count; i++) {
142012 auto lentry = ldata[LEFT_CONSTANT ? 0 : i];
142013 auto rentry = rdata[RIGHT_CONSTANT ? 0 : i];
142014 result_data[i] = OPWRAPPER::template Operation<FUNC, OP, LEFT_TYPE, RIGHT_TYPE, RESULT_TYPE>(
142015 fun, lentry, rentry, mask, i);
142016 }
142017 }
142018 }
142019#endif
142020
142021 template <class LEFT_TYPE, class RIGHT_TYPE, class RESULT_TYPE, class OPWRAPPER, class OP, class FUNC>
142022 static void ExecuteConstant(Vector &left, Vector &right, Vector &result, FUNC fun) {
142023 result.SetVectorType(VectorType::CONSTANT_VECTOR);
142024
142025 auto ldata = ConstantVector::GetData<LEFT_TYPE>(left);
142026 auto rdata = ConstantVector::GetData<RIGHT_TYPE>(right);
142027 auto result_data = ConstantVector::GetData<RESULT_TYPE>(result);
142028
142029 if (ConstantVector::IsNull(left) || ConstantVector::IsNull(right)) {
142030 ConstantVector::SetNull(result, true);
142031 return;
142032 }
142033 *result_data = OPWRAPPER::template Operation<FUNC, OP, LEFT_TYPE, RIGHT_TYPE, RESULT_TYPE>(
142034 fun, *ldata, *rdata, ConstantVector::Validity(result), 0);
142035 }
142036
142037#ifndef DUCKDB_SMALLER_BINARY
142038 template <class LEFT_TYPE, class RIGHT_TYPE, class RESULT_TYPE, class OPWRAPPER, class OP, class FUNC,
142039 bool LEFT_CONSTANT, bool RIGHT_CONSTANT>
142040 static void ExecuteFlat(Vector &left, Vector &right, Vector &result, idx_t count, FUNC fun) {
142041 auto ldata = FlatVector::GetData<LEFT_TYPE>(left);
142042 auto rdata = FlatVector::GetData<RIGHT_TYPE>(right);
142043
142044 if ((LEFT_CONSTANT && ConstantVector::IsNull(left)) || (RIGHT_CONSTANT && ConstantVector::IsNull(right))) {
142045
142046 result.SetVectorType(VectorType::CONSTANT_VECTOR);
142047 ConstantVector::SetNull(result, true);
142048 return;
142049 }
142050
142051 result.SetVectorType(VectorType::FLAT_VECTOR);
142052 auto result_data = FlatVector::GetData<RESULT_TYPE>(result);
142053 auto &result_validity = FlatVector::Validity(result);
142054 if (LEFT_CONSTANT) {
142055 if (OPWRAPPER::AddsNulls()) {
142056 result_validity.Copy(FlatVector::Validity(right), count);
142057 } else {
142058 FlatVector::SetValidity(result, FlatVector::Validity(right));
142059 }
142060 } else if (RIGHT_CONSTANT) {
142061 if (OPWRAPPER::AddsNulls()) {
142062 result_validity.Copy(FlatVector::Validity(left), count);
142063 } else {
142064 FlatVector::SetValidity(result, FlatVector::Validity(left));
142065 }
142066 } else {
142067 if (OPWRAPPER::AddsNulls()) {
142068 result_validity.Copy(FlatVector::Validity(left), count);
142069 if (result_validity.AllValid()) {
142070 result_validity.Copy(FlatVector::Validity(right), count);
142071 } else {
142072 result_validity.Combine(FlatVector::Validity(right), count);
142073 }
142074 } else {
142075 FlatVector::SetValidity(result, FlatVector::Validity(left));
142076 result_validity.Combine(FlatVector::Validity(right), count);
142077 }
142078 }
142079 ExecuteFlatLoop<LEFT_TYPE, RIGHT_TYPE, RESULT_TYPE, OPWRAPPER, OP, FUNC, LEFT_CONSTANT, RIGHT_CONSTANT>(
142080 ldata, rdata, result_data, count, result_validity, fun);
142081 }
142082#endif
142083
142084 template <class LEFT_TYPE, class RIGHT_TYPE, class RESULT_TYPE, class OPWRAPPER, class OP, class FUNC>
142085 static void ExecuteGenericLoop(const LEFT_TYPE *__restrict ldata, const RIGHT_TYPE *__restrict rdata,
142086 RESULT_TYPE *__restrict result_data, const SelectionVector *__restrict lsel,
142087 const SelectionVector *__restrict rsel, idx_t count, ValidityMask &lvalidity,
142088 ValidityMask &rvalidity, ValidityMask &result_validity, FUNC fun) {
142089 if (!lvalidity.AllValid() || !rvalidity.AllValid()) {
142090 for (idx_t i = 0; i < count; i++) {
142091 auto lindex = lsel->get_index(i);
142092 auto rindex = rsel->get_index(i);
142093 if (lvalidity.RowIsValid(lindex) && rvalidity.RowIsValid(rindex)) {
142094 auto lentry = ldata[lindex];
142095 auto rentry = rdata[rindex];
142096 result_data[i] = OPWRAPPER::template Operation<FUNC, OP, LEFT_TYPE, RIGHT_TYPE, RESULT_TYPE>(
142097 fun, lentry, rentry, result_validity, i);
142098 } else {
142099 result_validity.SetInvalid(i);
142100 }
142101 }
142102 } else {
142103 for (idx_t i = 0; i < count; i++) {
142104 auto lentry = ldata[lsel->get_index(i)];
142105 auto rentry = rdata[rsel->get_index(i)];
142106 result_data[i] = OPWRAPPER::template Operation<FUNC, OP, LEFT_TYPE, RIGHT_TYPE, RESULT_TYPE>(
142107 fun, lentry, rentry, result_validity, i);
142108 }
142109 }
142110 }
142111
142112 template <class LEFT_TYPE, class RIGHT_TYPE, class RESULT_TYPE, class OPWRAPPER, class OP, class FUNC>
142113 static void ExecuteGeneric(Vector &left, Vector &right, Vector &result, idx_t count, FUNC fun) {
142114 UnifiedVectorFormat ldata, rdata;
142115
142116 left.ToUnifiedFormat(count, ldata);
142117 right.ToUnifiedFormat(count, rdata);
142118
142119 result.SetVectorType(VectorType::FLAT_VECTOR);
142120 auto result_data = FlatVector::GetData<RESULT_TYPE>(result);
142121 ExecuteGenericLoop<LEFT_TYPE, RIGHT_TYPE, RESULT_TYPE, OPWRAPPER, OP, FUNC>(
142122 UnifiedVectorFormat::GetData<LEFT_TYPE>(ldata), UnifiedVectorFormat::GetData<RIGHT_TYPE>(rdata),
142123 result_data, ldata.sel, rdata.sel, count, ldata.validity, rdata.validity, FlatVector::Validity(result),
142124 fun);
142125 }
142126
142127 template <class LEFT_TYPE, class RIGHT_TYPE, class RESULT_TYPE, class OPWRAPPER, class OP, class FUNC>
142128 static void ExecuteSwitch(Vector &left, Vector &right, Vector &result, idx_t count, FUNC fun) {
142129 auto left_vector_type = left.GetVectorType();
142130 auto right_vector_type = right.GetVectorType();
142131 if (left_vector_type == VectorType::CONSTANT_VECTOR && right_vector_type == VectorType::CONSTANT_VECTOR) {
142132 ExecuteConstant<LEFT_TYPE, RIGHT_TYPE, RESULT_TYPE, OPWRAPPER, OP, FUNC>(left, right, result, fun);
142133#ifndef DUCKDB_SMALLER_BINARY
142134 } else if (left_vector_type == VectorType::FLAT_VECTOR && right_vector_type == VectorType::CONSTANT_VECTOR) {
142135 ExecuteFlat<LEFT_TYPE, RIGHT_TYPE, RESULT_TYPE, OPWRAPPER, OP, FUNC, false, true>(left, right, result,
142136 count, fun);
142137 } else if (left_vector_type == VectorType::CONSTANT_VECTOR && right_vector_type == VectorType::FLAT_VECTOR) {
142138 ExecuteFlat<LEFT_TYPE, RIGHT_TYPE, RESULT_TYPE, OPWRAPPER, OP, FUNC, true, false>(left, right, result,
142139 count, fun);
142140 } else if (left_vector_type == VectorType::FLAT_VECTOR && right_vector_type == VectorType::FLAT_VECTOR) {
142141 ExecuteFlat<LEFT_TYPE, RIGHT_TYPE, RESULT_TYPE, OPWRAPPER, OP, FUNC, false, false>(left, right, result,
142142 count, fun);
142143#endif
142144 } else {
142145 ExecuteGeneric<LEFT_TYPE, RIGHT_TYPE, RESULT_TYPE, OPWRAPPER, OP, FUNC>(left, right, result, count, fun);
142146 }
142147 }
142148
142149public:
142150 template <class LEFT_TYPE, class RIGHT_TYPE, class RESULT_TYPE,
142151 class FUNC = std::function<RESULT_TYPE(LEFT_TYPE, RIGHT_TYPE)>>
142152 static void Execute(Vector &left, Vector &right, Vector &result, idx_t count, FUNC fun) {
142153 ExecuteSwitch<LEFT_TYPE, RIGHT_TYPE, RESULT_TYPE, BinaryLambdaWrapper, bool, FUNC>(left, right, result, count,
142154 fun);
142155 }
142156
142157 template <class LEFT_TYPE, class RIGHT_TYPE, class RESULT_TYPE, class OP,
142158 class OPWRAPPER = BinarySingleArgumentOperatorWrapper>
142159 static void Execute(Vector &left, Vector &right, Vector &result, idx_t count) {
142160 ExecuteSwitch<LEFT_TYPE, RIGHT_TYPE, RESULT_TYPE, OPWRAPPER, OP, bool>(left, right, result, count, false);
142161 }
142162
142163 template <class LEFT_TYPE, class RIGHT_TYPE, class RESULT_TYPE, class OP>
142164 static void ExecuteStandard(Vector &left, Vector &right, Vector &result, idx_t count) {
142165 ExecuteSwitch<LEFT_TYPE, RIGHT_TYPE, RESULT_TYPE, BinaryStandardOperatorWrapper, OP, bool>(left, right, result,
142166 count, false);
142167 }
142168
142169 template <class LEFT_TYPE, class RIGHT_TYPE, class RESULT_TYPE,
142170 class FUNC = std::function<RESULT_TYPE(LEFT_TYPE, RIGHT_TYPE, ValidityMask &, idx_t)>>
142171 static void ExecuteWithNulls(Vector &left, Vector &right, Vector &result, idx_t count, FUNC fun) {
142172 ExecuteSwitch<LEFT_TYPE, RIGHT_TYPE, RESULT_TYPE, BinaryLambdaWrapperWithNulls, bool, FUNC>(left, right, result,
142173 count, fun);
142174 }
142175
142176public:
142177 template <class LEFT_TYPE, class RIGHT_TYPE, class OP>
142178 static idx_t SelectConstant(Vector &left, Vector &right,
const SelectionVector *sel, idx_t count,
142179 SelectionVector *true_sel, SelectionVector *false_sel) {
142180 auto ldata = ConstantVector::GetData<LEFT_TYPE>(left);
142181 auto rdata = ConstantVector::GetData<RIGHT_TYPE>(right);
142182
142183
142184
142185 if (ConstantVector::IsNull(left) || ConstantVector::IsNull(right) || !OP::Operation(*ldata, *rdata)) {
142186 if (false_sel) {
142187 for (idx_t i = 0; i < count; i++) {
142188 false_sel->set_index(i, sel->get_index(i));
142189 }
142190 }
142191 return 0;
142192 } else {
142193 if (true_sel) {
142194 for (idx_t i = 0; i < count; i++) {
142195 true_sel->set_index(i, sel->get_index(i));
142196 }
142197 }
142198 return count;
142199 }
142200 }
142201
142202#ifndef DUCKDB_SMALLER_BINARY
142203 template <class LEFT_TYPE, class RIGHT_TYPE, class OP, bool LEFT_CONSTANT, bool RIGHT_CONSTANT, bool HAS_TRUE_SEL,
142204 bool HAS_FALSE_SEL>
142205 static inline idx_t SelectFlatLoop(
const LEFT_TYPE *__restrict ldata,
const RIGHT_TYPE *__restrict rdata,
142206 const SelectionVector *sel, idx_t count, ValidityMask &validity_mask,
142207 SelectionVector *true_sel, SelectionVector *false_sel) {
142208 idx_t true_count = 0, false_count = 0;
142209 idx_t base_idx = 0;
142210 auto entry_count = ValidityMask::EntryCount(count);
142211 for (idx_t entry_idx = 0; entry_idx < entry_count; entry_idx++) {
142212 auto validity_entry = validity_mask.GetValidityEntry(entry_idx);
142213 idx_t next = MinValue<idx_t>(base_idx + ValidityMask::BITS_PER_VALUE, count);
142214 if (ValidityMask::AllValid(validity_entry)) {
142215
142216 for (; base_idx < next; base_idx++) {
142217 idx_t result_idx = sel->get_index(base_idx);
142218 idx_t lidx = LEFT_CONSTANT ? 0 : base_idx;
142219 idx_t ridx = RIGHT_CONSTANT ? 0 : base_idx;
142220 bool comparison_result = OP::Operation(ldata[lidx], rdata[ridx]);
142221 if (HAS_TRUE_SEL) {
142222 true_sel->set_index(true_count, result_idx);
142223 true_count += comparison_result;
142224 }
142225 if (HAS_FALSE_SEL) {
142226 false_sel->set_index(false_count, result_idx);
142227 false_count += !comparison_result;
142228 }
142229 }
142230 } else if (ValidityMask::NoneValid(validity_entry)) {
142231
142232 if (HAS_FALSE_SEL) {
142233 for (; base_idx < next; base_idx++) {
142234 idx_t result_idx = sel->get_index(base_idx);
142235 false_sel->set_index(false_count, result_idx);
142236 false_count++;
142237 }
142238 }
142239 base_idx = next;
142240 continue;
142241 } else {
142242
142243 idx_t start = base_idx;
142244 for (; base_idx < next; base_idx++) {
142245 idx_t result_idx = sel->get_index(base_idx);
142246 idx_t lidx = LEFT_CONSTANT ? 0 : base_idx;
142247 idx_t ridx = RIGHT_CONSTANT ? 0 : base_idx;
142248 bool comparison_result = ValidityMask::RowIsValid(validity_entry, base_idx - start) &&
142249 OP::Operation(ldata[lidx], rdata[ridx]);
142250 if (HAS_TRUE_SEL) {
142251 true_sel->set_index(true_count, result_idx);
142252 true_count += comparison_result;
142253 }
142254 if (HAS_FALSE_SEL) {
142255 false_sel->set_index(false_count, result_idx);
142256 false_count += !comparison_result;
142257 }
142258 }
142259 }
142260 }
142261 if (HAS_TRUE_SEL) {
142262 return true_count;
142263 } else {
142264 return count - false_count;
142265 }
142266 }
142267
142268 template <class LEFT_TYPE, class RIGHT_TYPE, class OP, bool LEFT_CONSTANT, bool RIGHT_CONSTANT>
142269 static inline idx_t SelectFlatLoopSwitch(
const LEFT_TYPE *__restrict ldata,
const RIGHT_TYPE *__restrict rdata,
142270 const SelectionVector *sel, idx_t count, ValidityMask &mask,
142271 SelectionVector *true_sel, SelectionVector *false_sel) {
142272 if (true_sel && false_sel) {
142273 return SelectFlatLoop<LEFT_TYPE, RIGHT_TYPE, OP, LEFT_CONSTANT, RIGHT_CONSTANT, true, true>(
142274 ldata, rdata, sel, count, mask, true_sel, false_sel);
142275 } else if (true_sel) {
142276 return SelectFlatLoop<LEFT_TYPE, RIGHT_TYPE, OP, LEFT_CONSTANT, RIGHT_CONSTANT, true, false>(
142277 ldata, rdata, sel, count, mask, true_sel, false_sel);
142278 } else {
142279 D_ASSERT(false_sel);
142280 return SelectFlatLoop<LEFT_TYPE, RIGHT_TYPE, OP, LEFT_CONSTANT, RIGHT_CONSTANT, false, true>(
142281 ldata, rdata, sel, count, mask, true_sel, false_sel);
142282 }
142283 }
142284
142285 template <class LEFT_TYPE, class RIGHT_TYPE, class OP, bool LEFT_CONSTANT, bool RIGHT_CONSTANT>
142286 static idx_t SelectFlat(Vector &left, Vector &right,
const SelectionVector *sel, idx_t count,
142287 SelectionVector *true_sel, SelectionVector *false_sel) {
142288 auto ldata = FlatVector::GetData<LEFT_TYPE>(left);
142289 auto rdata = FlatVector::GetData<RIGHT_TYPE>(right);
142290
142291 if (LEFT_CONSTANT && ConstantVector::IsNull(left)) {
142292 if (false_sel) {
142293 for (idx_t i = 0; i < count; i++) {
142294 false_sel->set_index(i, sel->get_index(i));
142295 }
142296 }
142297 return 0;
142298 }
142299 if (RIGHT_CONSTANT && ConstantVector::IsNull(right)) {
142300 if (false_sel) {
142301 for (idx_t i = 0; i < count; i++) {
142302 false_sel->set_index(i, sel->get_index(i));
142303 }
142304 }
142305 return 0;
142306 }
142307
142308 if (LEFT_CONSTANT) {
142309 return SelectFlatLoopSwitch<LEFT_TYPE, RIGHT_TYPE, OP, LEFT_CONSTANT, RIGHT_CONSTANT>(
142310 ldata, rdata, sel, count, FlatVector::Validity(right), true_sel, false_sel);
142311 } else if (RIGHT_CONSTANT) {
142312 return SelectFlatLoopSwitch<LEFT_TYPE, RIGHT_TYPE, OP, LEFT_CONSTANT, RIGHT_CONSTANT>(
142313 ldata, rdata, sel, count, FlatVector::Validity(left), true_sel, false_sel);
142314 } else {
142315 ValidityMask combined_mask = FlatVector::Validity(left);
142316 combined_mask.Combine(FlatVector::Validity(right), count);
142317 return SelectFlatLoopSwitch<LEFT_TYPE, RIGHT_TYPE, OP, LEFT_CONSTANT, RIGHT_CONSTANT>(
142318 ldata, rdata, sel, count, combined_mask, true_sel, false_sel);
142319 }
142320 }
142321#endif
142322
142323#ifndef DUCKDB_SMALLER_BINARY
142324 template <class LEFT_TYPE, class RIGHT_TYPE, class OP, bool NO_NULL, bool HAS_TRUE_SEL, bool HAS_FALSE_SEL>
142325#else
142326 template <class LEFT_TYPE, class RIGHT_TYPE, class OP>
142327#endif
142328 static inline idx_t
142329 SelectGenericLoop(const LEFT_TYPE *__restrict ldata, const RIGHT_TYPE *__restrict rdata,
142330 const SelectionVector *__restrict lsel, const SelectionVector *__restrict rsel,
142331 const SelectionVector *__restrict result_sel, idx_t count, ValidityMask &lvalidity,
142332 ValidityMask &rvalidity, SelectionVector *true_sel, SelectionVector *false_sel) {
142333 idx_t true_count = 0, false_count = 0;
142334#ifdef DUCKDB_SMALLER_BINARY
142335 const bool HAS_TRUE_SEL = true_sel;
142336 const bool HAS_FALSE_SEL = false_sel;
142337 const bool NO_NULL = false;
142338#endif
142339 for (idx_t i = 0; i < count; i++) {
142340 auto result_idx = result_sel->get_index(i);
142341 auto lindex = lsel->get_index(i);
142342 auto rindex = rsel->get_index(i);
142343 if ((NO_NULL || (lvalidity.RowIsValid(lindex) && rvalidity.RowIsValid(rindex))) &&
142344 OP::Operation(ldata[lindex], rdata[rindex])) {
142345 if (HAS_TRUE_SEL) {
142346 true_sel->set_index(true_count++, result_idx);
142347 }
142348 } else {
142349 if (HAS_FALSE_SEL) {
142350 false_sel->set_index(false_count++, result_idx);
142351 }
142352 }
142353 }
142354 if (HAS_TRUE_SEL) {
142355 return true_count;
142356 } else {
142357 return count - false_count;
142358 }
142359 }
142360
142361#ifndef DUCKDB_SMALLER_BINARY
142362 template <class LEFT_TYPE, class RIGHT_TYPE, class OP, bool NO_NULL>
142363 static inline idx_t
142364 SelectGenericLoopSelSwitch(const LEFT_TYPE *__restrict ldata, const RIGHT_TYPE *__restrict rdata,
142365 const SelectionVector *__restrict lsel, const SelectionVector *__restrict rsel,
142366 const SelectionVector *__restrict result_sel, idx_t count, ValidityMask &lvalidity,
142367 ValidityMask &rvalidity, SelectionVector *true_sel, SelectionVector *false_sel) {
142368 if (true_sel && false_sel) {
142369 return SelectGenericLoop<LEFT_TYPE, RIGHT_TYPE, OP, NO_NULL, true, true>(
142370 ldata, rdata, lsel, rsel, result_sel, count, lvalidity, rvalidity, true_sel, false_sel);
142371 } else if (true_sel) {
142372 return SelectGenericLoop<LEFT_TYPE, RIGHT_TYPE, OP, NO_NULL, true, false>(
142373 ldata, rdata, lsel, rsel, result_sel, count, lvalidity, rvalidity, true_sel, false_sel);
142374 } else {
142375 D_ASSERT(false_sel);
142376 return SelectGenericLoop<LEFT_TYPE, RIGHT_TYPE, OP, NO_NULL, false, true>(
142377 ldata, rdata, lsel, rsel, result_sel, count, lvalidity, rvalidity, true_sel, false_sel);
142378 }
142379 }
142380#endif
142381
142382 template <class LEFT_TYPE, class RIGHT_TYPE, class OP>
142383 static inline idx_t
142384 SelectGenericLoopSwitch(const LEFT_TYPE *__restrict ldata, const RIGHT_TYPE *__restrict rdata,
142385 const SelectionVector *__restrict lsel, const SelectionVector *__restrict rsel,
142386 const SelectionVector *__restrict result_sel, idx_t count, ValidityMask &lvalidity,
142387 ValidityMask &rvalidity, SelectionVector *true_sel, SelectionVector *false_sel) {
142388#ifndef DUCKDB_SMALLER_BINARY
142389 if (!lvalidity.AllValid() || !rvalidity.AllValid()) {
142390 return SelectGenericLoopSelSwitch<LEFT_TYPE, RIGHT_TYPE, OP, false>(
142391 ldata, rdata, lsel, rsel, result_sel, count, lvalidity, rvalidity, true_sel, false_sel);
142392 } else {
142393 return SelectGenericLoopSelSwitch<LEFT_TYPE, RIGHT_TYPE, OP, true>(
142394 ldata, rdata, lsel, rsel, result_sel, count, lvalidity, rvalidity, true_sel, false_sel);
142395 }
142396#else
142397 return SelectGenericLoop<LEFT_TYPE, RIGHT_TYPE, OP>(ldata, rdata, lsel, rsel, result_sel, count, lvalidity,
142398 rvalidity, true_sel, false_sel);
142399#endif
142400 }
142401
142402 template <class LEFT_TYPE, class RIGHT_TYPE, class OP>
142403 static idx_t SelectGeneric(Vector &left, Vector &right,
const SelectionVector *sel, idx_t count,
142404 SelectionVector *true_sel, SelectionVector *false_sel) {
142405 UnifiedVectorFormat ldata, rdata;
142406
142407 left.ToUnifiedFormat(count, ldata);
142408 right.ToUnifiedFormat(count, rdata);
142409
142410 return SelectGenericLoopSwitch<LEFT_TYPE, RIGHT_TYPE, OP>(
142411 UnifiedVectorFormat::GetData<LEFT_TYPE>(ldata), UnifiedVectorFormat::GetData<RIGHT_TYPE>(rdata), ldata.sel,
142412 rdata.sel, sel, count, ldata.validity, rdata.validity, true_sel, false_sel);
142413 }
142414
142415 template <class LEFT_TYPE, class RIGHT_TYPE, class OP>
142416 static idx_t Select(Vector &left, Vector &right,
const SelectionVector *sel, idx_t count, SelectionVector *true_sel,
142417 SelectionVector *false_sel) {
142418 if (!sel) {
142419 sel = FlatVector::IncrementalSelectionVector();
142420 }
142421 if (left.GetVectorType() == VectorType::CONSTANT_VECTOR &&
142422 right.GetVectorType() == VectorType::CONSTANT_VECTOR) {
142423 return SelectConstant<LEFT_TYPE, RIGHT_TYPE, OP>(left, right, sel, count, true_sel, false_sel);
142424#ifndef DUCKDB_SMALLER_BINARY
142425 } else if (left.GetVectorType() == VectorType::CONSTANT_VECTOR &&
142426 right.GetVectorType() == VectorType::FLAT_VECTOR) {
142427 return SelectFlat<LEFT_TYPE, RIGHT_TYPE, OP, true, false>(left, right, sel, count, true_sel, false_sel);
142428 } else if (left.GetVectorType() == VectorType::FLAT_VECTOR &&
142429 right.GetVectorType() == VectorType::CONSTANT_VECTOR) {
142430 return SelectFlat<LEFT_TYPE, RIGHT_TYPE, OP, false, true>(left, right, sel, count, true_sel, false_sel);
142431 } else if (left.GetVectorType() == VectorType::FLAT_VECTOR &&
142432 right.GetVectorType() == VectorType::FLAT_VECTOR) {
142433 return SelectFlat<LEFT_TYPE, RIGHT_TYPE, OP, false, false>(left, right, sel, count, true_sel, false_sel);
142434#endif
142435 } else {
142436 return SelectGeneric<LEFT_TYPE, RIGHT_TYPE, OP>(left, right, sel, count, true_sel, false_sel);
142437 }
142438 }
142439};
142440
142441}
142442
142443
142444
142445
142446
142447
142448
142449
142450
142451
142452
142453
142454
142455
142456
142457#include <functional>
142458
142459namespace duckdb {
142460
142461template <class OP>
142462struct TernaryStandardOperatorWrapper {
142463 template <class FUN, class A_TYPE, class B_TYPE, class C_TYPE, class RESULT_TYPE>
142464 static inline RESULT_TYPE Operation(FUN fun, A_TYPE a, B_TYPE b, C_TYPE c, ValidityMask &mask, idx_t idx) {
142465 return OP::template Operation<A_TYPE, B_TYPE, C_TYPE, RESULT_TYPE>(a, b, c);
142466 }
142467};
142468
142469struct TernaryLambdaWrapper {
142470 template <class FUN, class A_TYPE, class B_TYPE, class C_TYPE, class RESULT_TYPE>
142471 static inline RESULT_TYPE Operation(FUN fun, A_TYPE a, B_TYPE b, C_TYPE c, ValidityMask &mask, idx_t idx) {
142472 return fun(a, b, c);
142473 }
142474};
142475
142476struct TernaryLambdaWrapperWithNulls {
142477 template <class FUN, class A_TYPE, class B_TYPE, class C_TYPE, class RESULT_TYPE>
142478 static inline RESULT_TYPE Operation(FUN fun, A_TYPE a, B_TYPE b, C_TYPE c, ValidityMask &mask, idx_t idx) {
142479 return fun(a, b, c, mask, idx);
142480 }
142481};
142482
142483struct TernaryExecutor {
142484private:
142485 template <class A_TYPE, class B_TYPE, class C_TYPE, class RESULT_TYPE, class OPWRAPPER, class FUN>
142486 static inline void ExecuteLoop(const A_TYPE *__restrict adata, const B_TYPE *__restrict bdata,
142487 const C_TYPE *__restrict cdata, RESULT_TYPE *__restrict result_data, idx_t count,
142488 const SelectionVector &asel, const SelectionVector &bsel,
142489 const SelectionVector &csel, ValidityMask &avalidity, ValidityMask &bvalidity,
142490 ValidityMask &cvalidity, ValidityMask &result_validity, FUN fun) {
142491 if (!avalidity.AllValid() || !bvalidity.AllValid() || !cvalidity.AllValid()) {
142492 for (idx_t i = 0; i < count; i++) {
142493 auto aidx = asel.get_index(i);
142494 auto bidx = bsel.get_index(i);
142495 auto cidx = csel.get_index(i);
142496 if (avalidity.RowIsValid(aidx) && bvalidity.RowIsValid(bidx) && cvalidity.RowIsValid(cidx)) {
142497 result_data[i] = OPWRAPPER::template Operation<FUN, A_TYPE, B_TYPE, C_TYPE, RESULT_TYPE>(
142498 fun, adata[aidx], bdata[bidx], cdata[cidx], result_validity, i);
142499 } else {
142500 result_validity.SetInvalid(i);
142501 }
142502 }
142503 } else {
142504 for (idx_t i = 0; i < count; i++) {
142505 auto aidx = asel.get_index(i);
142506 auto bidx = bsel.get_index(i);
142507 auto cidx = csel.get_index(i);
142508 result_data[i] = OPWRAPPER::template Operation<FUN, A_TYPE, B_TYPE, C_TYPE, RESULT_TYPE>(
142509 fun, adata[aidx], bdata[bidx], cdata[cidx], result_validity, i);
142510 }
142511 }
142512 }
142513
142514public:
142515 template <class A_TYPE, class B_TYPE, class C_TYPE, class RESULT_TYPE, class OPWRAPPER, class FUN>
142516 static void ExecuteGeneric(Vector &a, Vector &b, Vector &c, Vector &result, idx_t count, FUN fun) {
142517 if (a.GetVectorType() == VectorType::CONSTANT_VECTOR && b.GetVectorType() == VectorType::CONSTANT_VECTOR &&
142518 c.GetVectorType() == VectorType::CONSTANT_VECTOR) {
142519 result.SetVectorType(VectorType::CONSTANT_VECTOR);
142520 if (ConstantVector::IsNull(a) || ConstantVector::IsNull(b) || ConstantVector::IsNull(c)) {
142521 ConstantVector::SetNull(result, true);
142522 } else {
142523 auto adata = ConstantVector::GetData<A_TYPE>(a);
142524 auto bdata = ConstantVector::GetData<B_TYPE>(b);
142525 auto cdata = ConstantVector::GetData<C_TYPE>(c);
142526 auto result_data = ConstantVector::GetData<RESULT_TYPE>(result);
142527 auto &result_validity = ConstantVector::Validity(result);
142528 result_data[0] = OPWRAPPER::template Operation<FUN, A_TYPE, B_TYPE, C_TYPE, RESULT_TYPE>(
142529 fun, adata[0], bdata[0], cdata[0], result_validity, 0);
142530 }
142531 } else {
142532 result.SetVectorType(VectorType::FLAT_VECTOR);
142533
142534 UnifiedVectorFormat adata, bdata, cdata;
142535 a.ToUnifiedFormat(count, adata);
142536 b.ToUnifiedFormat(count, bdata);
142537 c.ToUnifiedFormat(count, cdata);
142538
142539 ExecuteLoop<A_TYPE, B_TYPE, C_TYPE, RESULT_TYPE, OPWRAPPER>(
142540 UnifiedVectorFormat::GetData<A_TYPE>(adata), UnifiedVectorFormat::GetData<B_TYPE>(bdata),
142541 UnifiedVectorFormat::GetData<C_TYPE>(cdata), FlatVector::GetData<RESULT_TYPE>(result), count,
142542 *adata.sel, *bdata.sel, *cdata.sel, adata.validity, bdata.validity, cdata.validity,
142543 FlatVector::Validity(result), fun);
142544 }
142545 }
142546
142547 template <class A_TYPE, class B_TYPE, class C_TYPE, class RESULT_TYPE,
142548 class FUN = std::function<RESULT_TYPE(A_TYPE, B_TYPE, C_TYPE)>>
142549 static void Execute(Vector &a, Vector &b, Vector &c, Vector &result, idx_t count, FUN fun) {
142550 ExecuteGeneric<A_TYPE, B_TYPE, C_TYPE, RESULT_TYPE, TernaryLambdaWrapper, FUN>(a, b, c, result, count, fun);
142551 }
142552
142553 template <class A_TYPE, class B_TYPE, class C_TYPE, class RESULT_TYPE, class OP>
142554 static void ExecuteStandard(Vector &a, Vector &b, Vector &c, Vector &result, idx_t count) {
142555 ExecuteGeneric<A_TYPE, B_TYPE, C_TYPE, RESULT_TYPE, TernaryStandardOperatorWrapper<OP>, bool>(a, b, c, result,
142556 count, false);
142557 }
142558
142559 template <class A_TYPE, class B_TYPE, class C_TYPE, class RESULT_TYPE,
142560 class FUN = std::function<RESULT_TYPE(A_TYPE, B_TYPE, C_TYPE, ValidityMask &, idx_t)>>
142561 static void ExecuteWithNulls(Vector &a, Vector &b, Vector &c, Vector &result, idx_t count, FUN fun) {
142562 ExecuteGeneric<A_TYPE, B_TYPE, C_TYPE, RESULT_TYPE, TernaryLambdaWrapperWithNulls, FUN>(a, b, c, result, count,
142563 fun);
142564 }
142565
142566private:
142567 template <class A_TYPE, class B_TYPE, class C_TYPE, class OP, bool NO_NULL, bool HAS_TRUE_SEL, bool HAS_FALSE_SEL>
142568 static inline idx_t SelectLoop(
const A_TYPE *__restrict adata,
const B_TYPE *__restrict bdata,
142569 const C_TYPE *__restrict cdata, const SelectionVector *result_sel, idx_t count,
142570 const SelectionVector &asel, const SelectionVector &bsel,
142571 const SelectionVector &csel, ValidityMask &avalidity, ValidityMask &bvalidity,
142572 ValidityMask &cvalidity, SelectionVector *true_sel, SelectionVector *false_sel) {
142573 idx_t true_count = 0, false_count = 0;
142574 for (idx_t i = 0; i < count; i++) {
142575 auto result_idx = result_sel->get_index(i);
142576 auto aidx = asel.get_index(i);
142577 auto bidx = bsel.get_index(i);
142578 auto cidx = csel.get_index(i);
142579 bool comparison_result =
142580 (NO_NULL || (avalidity.RowIsValid(aidx) && bvalidity.RowIsValid(bidx) && cvalidity.RowIsValid(cidx))) &&
142581 OP::Operation(adata[aidx], bdata[bidx], cdata[cidx]);
142582 if (HAS_TRUE_SEL) {
142583 true_sel->set_index(true_count, result_idx);
142584 true_count += comparison_result;
142585 }
142586 if (HAS_FALSE_SEL) {
142587 false_sel->set_index(false_count, result_idx);
142588 false_count += !comparison_result;
142589 }
142590 }
142591 if (HAS_TRUE_SEL) {
142592 return true_count;
142593 } else {
142594 return count - false_count;
142595 }
142596 }
142597
142598 template <class A_TYPE, class B_TYPE, class C_TYPE, class OP, bool NO_NULL>
142599 static inline idx_t SelectLoopSelSwitch(UnifiedVectorFormat &adata, UnifiedVectorFormat &bdata,
142600 UnifiedVectorFormat &cdata, const SelectionVector *sel, idx_t count,
142601 SelectionVector *true_sel, SelectionVector *false_sel) {
142602 if (true_sel && false_sel) {
142603 return SelectLoop<A_TYPE, B_TYPE, C_TYPE, OP, NO_NULL, true, true>(
142604 UnifiedVectorFormat::GetData<A_TYPE>(adata), UnifiedVectorFormat::GetData<B_TYPE>(bdata),
142605 UnifiedVectorFormat::GetData<C_TYPE>(cdata), sel, count, *adata.sel, *bdata.sel, *cdata.sel,
142606 adata.validity, bdata.validity, cdata.validity, true_sel, false_sel);
142607 } else if (true_sel) {
142608 return SelectLoop<A_TYPE, B_TYPE, C_TYPE, OP, NO_NULL, true, false>(
142609 UnifiedVectorFormat::GetData<A_TYPE>(adata), UnifiedVectorFormat::GetData<B_TYPE>(bdata),
142610 UnifiedVectorFormat::GetData<C_TYPE>(cdata), sel, count, *adata.sel, *bdata.sel, *cdata.sel,
142611 adata.validity, bdata.validity, cdata.validity, true_sel, false_sel);
142612 } else {
142613 D_ASSERT(false_sel);
142614 return SelectLoop<A_TYPE, B_TYPE, C_TYPE, OP, NO_NULL, false, true>(
142615 UnifiedVectorFormat::GetData<A_TYPE>(adata), UnifiedVectorFormat::GetData<B_TYPE>(bdata),
142616 UnifiedVectorFormat::GetData<C_TYPE>(cdata), sel, count, *adata.sel, *bdata.sel, *cdata.sel,
142617 adata.validity, bdata.validity, cdata.validity, true_sel, false_sel);
142618 }
142619 }
142620
142621 template <class A_TYPE, class B_TYPE, class C_TYPE, class OP>
142622 static inline idx_t SelectLoopSwitch(UnifiedVectorFormat &adata, UnifiedVectorFormat &bdata,
142623 UnifiedVectorFormat &cdata, const SelectionVector *sel, idx_t count,
142624 SelectionVector *true_sel, SelectionVector *false_sel) {
142625 if (!adata.validity.AllValid() || !bdata.validity.AllValid() || !cdata.validity.AllValid()) {
142626 return SelectLoopSelSwitch<A_TYPE, B_TYPE, C_TYPE, OP, false>(adata, bdata, cdata, sel, count, true_sel,
142627 false_sel);
142628 } else {
142629 return SelectLoopSelSwitch<A_TYPE, B_TYPE, C_TYPE, OP, true>(adata, bdata, cdata, sel, count, true_sel,
142630 false_sel);
142631 }
142632 }
142633
142634public:
142635 template <class A_TYPE, class B_TYPE, class C_TYPE, class OP>
142636 static idx_t Select(Vector &a, Vector &b, Vector &c,
const SelectionVector *sel, idx_t count,
142637 SelectionVector *true_sel, SelectionVector *false_sel) {
142638 if (!sel) {
142639 sel = FlatVector::IncrementalSelectionVector();
142640 }
142641 UnifiedVectorFormat adata, bdata, cdata;
142642 a.ToUnifiedFormat(count, adata);
142643 b.ToUnifiedFormat(count, bdata);
142644 c.ToUnifiedFormat(count, cdata);
142645
142646 return SelectLoopSwitch<A_TYPE, B_TYPE, C_TYPE, OP>(adata, bdata, cdata, sel, count, true_sel, false_sel);
142647 }
142648};
142649
142650}
142651
142652
142653
142654
142655
142656
142657
142658
142659
142660
142661
142662
142663
142664
142665
142666
142667
142668
142669
142670
142671
142672
142673
142674
142675
142676
142677namespace duckdb {
142678
142681
142682}
142683
142684
142685#include <functional>
142686
142687namespace duckdb {
142688
142689struct UnaryOperatorWrapper {
142690 template <class OP, class INPUT_TYPE, class RESULT_TYPE>
142691 static inline RESULT_TYPE Operation(INPUT_TYPE input, ValidityMask &mask, idx_t idx, void *dataptr) {
142692 return OP::template Operation<INPUT_TYPE, RESULT_TYPE>(input);
142693 }
142694};
142695
142696struct UnaryLambdaWrapper {
142697 template <class FUNC, class INPUT_TYPE, class RESULT_TYPE>
142698 static inline RESULT_TYPE Operation(INPUT_TYPE input, ValidityMask &mask, idx_t idx, void *dataptr) {
142699 auto fun = (FUNC *)dataptr;
142700 return (*fun)(input);
142701 }
142702};
142703
142704struct GenericUnaryWrapper {
142705 template <class OP, class INPUT_TYPE, class RESULT_TYPE>
142706 static inline RESULT_TYPE Operation(INPUT_TYPE input, ValidityMask &mask, idx_t idx, void *dataptr) {
142707 return OP::template Operation<INPUT_TYPE, RESULT_TYPE>(input, mask, idx, dataptr);
142708 }
142709};
142710
142711struct UnaryLambdaWrapperWithNulls {
142712 template <class FUNC, class INPUT_TYPE, class RESULT_TYPE>
142713 static inline RESULT_TYPE Operation(INPUT_TYPE input, ValidityMask &mask, idx_t idx, void *dataptr) {
142714 auto fun = (FUNC *)dataptr;
142715 return (*fun)(input,
mask, idx);
142716 }
142717};
142718
142719template <class OP>
142720struct UnaryStringOperator {
142721 template <class INPUT_TYPE, class RESULT_TYPE>
142722 static RESULT_TYPE Operation(INPUT_TYPE input, ValidityMask &mask, idx_t idx, void *dataptr) {
142723 auto vector = reinterpret_cast<Vector *>(dataptr);
142724 return OP::template Operation<INPUT_TYPE, RESULT_TYPE>(input, *vector);
142725 }
142726};
142727
142728struct UnaryExecutor {
142729private:
142730 template <class INPUT_TYPE, class RESULT_TYPE, class OPWRAPPER, class OP>
142731 static inline void ExecuteLoop(const INPUT_TYPE *__restrict ldata, RESULT_TYPE *__restrict result_data, idx_t count,
142732 const SelectionVector *__restrict sel_vector, ValidityMask &mask,
142733 ValidityMask &result_mask, void *dataptr, bool adds_nulls) {
142734#ifdef DEBUG
142735
142736 idx_t max_index = 0;
142737 for (idx_t i = 0; i < count; i++) {
142738 auto idx = sel_vector->get_index(i);
142739 max_index = MaxValue(max_index, idx);
142740 }
142741 ASSERT_RESTRICT(ldata, ldata + max_index, result_data, result_data + count);
142742#endif
142743
142744 if (!
mask.AllValid()) {
142745 for (idx_t i = 0; i < count; i++) {
142746 auto idx = sel_vector->get_index(i);
142747 if (
mask.RowIsValidUnsafe(idx)) {
142748 result_data[i] =
142749 OPWRAPPER::template Operation<OP, INPUT_TYPE, RESULT_TYPE>(ldata[idx], result_mask, i, dataptr);
142750 } else {
142751 result_mask.SetInvalid(i);
142752 }
142753 }
142754 } else {
142755 for (idx_t i = 0; i < count; i++) {
142756 auto idx = sel_vector->get_index(i);
142757 result_data[i] =
142758 OPWRAPPER::template Operation<OP, INPUT_TYPE, RESULT_TYPE>(ldata[idx], result_mask, i, dataptr);
142759 }
142760 }
142761 }
142762
142763#ifndef DUCKDB_SMALLER_BINARY
142764 template <class INPUT_TYPE, class RESULT_TYPE, class OPWRAPPER, class OP>
142765 static inline void ExecuteFlat(const INPUT_TYPE *__restrict ldata, RESULT_TYPE *__restrict result_data, idx_t count,
142766 ValidityMask &mask, ValidityMask &result_mask, void *dataptr, bool adds_nulls) {
142767 ASSERT_RESTRICT(ldata, ldata + count, result_data, result_data + count);
142768
142769 if (!
mask.AllValid()) {
142770 if (!adds_nulls) {
142771 result_mask.Initialize(mask);
142772 } else {
142773 result_mask.Copy(mask, count);
142774 }
142775 idx_t base_idx = 0;
142776 auto entry_count = ValidityMask::EntryCount(count);
142777 for (idx_t entry_idx = 0; entry_idx < entry_count; entry_idx++) {
142778 auto validity_entry =
mask.GetValidityEntry(entry_idx);
142779 idx_t next = MinValue<idx_t>(base_idx + ValidityMask::BITS_PER_VALUE, count);
142780 if (ValidityMask::AllValid(validity_entry)) {
142781
142782 for (; base_idx < next; base_idx++) {
142783 result_data[base_idx] = OPWRAPPER::template Operation<OP, INPUT_TYPE, RESULT_TYPE>(
142784 ldata[base_idx], result_mask, base_idx, dataptr);
142785 }
142786 } else if (ValidityMask::NoneValid(validity_entry)) {
142787
142788 base_idx = next;
142789 continue;
142790 } else {
142791
142792 idx_t start = base_idx;
142793 for (; base_idx < next; base_idx++) {
142794 if (ValidityMask::RowIsValid(validity_entry, base_idx - start)) {
142795 D_ASSERT(
mask.RowIsValid(base_idx));
142796 result_data[base_idx] = OPWRAPPER::template Operation<OP, INPUT_TYPE, RESULT_TYPE>(
142797 ldata[base_idx], result_mask, base_idx, dataptr);
142798 }
142799 }
142800 }
142801 }
142802 } else {
142803 for (idx_t i = 0; i < count; i++) {
142804 result_data[i] =
142805 OPWRAPPER::template Operation<OP, INPUT_TYPE, RESULT_TYPE>(ldata[i], result_mask, i, dataptr);
142806 }
142807 }
142808 }
142809#endif
142810
142811 template <class INPUT_TYPE, class RESULT_TYPE, class OPWRAPPER, class OP>
142812 static inline void ExecuteStandard(Vector &input, Vector &result, idx_t count, void *dataptr, bool adds_nulls,
142813 FunctionErrors errors = FunctionErrors::CAN_THROW_RUNTIME_ERROR) {
142814 switch (input.GetVectorType()) {
142815 case VectorType::CONSTANT_VECTOR: {
142816 result.SetVectorType(VectorType::CONSTANT_VECTOR);
142817 auto result_data = ConstantVector::GetData<RESULT_TYPE>(result);
142818 auto ldata = ConstantVector::GetData<INPUT_TYPE>(input);
142819
142820 if (ConstantVector::IsNull(input)) {
142821 ConstantVector::SetNull(result, true);
142822 } else {
142823 ConstantVector::SetNull(result, false);
142824 *result_data = OPWRAPPER::template Operation<OP, INPUT_TYPE, RESULT_TYPE>(
142825 *ldata, ConstantVector::Validity(result), 0, dataptr);
142826 }
142827 break;
142828 }
142829#ifndef DUCKDB_SMALLER_BINARY
142830 case VectorType::FLAT_VECTOR: {
142831 result.SetVectorType(VectorType::FLAT_VECTOR);
142832 auto result_data = FlatVector::GetData<RESULT_TYPE>(result);
142833 auto ldata = FlatVector::GetData<INPUT_TYPE>(input);
142834
142835 ExecuteFlat<INPUT_TYPE, RESULT_TYPE, OPWRAPPER, OP>(ldata, result_data, count, FlatVector::Validity(input),
142836 FlatVector::Validity(result), dataptr, adds_nulls);
142837 break;
142838 }
142839 case VectorType::DICTIONARY_VECTOR: {
142840
142841
142842
142843
142844 if (errors == FunctionErrors::CANNOT_ERROR) {
142845 static constexpr idx_t DICTIONARY_THRESHOLD = 2;
142846 auto dict_size = DictionaryVector::DictionarySize(input);
142847 if (dict_size.IsValid() && dict_size.GetIndex() * DICTIONARY_THRESHOLD <= count) {
142848
142849
142850 auto &dictionary_values = DictionaryVector::Child(input);
142851 if (dictionary_values.GetVectorType() == VectorType::FLAT_VECTOR) {
142852
142853 auto result_data = FlatVector::GetData<RESULT_TYPE>(result);
142854 auto ldata = FlatVector::GetData<INPUT_TYPE>(dictionary_values);
142855 ExecuteFlat<INPUT_TYPE, RESULT_TYPE, OPWRAPPER, OP>(
142856 ldata, result_data, dict_size.GetIndex(), FlatVector::Validity(dictionary_values),
142857 FlatVector::Validity(result), dataptr, adds_nulls);
142858
142859 auto &offsets = DictionaryVector::SelVector(input);
142860 result.Dictionary(result, dict_size.GetIndex(), offsets, count);
142861 break;
142862 }
142863 }
142864 }
142865 DUCKDB_EXPLICIT_FALLTHROUGH;
142866 }
142867#endif
142868 default: {
142869 UnifiedVectorFormat vdata;
142870 input.ToUnifiedFormat(count, vdata);
142871
142872 result.SetVectorType(VectorType::FLAT_VECTOR);
142873 auto result_data = FlatVector::GetData<RESULT_TYPE>(result);
142874 auto ldata = UnifiedVectorFormat::GetData<INPUT_TYPE>(vdata);
142875
142876 ExecuteLoop<INPUT_TYPE, RESULT_TYPE, OPWRAPPER, OP>(ldata, result_data, count, vdata.sel, vdata.validity,
142877 FlatVector::Validity(result), dataptr, adds_nulls);
142878 break;
142879 }
142880 }
142881 }
142882
142883public:
142884 template <class INPUT_TYPE, class RESULT_TYPE, class OP>
142885 static void Execute(Vector &input, Vector &result, idx_t count) {
142886 ExecuteStandard<INPUT_TYPE, RESULT_TYPE, UnaryOperatorWrapper, OP>(input, result, count, nullptr, false);
142887 }
142888
142889 template <class INPUT_TYPE, class RESULT_TYPE, class FUNC = std::function<RESULT_TYPE(INPUT_TYPE)>>
142890 static void Execute(Vector &input, Vector &result, idx_t count, FUNC fun,
142891 FunctionErrors errors = FunctionErrors::CAN_THROW_RUNTIME_ERROR) {
142892 ExecuteStandard<INPUT_TYPE, RESULT_TYPE, UnaryLambdaWrapper, FUNC>(
142893 input, result, count, reinterpret_cast<void *>(&fun), false, errors);
142894 }
142895
142896 template <class INPUT_TYPE, class RESULT_TYPE, class OP>
142897 static void GenericExecute(Vector &input, Vector &result, idx_t count, void *dataptr, bool adds_nulls = false) {
142898 ExecuteStandard<INPUT_TYPE, RESULT_TYPE, GenericUnaryWrapper, OP>(input, result, count, dataptr, adds_nulls);
142899 }
142900
142901 template <class INPUT_TYPE, class RESULT_TYPE,
142902 class FUNC = std::function<RESULT_TYPE(INPUT_TYPE, ValidityMask &, idx_t)>>
142903 static void ExecuteWithNulls(Vector &input, Vector &result, idx_t count, FUNC fun) {
142904 ExecuteStandard<INPUT_TYPE, RESULT_TYPE, UnaryLambdaWrapperWithNulls, FUNC>(input, result, count, (void *)&fun,
142905 true);
142906 }
142907
142908 template <class INPUT_TYPE, class RESULT_TYPE, class OP>
142909 static void ExecuteString(Vector &input, Vector &result, idx_t count) {
142910 UnaryExecutor::GenericExecute<INPUT_TYPE, RESULT_TYPE, UnaryStringOperator<OP>>(input, result, count,
142911 (void *)&result);
142912 }
142913
142914private:
142915
142916 template <class INPUT_TYPE, class FUNC = std::function<bool(INPUT_TYPE)>, bool NO_NULL, bool HAS_TRUE_SEL,
142917 bool HAS_FALSE_SEL>
142918 static inline idx_t SelectLoop(
const INPUT_TYPE *__restrict input_data,
const SelectionVector *result_sel,
142919 const idx_t count, FUNC fun, const SelectionVector &input_sel,
142920 ValidityMask &input_validity, SelectionVector *true_sel,
142921 SelectionVector *false_sel) {
142922 idx_t true_count = 0, false_count = 0;
142923 for (idx_t i = 0; i < count; i++) {
142924 const auto result_idx = result_sel->get_index(i);
142925 const auto idx = input_sel.get_index(i);
142926 const bool comparison_result = (NO_NULL || input_validity.RowIsValid(idx)) && fun(input_data[idx]);
142927 if (HAS_TRUE_SEL) {
142928 true_sel->set_index(true_count, result_idx);
142929 true_count += comparison_result;
142930 }
142931 if (HAS_FALSE_SEL) {
142932 false_sel->set_index(false_count, result_idx);
142933 false_count += !comparison_result;
142934 }
142935 }
142936 if (HAS_TRUE_SEL) {
142937 return true_count;
142938 } else {
142939 return count - false_count;
142940 }
142941 }
142942
142943 template <class INPUT_TYPE, class FUNC = std::function<bool(INPUT_TYPE)>, bool NO_NULL>
142944 static inline idx_t SelectLoopSelSwitch(UnifiedVectorFormat &input_data,
const SelectionVector *sel,
142945 const idx_t count, FUNC fun, SelectionVector *true_sel,
142946 SelectionVector *false_sel) {
142947 if (true_sel && false_sel) {
142948 return SelectLoop<INPUT_TYPE, FUNC, NO_NULL, true, true>(
142949 UnifiedVectorFormat::GetData<INPUT_TYPE>(input_data), sel, count, fun, *input_data.sel,
142950 input_data.validity, true_sel, false_sel);
142951 } else if (true_sel) {
142952 return SelectLoop<INPUT_TYPE, FUNC, NO_NULL, true, false>(
142953 UnifiedVectorFormat::GetData<INPUT_TYPE>(input_data), sel, count, fun, *input_data.sel,
142954 input_data.validity, true_sel, false_sel);
142955 } else {
142956 D_ASSERT(false_sel);
142957 return SelectLoop<INPUT_TYPE, FUNC, NO_NULL, false, true>(
142958 UnifiedVectorFormat::GetData<INPUT_TYPE>(input_data), sel, count, fun, *input_data.sel,
142959 input_data.validity, true_sel, false_sel);
142960 }
142961 }
142962
142963 template <class INPUT_TYPE, class FUNC = std::function<bool(INPUT_TYPE)>>
142964 static inline idx_t SelectLoopSwitch(UnifiedVectorFormat &input_data,
const SelectionVector *sel,
const idx_t count,
142965 FUNC fun, SelectionVector *true_sel, SelectionVector *false_sel) {
142966 if (!input_data.validity.AllValid()) {
142967 return SelectLoopSelSwitch<INPUT_TYPE, FUNC, false>(input_data, sel, count, fun, true_sel, false_sel);
142968 } else {
142969 return SelectLoopSelSwitch<INPUT_TYPE, FUNC, true>(input_data, sel, count, fun, true_sel, false_sel);
142970 }
142971 }
142972
142973public:
142974 template <class INPUT_TYPE, class FUNC = std::function<bool(INPUT_TYPE)>>
142975 static idx_t Select(Vector &input,
const SelectionVector *sel,
const idx_t count, FUNC fun,
142976 SelectionVector *true_sel, SelectionVector *false_sel) {
142977 if (!sel) {
142978 sel = FlatVector::IncrementalSelectionVector();
142979 }
142980 UnifiedVectorFormat input_data;
142981 input.ToUnifiedFormat(count, input_data);
142982
142983 return SelectLoopSwitch<INPUT_TYPE, FUNC>(input_data, sel, count, fun, true_sel, false_sel);
142984 }
142985};
142986
142987}
142988
142989
142990
142991
142992
142993
142994
142995
142996
142997
142998
142999
143000
143001
143002
143003
143004
143005
143006
143007
143008
143009
143010
143011
143012
143013
143014
143015
143016
143017
143018
143019
143020
143021
143022
143023
143024namespace duckdb {
143025
143026using named_parameter_type_map_t = case_insensitive_map_t<LogicalType>;
143027using named_parameter_map_t = case_insensitive_map_t<Value>;
143028
143029}
143030
143031
143032
143033
143034
143035
143036
143037
143038
143039
143040
143041
143042#include <functional>
143043
143044
143045
143046namespace duckdb {
143047
143048class DependencyItem {
143049public:
143050 virtual ~DependencyItem() {};
143051
143052public:
143053 template <class TARGET>
143054 TARGET &Cast() {
143055 DynamicCastCheck<TARGET>(this);
143056 return reinterpret_cast<TARGET &>(*this);
143057 }
143058 template <class TARGET>
143059 const TARGET &Cast() const {
143060 DynamicCastCheck<TARGET>(this);
143061 return reinterpret_cast<const TARGET &>(*this);
143062 }
143063};
143064
143065using dependency_scan_t = std::function<void(const string &name, shared_ptr<DependencyItem> item)>;
143066
143067class ExternalDependency {
143068public:
143069 explicit ExternalDependency() {
143070 }
143071 ~ExternalDependency() {
143072 }
143073
143074public:
143075 void AddDependency(const string &name, shared_ptr<DependencyItem> item) {
143076 objects[name] = std::move(item);
143077 }
143078 shared_ptr<DependencyItem> GetDependency(const string &name) const {
143079 auto it = objects.find(name);
143080 if (it == objects.end()) {
143081 return nullptr;
143082 }
143083 return it->second;
143084 }
143085 void ScanDependencies(const dependency_scan_t &callback) {
143086 for (auto &kv : objects) {
143087 callback(kv.first, kv.second);
143088 }
143089 }
143090
143091private:
143093 case_insensitive_map_t<shared_ptr<DependencyItem>> objects;
143094};
143095
143096}
143097
143098
143099
143100
143101
143102
143103
143104
143105
143106
143107
143108
143109
143110
143111
143112
143113
143114
143115
143116
143117
143118
143119
143120
143121
143122
143123
143124
143125
143126
143127
143128
143129
143130
143131
143132
143133
143134
143135
143136
143137
143138
143139
143140
143141
143142namespace duckdb {
143143
143144
143145
143146
143147enum class ExpressionType :
uint8_t {
143148 INVALID = 0,
143149
143150
143151 OPERATOR_CAST = 12,
143152
143153 OPERATOR_NOT = 13,
143154
143155 OPERATOR_IS_NULL = 14,
143156
143157 OPERATOR_IS_NOT_NULL = 15,
143158
143159 OPERATOR_UNPACK = 16,
143160
143161
143162
143163
143164
143165 COMPARE_EQUAL = 25,
143166
143167 COMPARE_BOUNDARY_START = COMPARE_EQUAL,
143168
143169 COMPARE_NOTEQUAL = 26,
143170
143171 COMPARE_LESSTHAN = 27,
143172
143173 COMPARE_GREATERTHAN = 28,
143174
143175 COMPARE_LESSTHANOREQUALTO = 29,
143176
143177 COMPARE_GREATERTHANOREQUALTO = 30,
143178
143179 COMPARE_IN = 35,
143180
143181 COMPARE_NOT_IN = 36,
143182
143183 COMPARE_DISTINCT_FROM = 37,
143184
143185 COMPARE_BETWEEN = 38,
143186 COMPARE_NOT_BETWEEN = 39,
143187
143188 COMPARE_NOT_DISTINCT_FROM = 40,
143189
143190 COMPARE_BOUNDARY_END = COMPARE_NOT_DISTINCT_FROM,
143191
143192
143193
143194
143195 CONJUNCTION_AND = 50,
143196 CONJUNCTION_OR = 51,
143197
143198
143199
143200
143201 VALUE_CONSTANT = 75,
143202 VALUE_PARAMETER = 76,
143203 VALUE_TUPLE = 77,
143204 VALUE_TUPLE_ADDRESS = 78,
143205 VALUE_NULL = 79,
143206 VALUE_VECTOR = 80,
143207 VALUE_SCALAR = 81,
143208 VALUE_DEFAULT = 82,
143209
143210
143211
143212
143213 AGGREGATE = 100,
143214 BOUND_AGGREGATE = 101,
143215 GROUPING_FUNCTION = 102,
143216
143217
143218
143219
143220 WINDOW_AGGREGATE = 110,
143221
143222 WINDOW_RANK = 120,
143223 WINDOW_RANK_DENSE = 121,
143224 WINDOW_NTILE = 122,
143225 WINDOW_PERCENT_RANK = 123,
143226 WINDOW_CUME_DIST = 124,
143227 WINDOW_ROW_NUMBER = 125,
143228
143229 WINDOW_FIRST_VALUE = 130,
143230 WINDOW_LAST_VALUE = 131,
143231 WINDOW_LEAD = 132,
143232 WINDOW_LAG = 133,
143233 WINDOW_NTH_VALUE = 134,
143234 WINDOW_FILL = 135,
143235
143236
143237
143238
143239 FUNCTION = 140,
143240 BOUND_FUNCTION = 141,
143241
143242
143243
143244
143245 CASE_EXPR = 150,
143246 OPERATOR_NULLIF = 151,
143247 OPERATOR_COALESCE = 152,
143248 ARRAY_EXTRACT = 153,
143249 ARRAY_SLICE = 154,
143250 STRUCT_EXTRACT = 155,
143251 ARRAY_CONSTRUCTOR = 156,
143252 ARROW = 157,
143253 OPERATOR_TRY = 158,
143254
143255
143256
143257
143258 SUBQUERY = 175,
143259
143260
143261
143262
143263 STAR = 200,
143264 TABLE_STAR = 201,
143265 PLACEHOLDER = 202,
143266 COLUMN_REF = 203,
143267 FUNCTION_REF = 204,
143268 TABLE_REF = 205,
143269 LAMBDA_REF = 206,
143271
143272
143273
143274
143275 CAST = 225,
143276 BOUND_REF = 227,
143277 BOUND_COLUMN_REF = 228,
143278 BOUND_UNNEST = 229,
143279 COLLATE = 230,
143280 LAMBDA = 231,
143281 POSITIONAL_REFERENCE = 232,
143282 BOUND_LAMBDA_REF = 233,
143283 BOUND_EXPANDED = 234
143284};
143285
143286
143287
143288
143289enum class ExpressionClass :
uint8_t {
143290 INVALID = 0,
143291
143292
143293
143294 AGGREGATE = 1,
143295 CASE = 2,
143296 CAST = 3,
143297 COLUMN_REF = 4,
143298 COMPARISON = 5,
143299 CONJUNCTION = 6,
143300 CONSTANT = 7,
143301 DEFAULT = 8,
143302 FUNCTION = 9,
143303 OPERATOR = 10,
143304 STAR = 11,
143305 SUBQUERY = 13,
143306 WINDOW = 14,
143307 PARAMETER = 15,
143308 COLLATE = 16,
143309 LAMBDA = 17,
143310 POSITIONAL_REFERENCE = 18,
143311 BETWEEN = 19,
143312 LAMBDA_REF = 20,
143314
143315
143316
143317 BOUND_AGGREGATE = 25,
143318 BOUND_CASE = 26,
143319 BOUND_CAST = 27,
143320 BOUND_COLUMN_REF = 28,
143321 BOUND_COMPARISON = 29,
143322 BOUND_CONJUNCTION = 30,
143323 BOUND_CONSTANT = 31,
143324 BOUND_DEFAULT = 32,
143325 BOUND_FUNCTION = 33,
143326 BOUND_OPERATOR = 34,
143327 BOUND_PARAMETER = 35,
143328 BOUND_REF = 36,
143329 BOUND_SUBQUERY = 37,
143330 BOUND_WINDOW = 38,
143331 BOUND_BETWEEN = 39,
143332 BOUND_UNNEST = 40,
143333 BOUND_LAMBDA = 41,
143334 BOUND_LAMBDA_REF = 42,
143335
143336
143337
143338 BOUND_EXPRESSION = 50,
143339 BOUND_EXPANDED = 51
143340};
143341
143342DUCKDB_API string ExpressionTypeToString(ExpressionType type);
143343string ExpressionTypeToOperator(ExpressionType type);
143344
143345
143346ExpressionType OperatorToExpressionType(const string &op);
143351
143352DUCKDB_API string ExpressionClassToString(ExpressionClass type);
143353
143354}
143355
143356
143357
143358
143359namespace duckdb {
143360
143363class BaseExpression {
143364public:
143366 BaseExpression(ExpressionType type, ExpressionClass expression_class)
143367 : type(type), expression_class(expression_class) {
143368 }
143369 virtual ~BaseExpression() {
143370 }
143371
143373 ExpressionClass GetExpressionClass() const {
143374 return expression_class;
143375 }
143376
143378 ExpressionType GetExpressionType() const {
143379 return type;
143380 }
143381
143384 void SetExpressionTypeUnsafe(ExpressionType new_type) {
143385 type = new_type;
143386 }
143387
143389 optional_idx GetQueryLocation() const {
143390 return query_location;
143391 }
143392
143394 void SetQueryLocation(optional_idx location) {
143395 query_location = location;
143396 }
143397
143399 bool HasAlias() const {
143400 return !alias.empty();
143401 }
143402
143404 const string &GetAlias() const {
143405 return alias;
143406 }
143407
143409 void SetAlias(const string &alias_p) {
143410 alias = alias_p;
143411 }
143412
143414 void SetAlias(string &&alias_p) {
143415 alias = std::move(alias_p);
143416 }
143417
143419 void ClearAlias() {
143420 alias.clear();
143421 }
143422
143423
143424
143425
143427 ExpressionType type;
143428
143430 ExpressionClass expression_class;
143431
143433 string alias;
143434
143436 optional_idx query_location;
143437
143438public:
143440
143447 virtual bool IsAggregate() const = 0;
143449 virtual bool IsWindow() const = 0;
143451 virtual bool HasSubquery() const = 0;
143453 virtual bool IsScalar() const = 0;
143455 virtual bool HasParameter() const = 0;
143456
143458 virtual string GetName() const;
143460 virtual string ToString() const = 0;
143462 void Print() const;
143463
143466 virtual hash_t Hash()
const = 0;
143468 virtual bool Equals(const BaseExpression &other) const;
143469
143470 static bool Equals(const BaseExpression &left, const BaseExpression &right) {
143471 return left.Equals(right);
143472 }
143473 bool operator==(
const BaseExpression &rhs)
const {
143474 return Equals(rhs);
143475 }
143476
143477 virtual void Verify() const;
143478
143479public:
143480 template <class TARGET>
143481 TARGET &Cast() {
143482 if (expression_class != TARGET::TYPE) {
143483 throw InternalException("Failed to cast expression to type - expression type mismatch");
143484 }
143485 return reinterpret_cast<TARGET &>(*this);
143486 }
143487
143488 template <class TARGET>
143489 const TARGET &Cast() const {
143490 if (expression_class != TARGET::TYPE) {
143491 throw InternalException("Failed to cast expression to type - expression type mismatch");
143492 }
143493 return reinterpret_cast<const TARGET &>(*this);
143494 }
143495};
143496
143497}
143498
143499
143500
143501
143502
143503
143504
143505
143506
143507
143508
143509
143510
143511
143512
143513
143514
143515
143516
143517
143518
143519
143520
143521
143522
143523namespace duckdb {
143524class StandardEntry;
143525
143526struct BindingAlias {
143527 BindingAlias();
143528 explicit BindingAlias(string alias);
143529 BindingAlias(string schema, string alias);
143530 BindingAlias(string catalog, string schema, string alias);
143531 explicit BindingAlias(const StandardEntry &entry);
143532
143533 bool IsSet() const;
143534 const string &GetAlias() const;
143535
143536 const string &GetCatalog() const {
143537 return catalog;
143538 }
143539 const string &GetSchema() const {
143540 return schema;
143541 }
143542
143543 bool Matches(const BindingAlias &other) const;
143544 bool operator==(
const BindingAlias &other)
const;
143545 string ToString() const;
143546
143547private:
143548 string catalog;
143549 string schema;
143550 string alias;
143551};
143552
143553}
143554
143555
143556
143557
143558
143559
143560
143561
143562
143563
143564
143565
143566
143567
143568
143569
143570
143571
143572
143573
143574
143575
143576
143577
143578namespace duckdb {
143579
143583 SIMPLIFIED_TOKEN_IDENTIFIER,
143584 SIMPLIFIED_TOKEN_NUMERIC_CONSTANT,
143585 SIMPLIFIED_TOKEN_STRING_CONSTANT,
143586 SIMPLIFIED_TOKEN_OPERATOR,
143587 SIMPLIFIED_TOKEN_KEYWORD,
143588 SIMPLIFIED_TOKEN_COMMENT,
143589 SIMPLIFIED_TOKEN_ERROR,
143590 SIMPLIFIED_TOKEN_ERROR_EMPHASIS,
143591 SIMPLIFIED_TOKEN_ERROR_SUGGESTION
143592};
143593
143594struct SimplifiedToken {
143597};
143598
143599enum class KeywordCategory :
uint8_t {
143600 KEYWORD_RESERVED,
143601 KEYWORD_UNRESERVED,
143602 KEYWORD_TYPE_FUNC,
143603 KEYWORD_COL_NAME,
143604 KEYWORD_NONE
143605};
143606
143607struct ParserKeyword {
143608 string name;
143609 KeywordCategory category;
143610};
143611
143612}
143613
143614
143615namespace duckdb {
143616
143617class KeywordHelper {
143618public:
143620 static bool IsKeyword(const string &text, KeywordCategory category = KeywordCategory::KEYWORD_NONE);
143621
143622 static KeywordCategory KeywordCategoryType(const string &text);
143623
143624 static string EscapeQuotes(const string &text, char quote = '"');
143625
143627 static bool RequiresQuotes(const string &text, bool allow_caps = true,
143628 KeywordCategory category = KeywordCategory::KEYWORD_NONE);
143629
143631 static string WriteQuoted(const string &text, char quote = '\'');
143632
143634 static string WriteOptionallyQuoted(const string &text, char quote = '"', bool allow_caps = true,
143635 KeywordCategory category = KeywordCategory::KEYWORD_NONE);
143636};
143637
143638}
143639
143640
143641namespace duckdb {
143642
143643struct QualifiedName {
143644 string catalog;
143645 string schema;
143646 string name;
143647
143650 static QualifiedName Parse(const string &input);
143651 static vector<string> ParseComponents(const string &input);
143652 string ToString() const;
143653};
143654
143655struct QualifiedColumnName {
143656 QualifiedColumnName();
143657 QualifiedColumnName(string column_p);
143658 QualifiedColumnName(string table_p, string column_p);
143659 QualifiedColumnName(const BindingAlias &alias, string column_p);
143660
143661 string catalog;
143662 string schema;
143663 string table;
143664 string column;
143665
143666 static QualifiedColumnName Parse(string &input);
143667
143668 string ToString() const;
143669
143670 void Serialize(Serializer &serializer) const;
143671 static QualifiedColumnName Deserialize(Deserializer &deserializer);
143672
143673 bool IsQualified() const;
143674
143675 bool operator==(
const QualifiedColumnName &rhs)
const;
143676};
143677
143678}
143679
143680
143681namespace duckdb {
143682class Deserializer;
143683class Serializer;
143684
143687
143694class ParsedExpression : public BaseExpression {
143695public:
143697 ParsedExpression(ExpressionType type, ExpressionClass expression_class) : BaseExpression(type, expression_class) {
143698 }
143699
143700public:
143701 bool IsAggregate() const override;
143702 bool IsWindow() const override;
143703 bool HasSubquery() const override;
143704 bool IsScalar() const override;
143705 bool HasParameter() const override;
143706
143707 bool Equals(const BaseExpression &other) const override;
143708 hash_t Hash()
const override;
143709
143711 virtual unique_ptr<ParsedExpression> Copy() const = 0;
143712
143713 virtual void Serialize(Serializer &serializer) const;
143714 static unique_ptr<ParsedExpression> Deserialize(Deserializer &deserializer);
143715
143716 static bool Equals(const unique_ptr<ParsedExpression> &left, const unique_ptr<ParsedExpression> &right);
143717 static bool ListEquals(const vector<unique_ptr<ParsedExpression>> &left,
143718 const vector<unique_ptr<ParsedExpression>> &right);
143719
143720protected:
143723 void CopyProperties(const ParsedExpression &other) {
143724 type = other.type;
143725 expression_class = other.expression_class;
143726 alias = other.alias;
143727 query_location = other.query_location;
143728 }
143729};
143730
143731}
143732
143733
143734
143735
143736
143737
143738
143739
143740
143741
143742
143743
143744
143745
143746
143747namespace duckdb {
143748
143749class StorageManager;
143750
143751enum class CompressionType :
uint8_t {
143752 COMPRESSION_AUTO = 0,
143753 COMPRESSION_UNCOMPRESSED = 1,
143754 COMPRESSION_CONSTANT = 2,
143755 COMPRESSION_RLE = 3,
143756 COMPRESSION_DICTIONARY = 4,
143757 COMPRESSION_PFOR_DELTA = 5,
143758 COMPRESSION_BITPACKING = 6,
143759 COMPRESSION_FSST = 7,
143760 COMPRESSION_CHIMP = 8,
143761 COMPRESSION_PATAS = 9,
143762 COMPRESSION_ALP = 10,
143763 COMPRESSION_ALPRD = 11,
143764 COMPRESSION_ZSTD = 12,
143765 COMPRESSION_ROARING = 13,
143766 COMPRESSION_EMPTY = 14,
143767 COMPRESSION_DICT_FSST = 15,
143768 COMPRESSION_COUNT
143769};
143770
143771struct CompressionAvailabilityResult {
143772private:
143773 enum class UnavailableReason :
uint8_t {
143774 AVAILABLE,
143776 NOT_AVAILABLE_YET,
143778 DEPRECATED
143779 };
143780
143781public:
143782 CompressionAvailabilityResult() = default;
143783 static CompressionAvailabilityResult Deprecated() {
143784 return CompressionAvailabilityResult(UnavailableReason::DEPRECATED);
143785 }
143786 static CompressionAvailabilityResult NotAvailableYet() {
143787 return CompressionAvailabilityResult(UnavailableReason::NOT_AVAILABLE_YET);
143788 }
143789
143790public:
143791 bool IsAvailable() const {
143792 return reason == UnavailableReason::AVAILABLE;
143793 }
143794 bool IsDeprecated() {
143795 D_ASSERT(!IsAvailable());
143796 return reason == UnavailableReason::DEPRECATED;
143797 }
143798 bool IsNotAvailableYet() {
143799 D_ASSERT(!IsAvailable());
143800 return reason == UnavailableReason::NOT_AVAILABLE_YET;
143801 }
143802
143803private:
143804 explicit CompressionAvailabilityResult(UnavailableReason reason) : reason(reason) {
143805 }
143806
143807public:
143808 UnavailableReason reason = UnavailableReason::AVAILABLE;
143809};
143810
143812 optional_ptr<StorageManager> storage_manager = nullptr);
143813vector<string> ListCompressionTypes(void);
143814string CompressionTypeToString(CompressionType type);
143815
143816}
143817
143818
143819
143820
143821
143822
143823
143824
143825
143826
143827
143828
143829
143830namespace duckdb {
143831
143832enum class TableColumnType :
uint8_t { STANDARD = 0, GENERATED = 1 };
143833
143834}
143835
143836
143837namespace duckdb {
143838
143839struct RenameColumnInfo;
143840struct RenameTableInfo;
143841
143842class ColumnDefinition;
143843
143845class ColumnDefinition {
143846public:
143847 DUCKDB_API ColumnDefinition(string name, LogicalType type);
143848 DUCKDB_API ColumnDefinition(string name, LogicalType type, unique_ptr<ParsedExpression> expression,
143849 TableColumnType category);
143850
143851public:
143853 const ParsedExpression &DefaultValue() const;
143854 bool HasDefaultValue() const;
143855 void SetDefaultValue(unique_ptr<ParsedExpression> default_value);
143856
143858 DUCKDB_API const LogicalType &Type() const;
143859 LogicalType &TypeMutable();
143860 void SetType(const LogicalType &type);
143861
143863 DUCKDB_API const string &Name() const;
143864 void SetName(const string &name);
143865
143867 DUCKDB_API const Value &Comment() const;
143868 void SetComment(const Value &comment);
143869
143871 const duckdb::CompressionType &CompressionType() const;
143872 void SetCompressionType(duckdb::CompressionType compression_type);
143873
143876 void SetStorageOid(storage_t storage_oid);
143877
143878 LogicalIndex Logical() const;
143879 PhysicalIndex Physical() const;
143880
143883 void SetOid(column_t oid);
143884
143886 const TableColumnType &Category() const;
143888 bool Generated() const;
143889 DUCKDB_API ColumnDefinition Copy() const;
143890
143891 DUCKDB_API void Serialize(Serializer &serializer) const;
143892 DUCKDB_API static ColumnDefinition Deserialize(Deserializer &deserializer);
143893
143894
143895
143896
143897
143898 ParsedExpression &GeneratedExpressionMutable();
143899 const ParsedExpression &GeneratedExpression() const;
143900 void SetGeneratedExpression(unique_ptr<ParsedExpression> expression);
143901 void ChangeGeneratedExpressionType(const LogicalType &type);
143902 void GetListOfDependencies(vector<string> &dependencies) const;
143903
143904 string GetName() const;
143905
143906 LogicalType GetType() const;
143907
143908private:
143910 string name;
143912 LogicalType type;
143914 duckdb::CompressionType compression_type = duckdb::CompressionType::COMPRESSION_AUTO;
143916 storage_t storage_oid = DConstants::INVALID_INDEX;
143918 idx_t oid = DConstants::INVALID_INDEX;
143920 TableColumnType category = TableColumnType::STANDARD;
143923 unique_ptr<ParsedExpression> expression;
143925 Value comment;
143927 unordered_map<string, string> tags;
143928};
143929
143930}
143931
143932
143933
143934namespace duckdb {
143935class CatalogEntry;
143936class Catalog;
143937class ClientContext;
143938class Expression;
143939class ExpressionExecutor;
143940class Transaction;
143941
143942class AggregateFunction;
143943class AggregateFunctionSet;
143944class CopyFunction;
143945class PragmaFunction;
143946class PragmaFunctionSet;
143947class ScalarFunctionSet;
143948class ScalarFunction;
143949class TableFunctionSet;
143950class TableFunction;
143951class SimpleFunction;
143952
143953struct PragmaInfo;
143954
143963
143969 PROPAGATE_COLLATIONS = 0,
143970 PUSH_COMBINABLE_COLLATIONS = 1,
143971 IGNORE_COLLATIONS = 2
143972};
143973
143974struct FunctionData {
143975 DUCKDB_API virtual ~FunctionData();
143976
143977 DUCKDB_API virtual unique_ptr<FunctionData> Copy() const = 0;
143978 DUCKDB_API virtual bool Equals(const FunctionData &other) const = 0;
143979 DUCKDB_API static bool Equals(const FunctionData *left, const FunctionData *right);
143980 DUCKDB_API virtual bool SupportStatementCache() const;
143981
143982 template <class TARGET>
143983 TARGET &Cast() {
143984 DynamicCastCheck<TARGET>(this);
143985 return reinterpret_cast<TARGET &>(*this);
143986 }
143987 template <class TARGET>
143988 const TARGET &Cast() const {
143989 DynamicCastCheck<TARGET>(this);
143990 return reinterpret_cast<const TARGET &>(*this);
143991 }
143992
143993 template <class TARGET>
143994 TARGET &CastNoConst() const {
143995 return const_cast<TARGET &>(Cast<TARGET>());
143996 }
143997};
143998
143999struct TableFunctionData : public FunctionData {
144000
144001 vector<idx_t> column_ids;
144002
144003 DUCKDB_API ~TableFunctionData() override;
144004
144005 DUCKDB_API unique_ptr<FunctionData> Copy() const override;
144006 DUCKDB_API bool Equals(const FunctionData &other) const override;
144007};
144008
144009struct FunctionParameters {
144010 vector<Value> values;
144011 named_parameter_map_t named_parameters;
144012};
144013
144015class Function {
144016public:
144017 DUCKDB_API explicit Function(string name);
144018 DUCKDB_API virtual ~Function();
144019
144021 string name;
144023 string extra_info;
144024
144025
144026 string catalog_name;
144027
144028
144029 string schema_name;
144030
144031public:
144033 DUCKDB_API static string CallToString(const string &catalog_name, const string &schema_name, const string &name,
144034 const vector<LogicalType> &arguments,
144035 const LogicalType &varargs = LogicalType::INVALID);
144037 DUCKDB_API static string CallToString(const string &catalog_name, const string &schema_name, const string &name,
144038 const vector<LogicalType> &arguments, const LogicalType &varargs,
144039 const LogicalType &return_type);
144041 DUCKDB_API static string CallToString(const string &catalog_name, const string &schema_name, const string &name,
144042 const vector<LogicalType> &arguments,
144043 const named_parameter_type_map_t &named_parameters);
144044
144046 DUCKDB_API static void EraseArgument(SimpleFunction &bound_function, vector<unique_ptr<Expression>> &arguments,
144047 idx_t argument_index);
144048};
144049
144050class SimpleFunction : public Function {
144051public:
144052 DUCKDB_API SimpleFunction(string name, vector<LogicalType> arguments,
144053 LogicalType varargs = LogicalType(LogicalTypeId::INVALID));
144054 DUCKDB_API ~SimpleFunction() override;
144055
144057 vector<LogicalType> arguments;
144060 vector<LogicalType> original_arguments;
144063 LogicalType varargs;
144064
144065public:
144066 DUCKDB_API virtual string ToString() const;
144067
144068 DUCKDB_API bool HasVarArgs() const;
144069};
144070
144071class SimpleNamedParameterFunction : public SimpleFunction {
144072public:
144073 DUCKDB_API SimpleNamedParameterFunction(string name, vector<LogicalType> arguments,
144074 LogicalType varargs = LogicalType(LogicalTypeId::INVALID));
144075 DUCKDB_API ~SimpleNamedParameterFunction() override;
144076
144078 named_parameter_type_map_t named_parameters;
144079
144080public:
144081 DUCKDB_API string ToString() const override;
144082 DUCKDB_API bool HasNamedParameters() const;
144083};
144084
144085class BaseScalarFunction : public SimpleFunction {
144086public:
144087 DUCKDB_API BaseScalarFunction(string name, vector<LogicalType> arguments, LogicalType return_type,
144088 FunctionStability stability,
144089 LogicalType varargs = LogicalType(LogicalTypeId::INVALID),
144090 FunctionNullHandling null_handling = FunctionNullHandling::DEFAULT_NULL_HANDLING,
144091 FunctionErrors errors = FunctionErrors::CANNOT_ERROR);
144092 DUCKDB_API ~BaseScalarFunction() override;
144093
144094public:
144095 void SetReturnType(LogicalType return_type_p) {
144096 return_type = std::move(return_type_p);
144097 }
144098 const LogicalType &GetReturnType() const {
144099 return return_type;
144100 }
144101 LogicalType &GetReturnType() {
144102 return return_type;
144103 }
144104
144106 return stability;
144107 }
144108 void SetStability(FunctionStability stability_p) {
144109 stability = stability_p;
144110 }
144111
144113 return null_handling;
144114 }
144115 void SetNullHandling(FunctionNullHandling null_handling_p) {
144116 null_handling = null_handling_p;
144117 }
144118
144120 return errors;
144121 }
144122 void SetErrorMode(FunctionErrors errors_p) {
144123 errors = errors_p;
144124 }
144125
144127 void SetFallible() {
144128 errors = FunctionErrors::CAN_THROW_RUNTIME_ERROR;
144129 }
144131 void SetVolatile() {
144132 stability = FunctionStability::VOLATILE;
144133 }
144134
144135 void SetCollationHandling(FunctionCollationHandling collation_handling_p) {
144136 collation_handling = collation_handling_p;
144137 }
144139 return collation_handling;
144140 }
144141
144142public:
144144 LogicalType return_type;
144153
144154 static BaseScalarFunction SetReturnsError(BaseScalarFunction &function) {
144155 function.errors = FunctionErrors::CAN_THROW_RUNTIME_ERROR;
144156 return function;
144157 }
144158
144159public:
144160 DUCKDB_API
hash_t Hash()
const;
144161
144162 DUCKDB_API string ToString() const override;
144163};
144164
144165}
144166
144167
144168namespace duckdb {
144169
144170class Expression;
144171class BoundFunctionExpression;
144172class ExpressionExecutor;
144173struct ExpressionExecutorState;
144174struct FunctionLocalState;
144175
144176struct ExpressionState {
144177 ExpressionState(const Expression &expr, ExpressionExecutorState &root);
144178 virtual ~ExpressionState() {
144179 }
144180
144181 const Expression &expr;
144182 ExpressionExecutorState &root;
144183 vector<unique_ptr<ExpressionState>> child_states;
144184 vector<LogicalType> types;
144185 DataChunk intermediate_chunk;
144186 vector<bool> initialize;
144187
144188public:
144189 void AddChild(Expression &child_expr);
144190 void Finalize();
144191 Allocator &GetAllocator();
144192 bool HasContext();
144193 DUCKDB_API ClientContext &GetContext();
144194
144195 void Verify(ExpressionExecutorState &root);
144196
144198 virtual void ResetDictionaryStates();
144199
144200public:
144201 template <class TARGET>
144202 TARGET &Cast() {
144203 DynamicCastCheck<TARGET>(this);
144204 return reinterpret_cast<TARGET &>(*this);
144205 }
144206 template <class TARGET>
144207 const TARGET &Cast() const {
144208 DynamicCastCheck<TARGET>(this);
144209 return reinterpret_cast<const TARGET &>(*this);
144210 }
144211};
144212
144213struct ExecuteFunctionState : public ExpressionState {
144214public:
144215 ExecuteFunctionState(const Expression &expr, ExpressionExecutorState &root);
144216 ~ExecuteFunctionState() override;
144217
144218public:
144219 static optional_ptr<FunctionLocalState> GetFunctionState(ExpressionState &state) {
144220 return state.Cast<ExecuteFunctionState>().local_state.get();
144221 }
144222
144223 bool TryExecuteDictionaryExpression(const BoundFunctionExpression &expr, DataChunk &args, ExpressionState &state,
144224 Vector &result);
144225
144226 void ResetDictionaryStates() override;
144227
144228public:
144229 unique_ptr<FunctionLocalState> local_state;
144230
144231private:
144235 optional_idx input_col_idx;
144237 buffer_ptr<VectorChildBuffer> output_dictionary;
144239 string current_input_dictionary_id;
144240};
144241
144242struct ExpressionExecutorState {
144243 ExpressionExecutorState();
144244
144245 unique_ptr<ExpressionState> root_state;
144246 ExpressionExecutor *executor = nullptr;
144247
144248 void Verify();
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
144279
144280
144281
144282
144283
144284
144285
144286
144287
144288
144289
144290
144291
144292namespace duckdb {
144293
144295class Hugeint {
144296public:
144297 constexpr static const char *HUGEINT_MINIMUM_STRING = "-170141183460469231731687303715884105728";
144298
144300 static string ToString(hugeint_t input);
144301
144302 template <class T>
144303 DUCKDB_API static bool TryCast(hugeint_t input, T &result);
144304
144305 template <class T>
144306 static T Cast(hugeint_t input) {
144307 T result = 0;
144308 TryCast(input, result);
144309 return result;
144310 }
144311
144312 template <class T>
144313 static bool TryConvert(T value, hugeint_t &result);
144314
144315 template <class T>
144316 static hugeint_t Convert(T value) {
144317 hugeint_t result;
144318 if (!TryConvert(value, result)) {
144319 throw OutOfRangeException(double(value), GetTypeId<T>(), GetTypeId<hugeint_t>());
144320 }
144321 return result;
144322 }
144323
144324 static bool TryNegate(hugeint_t input, hugeint_t &result);
144325
144326 template <bool CHECK_OVERFLOW = true>
144327 inline static void NegateInPlace(hugeint_t &input) {
144328 if (!TryNegate(input, input)) {
144329 throw OutOfRangeException("Negation of HUGEINT is out of range!");
144330 }
144331 }
144332
144333 template <bool CHECK_OVERFLOW = true>
144334 inline static hugeint_t Negate(hugeint_t input) {
144335 NegateInPlace<CHECK_OVERFLOW>(input);
144336 return input;
144337 }
144338
144339 static bool TryMultiply(hugeint_t lhs, hugeint_t rhs, hugeint_t &result);
144340
144341 template <bool CHECK_OVERFLOW = true>
144342 inline static hugeint_t Multiply(hugeint_t lhs, hugeint_t rhs) {
144343 hugeint_t result;
144344 if (!TryMultiply(lhs, rhs, result)) {
144345 throw OutOfRangeException("Overflow in HUGEINT multiplication: %s * %s", lhs.ToString(), rhs.ToString());
144346 }
144347 return result;
144348 }
144349
144350 static bool TryDivMod(hugeint_t lhs, hugeint_t rhs, hugeint_t &result, hugeint_t &remainder);
144351
144352 template <bool CHECK_OVERFLOW = true>
144353 inline static hugeint_t Divide(hugeint_t lhs, hugeint_t rhs) {
144354
144355 if (rhs == 0) {
144356 throw OutOfRangeException("Division of HUGEINT by zero: %s / %s", lhs.ToString(), rhs.ToString());
144357 }
144358
144359
144360 if (lhs == NumericLimits<hugeint_t>::Minimum() && rhs == -1) {
144361 throw OutOfRangeException("Overflow in HUGEINT division: %s / %s", lhs.ToString(), rhs.ToString());
144362 }
144363 return Divide<false>(lhs, rhs);
144364 }
144365
144366 template <bool CHECK_OVERFLOW = true>
144367 inline static hugeint_t Modulo(hugeint_t lhs, hugeint_t rhs) {
144368
144369 if (rhs == 0) {
144370 throw OutOfRangeException("Modulo of HUGEINT by zero: %s %% %s", lhs.ToString(), rhs.ToString());
144371 }
144372
144373
144374 if (lhs == NumericLimits<hugeint_t>::Minimum() && rhs == -1) {
144375 throw OutOfRangeException("Overflow in HUGEINT modulo: %s %% %s", lhs.ToString(), rhs.ToString());
144376 }
144377 return Modulo<false>(lhs, rhs);
144378 }
144379
144380 static bool TryAddInPlace(hugeint_t &lhs, hugeint_t rhs);
144381
144382 template <bool CHECK_OVERFLOW = true>
144383 inline static hugeint_t Add(hugeint_t lhs, hugeint_t rhs) {
144384 if (!TryAddInPlace(lhs, rhs)) {
144385 throw OutOfRangeException("Overflow in HUGEINT addition: %s + %s", lhs.ToString(), rhs.ToString());
144386 }
144387 return lhs;
144388 }
144389
144390 static bool TrySubtractInPlace(hugeint_t &lhs, hugeint_t rhs);
144391
144392 template <bool CHECK_OVERFLOW = true>
144393 inline static hugeint_t Subtract(hugeint_t lhs, hugeint_t rhs) {
144394 if (!TrySubtractInPlace(lhs, rhs)) {
144395 throw OutOfRangeException("Underflow in HUGEINT subtraction: %s - %s", lhs.ToString(), rhs.ToString());
144396 }
144397 return lhs;
144398 }
144399
144400
144401 static hugeint_t DivMod(hugeint_t lhs, hugeint_t rhs, hugeint_t &remainder);
144402
144403 static hugeint_t DivModPositive(hugeint_t lhs, uint64_t rhs, uint64_t &remainder);
144404
144405 static int Sign(hugeint_t n);
144406 static hugeint_t Abs(hugeint_t n);
144407
144408 static bool Equals(const hugeint_t &lhs, const hugeint_t &rhs) {
144409 bool lower_equals = lhs.lower == rhs.lower;
144410 bool upper_equals = lhs.upper == rhs.upper;
144411 return lower_equals && upper_equals;
144412 }
144413
144414 static bool NotEquals(const hugeint_t &lhs, const hugeint_t &rhs) {
144415 return !Equals(lhs, rhs);
144416 }
144417
144418 static bool GreaterThan(const hugeint_t &lhs, const hugeint_t &rhs) {
144419 bool upper_bigger = lhs.upper > rhs.upper;
144420 bool upper_equal = lhs.upper == rhs.upper;
144421 bool lower_bigger = lhs.lower > rhs.lower;
144422 return upper_bigger || (upper_equal && lower_bigger);
144423 }
144424
144425 static bool GreaterThanEquals(const hugeint_t &lhs, const hugeint_t &rhs) {
144426 bool upper_bigger = lhs.upper > rhs.upper;
144427 bool upper_equal = lhs.upper == rhs.upper;
144428 bool lower_bigger_equals = lhs.lower >= rhs.lower;
144429 return upper_bigger || (upper_equal && lower_bigger_equals);
144430 }
144431
144432 static bool LessThan(const hugeint_t &lhs, const hugeint_t &rhs) {
144433 bool upper_smaller = lhs.upper < rhs.upper;
144434 bool upper_equal = lhs.upper == rhs.upper;
144435 bool lower_smaller = lhs.lower < rhs.lower;
144436 return upper_smaller || (upper_equal && lower_smaller);
144437 }
144438
144439 static bool LessThanEquals(const hugeint_t &lhs, const hugeint_t &rhs) {
144440 bool upper_smaller = lhs.upper < rhs.upper;
144441 bool upper_equal = lhs.upper == rhs.upper;
144442 bool lower_smaller_equals = lhs.lower <= rhs.lower;
144443 return upper_smaller || (upper_equal && lower_smaller_equals);
144444 }
144445
144446 static constexpr uint8_t CACHED_POWERS_OF_TEN = 39;
144447 static const hugeint_t POWERS_OF_TEN[CACHED_POWERS_OF_TEN];
144448};
144449
144450template <>
144451DUCKDB_API bool Hugeint::TryCast(hugeint_t input, int8_t &result);
144452template <>
144453DUCKDB_API bool Hugeint::TryCast(hugeint_t input, int16_t &result);
144454template <>
144455DUCKDB_API bool Hugeint::TryCast(hugeint_t input, int32_t &result);
144456template <>
144457DUCKDB_API bool Hugeint::TryCast(hugeint_t input, int64_t &result);
144458template <>
144459DUCKDB_API bool Hugeint::TryCast(hugeint_t input, uint8_t &result);
144460template <>
144461DUCKDB_API bool Hugeint::TryCast(hugeint_t input, uint16_t &result);
144462template <>
144463DUCKDB_API bool Hugeint::TryCast(hugeint_t input, uint32_t &result);
144464template <>
144465DUCKDB_API bool Hugeint::TryCast(hugeint_t input, uint64_t &result);
144466template <>
144467DUCKDB_API bool Hugeint::TryCast(hugeint_t input, hugeint_t &result);
144468template <>
144469DUCKDB_API bool Hugeint::TryCast(hugeint_t input, uhugeint_t &result);
144470template <>
144471DUCKDB_API bool Hugeint::TryCast(hugeint_t input, float &result);
144472template <>
144473DUCKDB_API bool Hugeint::TryCast(hugeint_t input, double &result);
144474template <>
144475DUCKDB_API bool Hugeint::TryCast(hugeint_t input, long double &result);
144476
144477template <>
144478bool Hugeint::TryConvert(int8_t value, hugeint_t &result);
144479template <>
144480bool Hugeint::TryConvert(int16_t value, hugeint_t &result);
144481template <>
144482bool Hugeint::TryConvert(int32_t value, hugeint_t &result);
144483template <>
144484bool Hugeint::TryConvert(int64_t value, hugeint_t &result);
144485template <>
144486bool Hugeint::TryConvert(uint8_t value, hugeint_t &result);
144487template <>
144488bool Hugeint::TryConvert(uint16_t value, hugeint_t &result);
144489template <>
144490bool Hugeint::TryConvert(uint32_t value, hugeint_t &result);
144491template <>
144492bool Hugeint::TryConvert(uint64_t value, hugeint_t &result);
144493template <>
144494bool Hugeint::TryConvert(float value, hugeint_t &result);
144495template <>
144496bool Hugeint::TryConvert(double value, hugeint_t &result);
144497template <>
144498bool Hugeint::TryConvert(long double value, hugeint_t &result);
144499template <>
144500bool Hugeint::TryConvert(const char *value, hugeint_t &result);
144501
144502}
144503
144504
144505
144506
144507#include <cstring>
144508
144509namespace duckdb {
144510
144511
144512
144513
144514struct Equals {
144515 template <class T>
144516 static inline bool Operation(const T &left, const T &right) {
144517 return left == right;
144518 }
144519};
144520struct NotEquals {
144521 template <class T>
144522 static inline bool Operation(const T &left, const T &right) {
144523 return !Equals::Operation(left, right);
144524 }
144525};
144526
144527struct GreaterThan {
144528 template <class T>
144529 static inline bool Operation(const T &left, const T &right) {
144530 return left > right;
144531 }
144532};
144533
144534struct GreaterThanEquals {
144535 template <class T>
144536 static inline bool Operation(const T &left, const T &right) {
144537 return !GreaterThan::Operation(right, left);
144538 }
144539};
144540
144541struct LessThan {
144542 template <class T>
144543 static inline bool Operation(const T &left, const T &right) {
144544 return GreaterThan::Operation(right, left);
144545 }
144546};
144547
144548struct LessThanEquals {
144549 template <class T>
144550 static inline bool Operation(const T &left, const T &right) {
144551 return !GreaterThan::Operation(left, right);
144552 }
144553};
144554
144555template <>
144556DUCKDB_API bool Equals::Operation(const float &left, const float &right);
144557template <>
144558DUCKDB_API bool Equals::Operation(const double &left, const double &right);
144559
144560template <>
144561DUCKDB_API bool GreaterThan::Operation(const float &left, const float &right);
144562template <>
144563DUCKDB_API bool GreaterThan::Operation(const double &left, const double &right);
144564
144565template <>
144566DUCKDB_API bool GreaterThanEquals::Operation(const float &left, const float &right);
144567template <>
144568DUCKDB_API bool GreaterThanEquals::Operation(const double &left, const double &right);
144569
144570
144571
144572
144573struct DistinctFrom {
144574 template <class T>
144575 static inline bool Operation(const T &left, const T &right, bool left_null, bool right_null) {
144576 if (left_null || right_null) {
144577 return left_null != right_null;
144578 }
144579 return NotEquals::Operation(left, right);
144580 }
144581};
144582
144583struct NotDistinctFrom {
144584 template <class T>
144585 static inline bool Operation(const T &left, const T &right, bool left_null, bool right_null) {
144586 return !DistinctFrom::Operation(left, right, left_null, right_null);
144587 }
144588};
144589
144590struct DistinctGreaterThan {
144591 template <class T>
144592 static inline bool Operation(const T &left, const T &right, bool left_null, bool right_null) {
144593 if (left_null || right_null) {
144594 return !right_null;
144595 }
144596 return GreaterThan::Operation(left, right);
144597 }
144598};
144599
144600struct DistinctGreaterThanNullsFirst {
144601 template <class T>
144602 static inline bool Operation(const T &left, const T &right, bool left_null, bool right_null) {
144603 return DistinctGreaterThan::Operation(left, right, right_null, left_null);
144604 }
144605};
144606
144607struct DistinctGreaterThanEquals {
144608 template <class T>
144609 static inline bool Operation(const T &left, const T &right, bool left_null, bool right_null) {
144610 return !DistinctGreaterThan::Operation(right, left, right_null, left_null);
144611 }
144612};
144613
144614struct DistinctLessThan {
144615 template <class T>
144616 static inline bool Operation(const T &left, const T &right, bool left_null, bool right_null) {
144617 return DistinctGreaterThan::Operation(right, left, right_null, left_null);
144618 }
144619};
144620
144621struct DistinctLessThanNullsFirst {
144622 template <class T>
144623 static inline bool Operation(const T &left, const T &right, bool left_null, bool right_null) {
144624 return DistinctGreaterThan::Operation(right, left, left_null, right_null);
144625 }
144626};
144627
144628struct DistinctLessThanEquals {
144629 template <class T>
144630 static inline bool Operation(const T &left, const T &right, bool left_null, bool right_null) {
144631 return !DistinctGreaterThan::Operation(left, right, left_null, right_null);
144632 }
144633};
144634
144635
144636
144637
144638template <class OP>
144639struct ComparisonOperationWrapper {
144640 static constexpr const bool COMPARE_NULL = false;
144641
144642 template <class T>
144643 static inline bool Operation(const T &left, const T &right, bool left_null, bool right_null) {
144644 if (right_null || left_null) {
144645 return false;
144646 }
144647 return OP::template Operation<T>(left, right);
144648 }
144649};
144650
144651template <>
144652struct ComparisonOperationWrapper<DistinctFrom> {
144653 static constexpr const bool COMPARE_NULL = true;
144654
144655 template <class T>
144656 static inline bool Operation(const T &left, const T &right, bool left_null, bool right_null) {
144657 return DistinctFrom::template Operation<T>(left, right, left_null, right_null);
144658 }
144659};
144660
144661template <>
144662struct ComparisonOperationWrapper<NotDistinctFrom> {
144663 static constexpr const bool COMPARE_NULL = true;
144664
144665 template <class T>
144666 static inline bool Operation(const T &left, const T &right, bool left_null, bool right_null) {
144667 return NotDistinctFrom::template Operation<T>(left, right, left_null, right_null);
144668 }
144669};
144670
144671
144672
144673
144674template <>
144675inline bool GreaterThan::Operation(const bool &left, const bool &right) {
144676 return !right && left;
144677}
144678
144679
144680
144681template <>
144682inline bool Equals::Operation(const string_t &left, const string_t &right) {
144683 return left == right;
144684}
144685
144686template <>
144687inline bool GreaterThan::Operation(const string_t &left, const string_t &right) {
144688 return left > right;
144689}
144690
144691
144692
144693
144694template <>
144695inline bool Equals::Operation(const interval_t &left, const interval_t &right) {
144696 return Interval::Equals(left, right);
144697}
144698template <>
144699inline bool GreaterThan::Operation(const interval_t &left, const interval_t &right) {
144700 return Interval::GreaterThan(left, right);
144701}
144702
144703}
144704
144705
144706
144707
144708
144709
144710
144711
144712
144713
144714
144715
144716
144717
144718
144719
144720
144721
144722
144723
144724
144725
144726
144727
144728
144729
144730
144731
144732
144733namespace duckdb {
144734
144736 INVALID,
144741};
144742
144743struct ColumnIndex {
144744public:
144747 }
144748 explicit ColumnIndex(idx_t index)
144750 }
144751 explicit ColumnIndex(const string &field)
144753 }
144754
144755 ColumnIndex(idx_t index, vector<ColumnIndex> child_indexes_p)
144757 child_indexes(std::move(child_indexes_p)) {
144758 }
144759 ColumnIndex(const string &field, vector<ColumnIndex> child_indexes_p)
144761 child_indexes(std::move(child_indexes_p)) {
144762 }
144763
144764 inline bool operator==(
const ColumnIndex &rhs)
const {
144765 if (has_index != rhs.has_index) {
144766 return false;
144767 }
144768 if (has_index) {
144769 if (index != rhs.index) {
144770 return false;
144771 }
144772 } else {
144773 if (field != rhs.field) {
144774 return false;
144775 }
144776 }
144777 if (type != rhs.type) {
144778 return false;
144779 }
144781 return false;
144782 }
144783
144784 if (child_indexes.size() != rhs.child_indexes.size()) {
144785 return false;
144786 }
144787 for (idx_t i = 0; i < child_indexes.size(); i++) {
144788 auto &a = child_indexes[i];
144789 auto &b = rhs.child_indexes[i];
144790 if (a != b) {
144791 return false;
144792 }
144793 }
144794 return true;
144795 }
144796 inline bool operator!=(
const ColumnIndex &rhs)
const {
144797 return !(*this == rhs);
144798 }
144799 inline bool operator<(
const ColumnIndex &rhs)
const {
144801 return index < rhs.index;
144802 }
144803
144804public:
144805 bool HasPrimaryIndex() const {
144806 return has_index;
144807 }
144808 idx_t GetPrimaryIndex()
const {
144809 if (!has_index) {
144810 throw InternalException("Attempted to get the primary index (numeric) for an index that consists of a "
144811 "field identifier (string: %s)",
144812 field);
144813 }
144815 }
144816 const string &GetFieldName() const {
144817 if (has_index) {
144818 throw InternalException("Attempted to get the field identifier (string) for an index that consists of a "
144819 "primary index (numeric: %d)",
144820 index);
144821 }
144822 return field;
144823 }
144824 LogicalIndex ToLogical() const {
144825 return LogicalIndex(GetPrimaryIndex());
144826 }
144827 bool HasChildren() const {
144828 return !child_indexes.empty();
144829 }
144830 bool HasType() const {
144831 return type.id() != LogicalTypeId::INVALID;
144832 }
144833 idx_t ChildIndexCount()
const {
144834 return child_indexes.size();
144835 }
144836 const ColumnIndex &GetChildIndex(idx_t idx) const {
144837 return child_indexes[idx];
144838 }
144839 ColumnIndex &GetChildIndex(idx_t idx) {
144840 return child_indexes[idx];
144841 }
144842 const vector<ColumnIndex> &GetChildIndexes() const {
144843 return child_indexes;
144844 }
144845 vector<ColumnIndex> &GetChildIndexesMutable() {
144846 return child_indexes;
144847 }
144848
144849 bool IsPushdownExtract() const {
144850 return index_type == ColumnIndexType::PUSHDOWN_EXTRACT;
144851 }
144852 void SetType(const LogicalType &type_information) {
144853 type = type_information;
144854 }
144855 void SetPushdownExtractType(const LogicalType &type_information,
144856 optional_ptr<const LogicalType> cast_type = nullptr) {
144858 index_type = ColumnIndexType::PUSHDOWN_EXTRACT;
144859 type = type_information;
144860 D_ASSERT(child_indexes.size() == 1);
144861
144862 auto &child = child_indexes[0];
144863 if (child.HasPrimaryIndex()) {
144864 auto &child_types = StructType::GetChildTypes(type);
144865 auto &child_type = child_types[child.GetPrimaryIndex()].second;
144866 if (child.child_indexes.empty()) {
144867 if (cast_type) {
144868 child.SetType(*cast_type);
144869 } else {
144870 child.SetType(child_type);
144871 }
144872 } else {
144873 child.SetPushdownExtractType(child_type, cast_type);
144874 }
144875 } else {
144876 D_ASSERT(type_information.id() == LogicalTypeId::VARIANT);
144877 if (child.child_indexes.empty()) {
144878 if (cast_type) {
144879 child.SetType(*cast_type);
144880 } else {
144882 child.SetType(type_information);
144883 }
144884 } else {
144885 child.SetPushdownExtractType(type_information, cast_type);
144886 }
144887 }
144888 }
144889 const LogicalType &GetScanType() const {
144890 D_ASSERT(HasType());
144891 if (IsPushdownExtract()) {
144892 return child_indexes[0].GetScanType();
144893 }
144894 return GetType();
144895 }
144896 const LogicalType &GetType() const {
144897 D_ASSERT(type.id() != LogicalTypeId::INVALID);
144898 return type;
144899 }
144900 void AddChildIndex(ColumnIndex new_index) {
144901 this->child_indexes.push_back(std::move(new_index));
144902 }
144903 bool IsRowIdColumn() const {
144904 if (!has_index) {
144905 return false;
144906 }
144908 }
144909 bool IsEmptyColumn() const {
144910 if (!has_index) {
144911 return false;
144912 }
144914 }
144915 bool IsVirtualColumn() const {
144916 if (!has_index) {
144917 return false;
144918 }
144919 return index >= VIRTUAL_COLUMN_START;
144920 }
144921 void VerifySinglePath() const {
144922 if (child_indexes.empty()) {
144923 return;
144924 }
144925 if (child_indexes.size() != 1) {
144926 throw InternalException(
144927 "We were expecting to find a single path in the index, meaning 0 or 1 children, found: %d",
144928 child_indexes.size());
144929 }
144930 child_indexes[0].VerifySinglePath();
144931 }
144932 bool IsChildPathOf(const ColumnIndex &path) const {
144933 VerifySinglePath();
144934 path.VerifySinglePath();
144935 reference<const ColumnIndex> a(*this);
144936 reference<const ColumnIndex> b(path);
144937
144938 while (true) {
144939 if (a.get().HasPrimaryIndex()) {
144940 if (!b.get().HasPrimaryIndex()) {
144941 return false;
144942 }
144943 if (a.get().GetPrimaryIndex() != b.get().GetPrimaryIndex()) {
144944 return false;
144945 }
144946 } else {
144947 if (b.get().HasPrimaryIndex()) {
144948 return false;
144949 }
144950 if (a.get().GetFieldName() != b.get().GetFieldName()) {
144951 return false;
144952 }
144953 }
144954 const bool a_has_children = a.get().HasChildren();
144955 const bool b_has_children = b.get().HasChildren();
144956 if (!a_has_children && !b_has_children) {
144957 return false;
144958 }
144959 if (!a_has_children) {
144961 return false;
144962 }
144963 if (!b_has_children) {
144965 return true;
144966 }
144967 a = a.get().GetChildIndexes()[0];
144968 b = b.get().GetChildIndexes()[0];
144969 }
144970 return true;
144971 }
144972
144973public:
144974 void Serialize(Serializer &serializer) const;
144975 static ColumnIndex Deserialize(Deserializer &deserializer);
144976
144977private:
144979 bool has_index = true;
144982 string field;
144983
144985 LogicalType type = LogicalType::INVALID;
144988 vector<ColumnIndex> child_indexes;
144989};
144990
144991}
144992
144993
144994namespace duckdb {
144995
144997
144998struct StorageIndex {
144999public:
145000 StorageIndex();
145001 explicit StorageIndex(idx_t index);
145002 explicit StorageIndex(const string &field);
145003 StorageIndex(idx_t index, vector<StorageIndex> child_indexes_p);
145004 StorageIndex(const string &field, vector<StorageIndex> child_indexes_p);
145005
145006 inline bool operator==(
const StorageIndex &rhs)
const {
145007 return index == rhs.index;
145008 }
145009 inline bool operator!=(
const StorageIndex &rhs)
const {
145010 return index != rhs.index;
145011 }
145012 inline bool operator<(
const StorageIndex &rhs)
const {
145013 return index < rhs.index;
145014 }
145015
145016public:
145017 static StorageIndex FromColumnIndex(const ColumnIndex &column_id);
145018
145019public:
145020 bool HasPrimaryIndex() const;
145021 idx_t GetPrimaryIndex()
const;
145022 const string &GetFieldName() const;
145023 PhysicalIndex ToPhysical() const;
145024 bool HasType() const;
145025 const LogicalType &GetScanType() const;
145026 const LogicalType &GetType() const;
145027 bool HasChildren() const;
145028 idx_t ChildIndexCount()
const;
145029 const StorageIndex &GetChildIndex(idx_t idx) const;
145030 StorageIndex &GetChildIndex(idx_t idx);
145031 const vector<StorageIndex> &GetChildIndexes() const;
145032 void AddChildIndex(StorageIndex new_index);
145033 void SetType(const LogicalType &type_information);
145034 void SetPushdownExtract();
145035 bool IsPushdownExtract() const;
145036 void SetIndex(idx_t new_index);
145037 bool IsRowIdColumn() const;
145038
145039 void Serialize(Serializer &serializer) const;
145040 static StorageIndex Deserialize(Deserializer &deserializer);
145041
145042private:
145043 bool has_index = true;
145045 string field;
145046
145047 LogicalType type = LogicalType::INVALID;
145049 vector<StorageIndex> child_indexes;
145050};
145051
145052}
145053
145054
145055
145056
145057
145058
145059
145060
145061
145062
145063
145064
145065
145066
145067
145068
145069
145070
145071
145072
145073
145074
145075
145076
145077
145078namespace duckdb {
145079
145080enum class FilterPropagateResult :
uint8_t {
145081 NO_PRUNING_POSSIBLE = 0,
145082 FILTER_ALWAYS_TRUE = 1,
145083 FILTER_ALWAYS_FALSE = 2,
145084 FILTER_TRUE_OR_NULL = 3,
145085 FILTER_FALSE_OR_NULL = 4
145086};
145087
145088}
145089
145090
145091
145092
145093
145094
145095
145096
145097
145098
145099
145100
145101
145102
145103
145104namespace duckdb {
145105
145106struct NumericValueUnion {
145107 union Val {
145108 bool boolean;
145117 hugeint_t hugeint;
145118 uhugeint_t uhugeint;
145119 float float_;
145120 double double_;
145121 } value_;
145122
145123 template <class T>
145124 T &GetReferenceUnsafe();
145125};
145126
145127template <>
145128DUCKDB_API inline bool &NumericValueUnion::GetReferenceUnsafe() {
145129 return value_.boolean;
145130}
145131
145132template <>
145133DUCKDB_API
inline int8_t &NumericValueUnion::GetReferenceUnsafe() {
145134 return value_.tinyint;
145135}
145136
145137template <>
145138DUCKDB_API
inline int16_t &NumericValueUnion::GetReferenceUnsafe() {
145139 return value_.smallint;
145140}
145141
145142template <>
145143DUCKDB_API
inline int32_t &NumericValueUnion::GetReferenceUnsafe() {
145144 return value_.integer;
145145}
145146
145147template <>
145148DUCKDB_API
inline int64_t &NumericValueUnion::GetReferenceUnsafe() {
145149 return value_.bigint;
145150}
145151
145152template <>
145153DUCKDB_API inline hugeint_t &NumericValueUnion::GetReferenceUnsafe() {
145154 return value_.hugeint;
145155}
145156
145157template <>
145158DUCKDB_API inline uhugeint_t &NumericValueUnion::GetReferenceUnsafe() {
145159 return value_.uhugeint;
145160}
145161
145162template <>
145163DUCKDB_API
inline uint8_t &NumericValueUnion::GetReferenceUnsafe() {
145164 return value_.utinyint;
145165}
145166
145167template <>
145168DUCKDB_API
inline uint16_t &NumericValueUnion::GetReferenceUnsafe() {
145169 return value_.usmallint;
145170}
145171
145172template <>
145173DUCKDB_API
inline uint32_t &NumericValueUnion::GetReferenceUnsafe() {
145174 return value_.uinteger;
145175}
145176
145177template <>
145178DUCKDB_API
inline uint64_t &NumericValueUnion::GetReferenceUnsafe() {
145179 return value_.ubigint;
145180}
145181
145182template <>
145183DUCKDB_API inline float &NumericValueUnion::GetReferenceUnsafe() {
145184 return value_.float_;
145185}
145186
145187template <>
145188DUCKDB_API inline double &NumericValueUnion::GetReferenceUnsafe() {
145189 return value_.double_;
145190}
145191
145192}
145193
145194
145195
145196
145197
145198
145199
145200
145201
145202
145203
145204
145205
145206
145207
145208namespace duckdb {
145209
145210template <class DATA_TYPE>
145211class array_ptr_iterator {
145212public:
145213 array_ptr_iterator(DATA_TYPE *ptr, idx_t index, idx_t size) : ptr(ptr),
index(
index),
size(
size) {
145214 }
145215
145216public:
145217 array_ptr_iterator<DATA_TYPE> &operator++() {
145219 if (index > size) {
145221 }
145222 return *this;
145223 }
145224 bool operator!=(
const array_ptr_iterator<DATA_TYPE> &other)
const {
145225 return ptr != other.ptr ||
index != other.index ||
size != other.size;
145226 }
145228 if (DUCKDB_UNLIKELY(index >= size)) {
145229 throw InternalException("array_ptr iterator dereferenced while iterator is out of range");
145230 }
145231 return ptr[
index];
145232 }
145233
145234private:
145235 DATA_TYPE *ptr;
145238};
145239
145241template <class DATA_TYPE, bool SAFE = true>
145242class array_ptr {
145243public:
145244 using iterator_type = array_ptr_iterator<DATA_TYPE>;
145245
145246private:
145247 static inline void AssertNotNull(const bool null) {
145248#if defined(DUCKDB_DEBUG_NO_SAFETY) || defined(DUCKDB_CLANG_TIDY)
145249 return;
145250#else
145251 if (DUCKDB_UNLIKELY(null)) {
145252 throw duckdb::InternalException("Attempted to construct an array_ptr from a NULL pointer");
145253 }
145254#endif
145255 }
145256
145257 static inline void AssertIndexInBounds(idx_t index, idx_t size) {
145258#if defined(DUCKDB_DEBUG_NO_SAFETY) || defined(DUCKDB_CLANG_TIDY)
145259 return;
145260#else
145261 if (DUCKDB_UNLIKELY(index >= size)) {
145262 throw InternalException("Attempted to access index %ld within array_ptr of size %ld", index, size);
145263 }
145264#endif
145265 }
145266
145267public:
145268 array_ptr(DATA_TYPE *ptr_p, idx_t count) : ptr(ptr_p), count(count) {
145269 if (MemorySafety<SAFE>::ENABLED) {
145270 AssertNotNull(!ptr);
145271 }
145272 }
145273 explicit array_ptr(DATA_TYPE &ref) : ptr(&ref), count(1) {
145274 }
145275
145276 const DATA_TYPE &operator[](idx_t idx) const {
145277 if (MemorySafety<SAFE>::ENABLED) {
145278 AssertIndexInBounds(idx, count);
145279 }
145280 return ptr[idx];
145281 }
145282
145283 DATA_TYPE &operator[](idx_t idx) {
145284 if (MemorySafety<SAFE>::ENABLED) {
145285 AssertIndexInBounds(idx, count);
145286 }
145287 return ptr[idx];
145288 }
145289
145291 return count;
145292 }
145293
145294 array_ptr_iterator<DATA_TYPE> begin() {
145295 return array_ptr_iterator<DATA_TYPE>(ptr, 0, count);
145296 }
145297 array_ptr_iterator<DATA_TYPE> begin() const {
145298 return array_ptr_iterator<const DATA_TYPE>(ptr, 0, count);
145299 }
145300 array_ptr_iterator<DATA_TYPE> cbegin() {
145301 return array_ptr_iterator<const DATA_TYPE>(ptr, 0, count);
145302 }
145303 array_ptr_iterator<DATA_TYPE> end() {
145304 return array_ptr_iterator<DATA_TYPE>(ptr, count, count);
145305 }
145306 array_ptr_iterator<DATA_TYPE> end() const {
145307 return array_ptr_iterator<const DATA_TYPE>(ptr, count, count);
145308 }
145309 array_ptr_iterator<DATA_TYPE> cend() {
145310 return array_ptr_iterator<const DATA_TYPE>(ptr, count, count);
145311 }
145312
145313private:
145314 DATA_TYPE *ptr;
145316};
145317
145318template <typename T>
145319using unsafe_array_ptr = array_ptr<T, false>;
145320
145321}
145322
145323
145324namespace duckdb {
145325class BaseStatistics;
145326struct SelectionVector;
145327class Vector;
145328
145329struct NumericStatsData {
145331 bool has_min;
145333 bool has_max;
145335 NumericValueUnion
min;
145337 NumericValueUnion
max;
145338};
145339
145340struct NumericStats {
145342 DUCKDB_API static BaseStatistics CreateUnknown(LogicalType type);
145344 DUCKDB_API static BaseStatistics CreateEmpty(LogicalType type);
145345
145347 DUCKDB_API static bool IsConstant(const BaseStatistics &stats);
145349 DUCKDB_API static bool HasMinMax(const BaseStatistics &stats);
145351 DUCKDB_API static bool HasMin(const BaseStatistics &stats);
145353 DUCKDB_API static bool HasMax(const BaseStatistics &stats);
145355 DUCKDB_API static Value Min(const BaseStatistics &stats);
145357 DUCKDB_API static Value Max(const BaseStatistics &stats);
145359 DUCKDB_API static void SetMin(BaseStatistics &stats, const Value &val);
145361 DUCKDB_API static void SetMax(BaseStatistics &stats, const Value &val);
145362
145363 template <class T>
145364 static void SetMax(BaseStatistics &stats, T val) {
145365 auto &nstats = GetDataUnsafe(stats);
145366 nstats.has_max = true;
145367 nstats.max.GetReferenceUnsafe<T>() = val;
145368 }
145369
145370 template <class T>
145371 static void SetMin(BaseStatistics &stats, T val) {
145372 auto &nstats = GetDataUnsafe(stats);
145373 nstats.has_min = true;
145374 nstats.min.GetReferenceUnsafe<T>() = val;
145375 }
145376
145378 DUCKDB_API static FilterPropagateResult CheckZonemap(const BaseStatistics &stats, ExpressionType comparison_type,
145379 array_ptr<const Value> constants);
145380
145381 DUCKDB_API static void Merge(BaseStatistics &stats, const BaseStatistics &other_p);
145382
145383 DUCKDB_API static void Serialize(const BaseStatistics &stats, Serializer &serializer);
145384 DUCKDB_API static void Deserialize(Deserializer &deserializer, BaseStatistics &stats);
145385
145386 DUCKDB_API static string ToString(const BaseStatistics &stats);
145387
145388 template <class T>
145389 static inline void UpdateValue(T new_value, T &
min, T &
max) {
145390 min = LessThan::Operation(new_value,
min) ? new_value :
min;
145391 max = GreaterThan::Operation(new_value,
max) ? new_value :
max;
145392 }
145393 template <class T>
145394 static inline void Update(NumericStatsData &nstats, T new_value) {
145395 UpdateValue<T>(new_value, nstats.min.GetReferenceUnsafe<T>(), nstats.max.GetReferenceUnsafe<T>());
145396 }
145397
145398 static void Verify(const BaseStatistics &stats, Vector &vector, const SelectionVector &sel, idx_t count);
145399
145400 template <class T>
145401 static T GetMin(const BaseStatistics &stats) {
145402 return NumericStats::Min(stats).GetValueUnsafe<T>();
145403 }
145404 template <class T>
145405 static T GetMax(const BaseStatistics &stats) {
145406 return NumericStats::Max(stats).GetValueUnsafe<T>();
145407 }
145408 template <class T>
145409 static T GetMinUnsafe(const BaseStatistics &stats);
145410 template <class T>
145411 static T GetMaxUnsafe(const BaseStatistics &stats);
145412
145413private:
145414 static NumericStatsData &GetDataUnsafe(BaseStatistics &stats);
145415 static const NumericStatsData &GetDataUnsafe(const BaseStatistics &stats);
145416 static Value MinOrNull(const BaseStatistics &stats);
145417 static Value MaxOrNull(const BaseStatistics &stats);
145418 template <class T>
145419 static void TemplatedVerify(const BaseStatistics &stats, Vector &vector, const SelectionVector &sel, idx_t count);
145420};
145421
145422}
145423
145424
145425
145426
145427
145428
145429
145430
145431
145432
145433
145434
145435
145436
145437
145438
145439
145440namespace duckdb {
145441class BaseStatistics;
145442struct SelectionVector;
145443class Vector;
145444
145445struct StringStatsData {
145446 constexpr static uint32_t MAX_STRING_MINMAX_SIZE = 8;
145447
145453 bool has_unicode;
145455 bool has_max_string_length;
145458};
145459
145460struct StringStats {
145462 DUCKDB_API static BaseStatistics CreateUnknown(LogicalType type);
145464 DUCKDB_API static BaseStatistics CreateEmpty(LogicalType type);
145466 DUCKDB_API static bool HasMaxStringLength(const BaseStatistics &stats);
145468 DUCKDB_API
static uint32_t MaxStringLength(
const BaseStatistics &stats);
145470 DUCKDB_API static bool CanContainUnicode(const BaseStatistics &stats);
145472 DUCKDB_API static string Min(const BaseStatistics &stats);
145474 DUCKDB_API static string Max(const BaseStatistics &stats);
145475
145477 DUCKDB_API static void ResetMaxStringLength(BaseStatistics &stats);
145479 DUCKDB_API static void SetMaxStringLength(BaseStatistics &stats, uint32_t length);
145481 DUCKDB_API static void SetContainsUnicode(BaseStatistics &stats);
145482
145483 DUCKDB_API static void Serialize(const BaseStatistics &stats, Serializer &serializer);
145484 DUCKDB_API static void Deserialize(Deserializer &deserializer, BaseStatistics &base);
145485
145486 DUCKDB_API static string ToString(const BaseStatistics &stats);
145487
145488 DUCKDB_API static FilterPropagateResult CheckZonemap(const BaseStatistics &stats, ExpressionType comparison_type,
145489 array_ptr<const Value> constants);
145490 DUCKDB_API static FilterPropagateResult CheckZonemap(const_data_ptr_t min_data, idx_t min_len,
145491 const_data_ptr_t max_data, idx_t max_len,
145492 ExpressionType comparison_type, const string &value);
145493
145494 DUCKDB_API static void Update(BaseStatistics &stats, const string_t &value);
145495 DUCKDB_API static void SetMin(BaseStatistics &stats, const string_t &value);
145496 DUCKDB_API static void SetMax(BaseStatistics &stats, const string_t &value);
145497 DUCKDB_API static void Merge(BaseStatistics &stats, const BaseStatistics &other);
145498 DUCKDB_API static void Verify(const BaseStatistics &stats, Vector &vector, const SelectionVector &sel, idx_t count);
145499
145500private:
145501 static StringStatsData &GetDataUnsafe(BaseStatistics &stats);
145502 static const StringStatsData &GetDataUnsafe(const BaseStatistics &stats);
145503};
145504
145505}
145506
145507
145508
145509
145510
145511
145512
145513
145514
145515
145516
145517
145518
145519
145520
145521
145522
145523
145524
145525
145526
145527
145528
145529
145530
145531
145532
145533#include <limits>
145534#include <cmath>
145535
145536namespace duckdb {
145537
145538struct GeometryStatsData;
145539
145540enum class GeometryType :
uint8_t {
145541 INVALID = 0,
145542 POINT = 1,
145543 LINESTRING = 2,
145545 MULTIPOINT = 4,
145546 MULTILINESTRING = 5,
145547 MULTIPOLYGON = 6,
145548 GEOMETRYCOLLECTION = 7,
145549};
145550
145551enum class VertexType :
uint8_t { XY = 0,
XYZ = 1, XYM = 2, XYZM = 3 };
145552
145553struct VertexXY {
145554 static constexpr auto TYPE = VertexType::XY;
145555 static constexpr auto HAS_Z = false;
145556 static constexpr auto HAS_M = false;
145557 static constexpr auto WIDTH = 2;
145558
145559 double x;
145560 double y;
145561
145562 bool AllNan() const {
145563 return std::isnan(x) && std::isnan(y);
145564 }
145565};
145566
145567struct VertexXYZ {
145568 static constexpr auto TYPE = VertexType::XYZ;
145569 static constexpr auto HAS_Z = true;
145570 static constexpr auto HAS_M = false;
145571 static constexpr auto WIDTH = 3;
145572
145573 double x;
145574 double y;
145576
145577 bool AllNan() const {
145578 return std::isnan(x) && std::isnan(y) && std::isnan(z);
145579 }
145580};
145581struct VertexXYM {
145582 static constexpr auto TYPE = VertexType::XYM;
145583 static constexpr auto HAS_M = true;
145584 static constexpr auto HAS_Z = false;
145585 static constexpr auto WIDTH = 3;
145586
145587 double x;
145588 double y;
145589 double m;
145590
145591 bool AllNan() const {
145592 return std::isnan(x) && std::isnan(y) && std::isnan(m);
145593 }
145594};
145595
145596struct VertexXYZM {
145597 static constexpr auto TYPE = VertexType::XYZM;
145598 static constexpr auto HAS_Z = true;
145599 static constexpr auto HAS_M = true;
145600 static constexpr auto WIDTH = 4;
145601
145602 double x;
145603 double y;
145605 double m;
145606
145607 bool AllNan() const {
145608 return std::isnan(x) && std::isnan(y) && std::isnan(z) && std::isnan(m);
145609 }
145610};
145611
145612class GeometryExtent {
145613public:
145614 static constexpr auto UNKNOWN_MIN = -std::numeric_limits<double>::infinity();
145615 static constexpr auto UNKNOWN_MAX = +std::numeric_limits<double>::infinity();
145616
145617 static constexpr auto EMPTY_MIN = +std::numeric_limits<double>::infinity();
145618 static constexpr auto EMPTY_MAX = -std::numeric_limits<double>::infinity();
145619
145620
145621
145622
145623 static GeometryExtent Unknown() {
145624 return GeometryExtent {UNKNOWN_MIN, UNKNOWN_MIN, UNKNOWN_MIN, UNKNOWN_MIN,
145625 UNKNOWN_MAX, UNKNOWN_MAX, UNKNOWN_MAX, UNKNOWN_MAX};
145626 }
145627
145628
145629
145630
145631 static GeometryExtent Empty() {
145632 return GeometryExtent {EMPTY_MIN, EMPTY_MIN, EMPTY_MIN, EMPTY_MIN, EMPTY_MAX, EMPTY_MAX, EMPTY_MAX, EMPTY_MAX};
145633 }
145634
145635
145636
145637 bool HasXY() const {
145638 return std::isfinite(x_min) && std::isfinite(y_min) && std::isfinite(x_max) && std::isfinite(y_max);
145639 }
145640
145641
145642 bool HasZ() const {
145643 return std::isfinite(z_min) && std::isfinite(z_max);
145644 }
145645
145646
145647 bool HasM() const {
145648 return std::isfinite(m_min) && std::isfinite(m_max);
145649 }
145650
145651 void Extend(const VertexXY &vertex) {
145652 x_min = MinValue(x_min, vertex.x);
145653 x_max = MaxValue(x_max, vertex.x);
145654 y_min = MinValue(y_min, vertex.y);
145655 y_max = MaxValue(y_max, vertex.y);
145656 }
145657
145658 void Extend(const VertexXYZ &vertex) {
145659 x_min = MinValue(x_min, vertex.x);
145660 x_max = MaxValue(x_max, vertex.x);
145661 y_min = MinValue(y_min, vertex.y);
145662 y_max = MaxValue(y_max, vertex.y);
145663 z_min = MinValue(z_min, vertex.z);
145664 z_max = MaxValue(z_max, vertex.z);
145665 }
145666
145667 void Extend(const VertexXYM &vertex) {
145668 x_min = MinValue(x_min, vertex.x);
145669 x_max = MaxValue(x_max, vertex.x);
145670 y_min = MinValue(y_min, vertex.y);
145671 y_max = MaxValue(y_max, vertex.y);
145672 m_min = MinValue(m_min, vertex.m);
145673 m_max = MaxValue(m_max, vertex.m);
145674 }
145675
145676 void Extend(const VertexXYZM &vertex) {
145677 x_min = MinValue(x_min, vertex.x);
145678 x_max = MaxValue(x_max, vertex.x);
145679 y_min = MinValue(y_min, vertex.y);
145680 y_max = MaxValue(y_max, vertex.y);
145681 z_min = MinValue(z_min, vertex.z);
145682 z_max = MaxValue(z_max, vertex.z);
145683 m_min = MinValue(m_min, vertex.m);
145684 m_max = MaxValue(m_max, vertex.m);
145685 }
145686
145687 void Merge(const GeometryExtent &other) {
145688 x_min = MinValue(x_min, other.x_min);
145689 y_min = MinValue(y_min, other.y_min);
145690 z_min = MinValue(z_min, other.z_min);
145691 m_min = MinValue(m_min, other.m_min);
145692
145693 x_max = MaxValue(x_max, other.x_max);
145694 y_max = MaxValue(y_max, other.y_max);
145695 z_max = MaxValue(z_max, other.z_max);
145696 m_max = MaxValue(m_max, other.m_max);
145697 }
145698
145699 bool IntersectsXY(const GeometryExtent &other) const {
145700 return !(x_min > other.x_max || x_max < other.x_min || y_min > other.y_max || y_max < other.y_min);
145701 }
145702
145703 bool IntersectsXYZM(const GeometryExtent &other) const {
145704 return !(x_min > other.x_max || x_max < other.x_min || y_min > other.y_max || y_max < other.y_min ||
145705 z_min > other.z_max || z_max < other.z_min || m_min > other.m_max || m_max < other.m_min);
145706 }
145707
145708 bool ContainsXY(const GeometryExtent &other) const {
145709 return x_min <= other.x_min && x_max >= other.x_max && y_min <= other.y_min && y_max >= other.y_max;
145710 }
145711
145712 double x_min;
145713 double y_min;
145714 double z_min;
145715 double m_min;
145716
145717 double x_max;
145718 double y_max;
145719 double z_max;
145720 double m_max;
145721};
145722
145723enum class GeometryStorageType :
uint8_t {
145724
145725 SPATIAL = 0,
145726 WKB = 1,
145727
145728
145729 POINT_XY = 17,
145730 LINESTRING_XY = 18,
145731 POLYGON_XY = 19,
145732 MULTIPOINT_XY = 20,
145733 MULTILINESTRING_XY = 21,
145734 MULTIPOLYGON_XY = 22,
145735
145736
145737 POINT_XYZ = 33,
145738 LINESTRING_XYZ = 34,
145739 POLYGON_XYZ = 35,
145740 MULTIPOINT_XYZ = 36,
145741 MULTILINESTRING_XYZ = 37,
145742 MULTIPOLYGON_XYZ = 38,
145743
145744
145745 POINT_XYM = 65,
145746 LINESTRING_XYM = 66,
145747 POLYGON_XYM = 67,
145748 MULTIPOINT_XYM = 68,
145749 MULTILINESTRING_XYM = 69,
145750 MULTIPOLYGON_XYM = 70,
145751
145752
145753 POINT_XYZM = 97,
145754 LINESTRING_XYZM = 98,
145755 POLYGON_XYZM = 99,
145756 MULTIPOINT_XYZM = 100,
145757 MULTILINESTRING_XYZM = 101,
145758 MULTIPOLYGON_XYZM = 102,
145759};
145760
145761class Geometry {
145762public:
145763 static constexpr idx_t MAX_RECURSION_DEPTH = 16;
145764 static constexpr idx_t VERSION_ADDED = 7;
145765
145767 static bool IsSpatialGeometryType(const LogicalType &type);
145769 static LogicalType GetSpatialGeometryType();
145770
145772 DUCKDB_API static bool FromString(const string_t &wkt_text, string_t &result, Vector &result_vector, bool strict);
145773 DUCKDB_API static bool FromString(const string_t &wkt_text, string_t &result, Vector &result_vector, bool strict,
145774 optional_idx query_location);
145775
145777 DUCKDB_API static string_t ToString(Vector &result, const string_t &geom);
145778
145780 DUCKDB_API static bool FromBinary(const string_t &wkb, string_t &result, Vector &result_vector, bool strict);
145781 DUCKDB_API static bool FromBinary(Vector &source, Vector &result, idx_t count, bool strict);
145782
145784 DUCKDB_API static void ToBinary(Vector &source, Vector &result, idx_t count);
145785
145787 DUCKDB_API static pair<GeometryType, VertexType> GetType(const string_t &wkb);
145788
145790 DUCKDB_API
static uint32_t GetExtent(
const string_t &wkb, GeometryExtent &extent);
145791 DUCKDB_API
static uint32_t GetExtent(
const string_t &wkb, GeometryExtent &extent,
bool &has_any_empty);
145792
145794 DUCKDB_API static void ToVectorizedFormat(Vector &source, Vector &target, idx_t count, GeometryType geom_type,
145795 VertexType vert_type);
145796 DUCKDB_API static void ToVectorizedFormat(Vector &source, Vector &target, idx_t count, GeometryStorageType type);
145798 DUCKDB_API static void FromVectorizedFormat(Vector &source, Vector &target, idx_t count, GeometryType geom_type,
145799 VertexType vert_type, idx_t result_offset);
145800 DUCKDB_API static void FromVectorizedFormat(Vector &source, Vector &target, idx_t count, GeometryStorageType type,
145801 idx_t result_offset);
145802
145804 DUCKDB_API static LogicalType GetVectorizedType(GeometryStorageType type);
145805 DUCKDB_API static LogicalType GetVectorizedType(GeometryType geom_type, VertexType vert_type);
145806
145807 DUCKDB_API static pair<GeometryType, VertexType> GetSpecializedType(GeometryStorageType type);
145808
145809 DUCKDB_API static void FromSpatialGeometry(const string_t &source, string_t &target, Vector &vector);
145810 DUCKDB_API static void FromSpatialGeometry(Vector &source, Vector &target, idx_t count, idx_t result_offset);
145811 DUCKDB_API static void FromSpatialGeometry(const string_t &source, string &target);
145812
145813 DUCKDB_API static void ToSpatialGeometry(const string_t &source, string_t &target, Vector &vector);
145814 DUCKDB_API static void ToSpatialGeometry(Vector &source, Vector &target, idx_t count);
145815 DUCKDB_API static void ToSpatialGeometry(const string_t &source, string &target);
145816};
145817
145818}
145819
145820
145821namespace duckdb {
145822class BaseStatistics;
145823struct SelectionVector;
145824
145825class GeometryTypeSet {
145826public:
145827 static constexpr auto VERT_TYPES = 4;
145828 static constexpr auto PART_TYPES = 8;
145829
145830 static GeometryTypeSet Unknown() {
145831 GeometryTypeSet result;
145832 for (idx_t i = 0; i < VERT_TYPES; i++) {
145833 result.sets[i] = 0xFF;
145834 }
145835 return result;
145836 }
145837 static GeometryTypeSet Empty() {
145838 GeometryTypeSet result;
145839 for (idx_t i = 0; i < VERT_TYPES; i++) {
145840 result.sets[i] = 0;
145841 }
145842 return result;
145843 }
145844
145845 bool IsEmpty() const {
145846 for (idx_t i = 0; i < VERT_TYPES; i++) {
145847 if (sets[i] != 0) {
145848 return false;
145849 }
145850 }
145851 return true;
145852 }
145853
145854 bool IsUnknown() const {
145855 for (idx_t i = 0; i < VERT_TYPES; i++) {
145856 if (sets[i] != 0xFF) {
145857 return false;
145858 }
145859 }
145860 return true;
145861 }
145862
145863 void Add(GeometryType geom_type, VertexType vert_type) {
145864 const auto vert_idx =
static_cast<uint8_t>(vert_type);
145865 const auto geom_idx =
static_cast<uint8_t>(geom_type);
145866 D_ASSERT(vert_idx < VERT_TYPES);
145867 D_ASSERT(geom_idx < PART_TYPES);
145868 sets[vert_idx] |= (1 << geom_idx);
145869 }
145870
145871 void Merge(const GeometryTypeSet &other) {
145872 for (idx_t i = 0; i < VERT_TYPES; i++) {
145873 sets[i] |= other.sets[i];
145874 }
145875 }
145876
145877 void Clear() {
145878 for (idx_t i = 0; i < VERT_TYPES; i++) {
145879 sets[i] = 0;
145880 }
145881 }
145882
145885 bool HasOnly(GeometryType geom_type, VertexType vert_type) const {
145886 const auto vert_idx =
static_cast<uint8_t>(vert_type);
145887 const auto geom_idx =
static_cast<uint8_t>(geom_type);
145888 D_ASSERT(vert_idx < VERT_TYPES);
145889 D_ASSERT(geom_idx < PART_TYPES);
145890 for (uint8_t v_idx = 0; v_idx < VERT_TYPES; v_idx++) {
145891 for (uint8_t g_idx = 1; g_idx < PART_TYPES; g_idx++) {
145892 if (v_idx == vert_idx && g_idx == geom_idx) {
145893 if (!(sets[v_idx] & (1 << g_idx))) {
145894 return false;
145895 }
145896 } else {
145897 if (sets[v_idx] & (1 << g_idx)) {
145898 return false;
145899 }
145900 }
145901 }
145902 }
145903 return true;
145904 }
145905
145906 bool HasSingleType() const {
145907 idx_t type_count = 0;
145908 for (uint8_t v_idx = 0; v_idx < VERT_TYPES; v_idx++) {
145909 for (uint8_t g_idx = 1; g_idx < PART_TYPES; g_idx++) {
145910 if (sets[v_idx] & (1 << g_idx)) {
145911 type_count++;
145912 if (type_count > 1) {
145913 return false;
145914 }
145915 }
145916 }
145917 }
145918 return type_count == 1;
145919 }
145920
145921 bool TryGetSingleType(GeometryType &geom_type, VertexType &vert_type) const {
145922 auto result_geom = GeometryType::INVALID;
145923 auto result_vert = VertexType::XY;
145924 auto result_found = false;
145925
145926 for (uint8_t v_idx = 0; v_idx < VERT_TYPES; v_idx++) {
145927 for (uint8_t g_idx = 1; g_idx < PART_TYPES; g_idx++) {
145928 if (sets[v_idx] & (1 << g_idx)) {
145929 if (result_found) {
145930
145931 return false;
145932 }
145933 result_found = true;
145934 result_geom = static_cast<GeometryType>(g_idx);
145935 result_vert = static_cast<VertexType>(v_idx);
145936 }
145937 }
145938 }
145939 if (result_found) {
145940 geom_type = result_geom;
145941 vert_type = result_vert;
145942 }
145943 return result_found;
145944 }
145945
145946 void AddWKBType(int32_t wkb_type) {
145947 const auto vert_idx =
static_cast<uint8_t>((wkb_type / 1000) % 10);
145948 const auto geom_idx =
static_cast<uint8_t>(wkb_type % 1000);
145949 D_ASSERT(vert_idx < VERT_TYPES);
145950 D_ASSERT(geom_idx < PART_TYPES);
145951 sets[vert_idx] |= (1 << geom_idx);
145952 }
145953
145954 vector<int32_t> ToWKBList() const {
145955 vector<int32_t> result;
145956 for (uint8_t vert_idx = 0; vert_idx < VERT_TYPES; vert_idx++) {
145957 for (uint8_t geom_idx = 1; geom_idx < PART_TYPES; geom_idx++) {
145958 if (sets[vert_idx] & (1 << geom_idx)) {
145959 result.push_back(geom_idx + vert_idx * 1000);
145960 }
145961 }
145962 }
145963 return result;
145964 }
145965
145966 vector<string> ToString(bool snake_case) const;
145967
145969};
145970
145971class GeometryStatsFlags {
145972public:
145973
145974
145975
145976
145977 static GeometryStatsFlags Unknown() {
145978 GeometryStatsFlags flags;
145979 flags.flags = 0xF;
145980 return flags;
145981 }
145982
145983 static GeometryStatsFlags Empty() {
145984 GeometryStatsFlags flags;
145985 flags.flags = 0x0;
145986 return flags;
145987 }
145988 void Clear() {
145989 flags = 0x0;
145990 }
145991 bool HasEmptyGeometry() const {
145992 return (flags & HAS_EMPTY_GEOM) != 0;
145993 }
145994 bool HasNonEmptyGeometry() const {
145995 return (flags & HAS_NON_EMPTY_GEOM) != 0;
145996 }
145997 bool HasEmptyPart() const {
145998 return (flags & HAS_EMPTY_PART) != 0;
145999 }
146000 bool HasNonEmptyPart() const {
146001 return (flags & HAS_NON_EMPTY_PART) != 0;
146002 }
146003 void SetHasEmptyGeometry() {
146004 flags |= HAS_EMPTY_GEOM;
146005 }
146006 void SetHasNonEmptyGeometry() {
146007 flags |= HAS_NON_EMPTY_GEOM;
146008 }
146009 void SetHasEmptyPart() {
146010 flags |= HAS_EMPTY_PART;
146011 }
146012 void SetHasNonEmptyPart() {
146013 flags |= HAS_NON_EMPTY_PART;
146014 }
146015
146016 void Merge(const GeometryStatsFlags &other) {
146017 flags |= other.flags;
146018 }
146019
146021
146022private:
146023 static constexpr auto HAS_EMPTY_GEOM = 0x1;
146024 static constexpr auto HAS_NON_EMPTY_GEOM = 0x2;
146025 static constexpr auto HAS_EMPTY_PART = 0x4;
146026 static constexpr auto HAS_NON_EMPTY_PART = 0x8;
146027};
146028
146029struct GeometryStatsData {
146030 GeometryTypeSet types;
146031 GeometryExtent extent;
146032 GeometryStatsFlags flags;
146033
146034 void SetEmpty() {
146035 types = GeometryTypeSet::Empty();
146036 extent = GeometryExtent::Empty();
146037 flags = GeometryStatsFlags::Empty();
146038 }
146039
146040 void SetUnknown() {
146041 types = GeometryTypeSet::Unknown();
146042 extent = GeometryExtent::Unknown();
146043 flags = GeometryStatsFlags::Unknown();
146044 }
146045
146046 void Merge(const GeometryStatsData &other) {
146047 types.Merge(other.types);
146048 extent.Merge(other.extent);
146049 flags.Merge(other.flags);
146050 }
146051
146052 void Update(const string_t &geom_blob) {
146053
146054 const auto type_info = Geometry::GetType(geom_blob);
146055 types.Add(type_info.first, type_info.second);
146056
146057
146058 bool has_any_empty = false;
146059 const auto vert_count = Geometry::GetExtent(geom_blob, extent, has_any_empty);
146060
146061
146062 if (has_any_empty) {
146063 flags.SetHasEmptyPart();
146064 } else {
146065 flags.SetHasNonEmptyPart();
146066 }
146067
146068 if (vert_count == 0) {
146069 flags.SetHasEmptyGeometry();
146070 } else {
146071 flags.SetHasNonEmptyGeometry();
146072 }
146073 }
146074};
146075
146076struct GeometryStats {
146078 DUCKDB_API static BaseStatistics CreateUnknown(LogicalType type);
146080 DUCKDB_API static BaseStatistics CreateEmpty(LogicalType type);
146081
146082 DUCKDB_API static void Serialize(const BaseStatistics &stats, Serializer &serializer);
146083 DUCKDB_API static void Deserialize(Deserializer &deserializer, BaseStatistics &base);
146084
146085 DUCKDB_API static string ToString(const BaseStatistics &stats);
146086
146087 DUCKDB_API static void Update(BaseStatistics &stats, const string_t &value);
146088 DUCKDB_API static void Merge(BaseStatistics &stats, const BaseStatistics &other);
146089 DUCKDB_API static void Verify(const BaseStatistics &stats, Vector &vector, const SelectionVector &sel, idx_t count);
146090
146092 DUCKDB_API static FilterPropagateResult CheckZonemap(const BaseStatistics &stats,
146093 const unique_ptr<Expression> &expr);
146094
146095 DUCKDB_API static GeometryExtent &GetExtent(BaseStatistics &stats);
146096 DUCKDB_API static const GeometryExtent &GetExtent(const BaseStatistics &stats);
146097 DUCKDB_API static GeometryTypeSet &GetTypes(BaseStatistics &stats);
146098 DUCKDB_API static const GeometryTypeSet &GetTypes(const BaseStatistics &stats);
146099 DUCKDB_API static GeometryStatsFlags &GetFlags(BaseStatistics &stats);
146100 DUCKDB_API static const GeometryStatsFlags &GetFlags(const BaseStatistics &stats);
146101
146102 static GeometryStatsData &GetDataUnsafe(BaseStatistics &stats);
146103 static const GeometryStatsData &GetDataUnsafe(const BaseStatistics &stats);
146104};
146105
146106}
146107
146108
146109
146110
146111
146112
146113
146114
146115
146116
146117namespace duckdb_yyjson {
146120}
146121
146122namespace duckdb {
146123class Vector;
146124struct ValidityMask;
146125struct UnifiedVariantVector;
146126struct RecursiveUnifiedVectorFormat;
146127struct UnifiedVectorFormat;
146128
146129enum class VariantChildLookupMode :
uint8_t { INVALID, BY_KEY, BY_INDEX };
146130
146131struct Variant {
146132public:
146133 static constexpr idx_t VERSION_ADDED = 7;
146134};
146135
146136struct VariantPathComponent {
146137public:
146138 explicit VariantPathComponent() : lookup_mode(VariantChildLookupMode::INVALID) {
146139 }
146140 explicit VariantPathComponent(const string &key) : lookup_mode(VariantChildLookupMode::BY_KEY), key(key) {
146141 }
146142 explicit VariantPathComponent(uint32_t index) : lookup_mode(VariantChildLookupMode::BY_INDEX),
index(
index) {
146143 }
146144
146145public:
146146 VariantChildLookupMode lookup_mode;
146147 string key;
146149};
146150
146151struct VariantNestedData {
146156};
146157
146158struct VariantDecimalData {
146159public:
146160 VariantDecimalData(uint32_t width, uint32_t scale, const_data_ptr_t value_ptr)
146161 : width(width),
scale(
scale), value_ptr(value_ptr) {
146162 }
146163
146164public:
146166
146167public:
146170 const_data_ptr_t value_ptr = nullptr;
146171};
146172
146173struct VariantVectorData {
146174public:
146175 explicit VariantVectorData(Vector &variant);
146176
146177public:
146178 Vector &variant;
146179
146181 string_t *blob_data;
146182
146186
146190 ValidityMask &keys_index_validity;
146191
146193 list_entry_t *values_data;
146194 list_entry_t *children_data;
146195 list_entry_t *keys_data;
146196
146197 Vector &keys;
146198};
146199
146200enum class VariantLogicalType :
uint8_t {
146201 VARIANT_NULL = 0,
146202 BOOL_TRUE = 1,
146203 BOOL_FALSE = 2,
146208 INT128 = 7,
146213 UINT128 = 12,
146216 DECIMAL = 15,
146217 VARCHAR = 16,
146218 BLOB = 17,
146219 UUID = 18,
146220 DATE = 19,
146221 TIME_MICROS = 20,
146222 TIME_NANOS = 21,
146223 TIMESTAMP_SEC = 22,
146224 TIMESTAMP_MILIS = 23,
146225 TIMESTAMP_MICROS = 24,
146226 TIMESTAMP_NANOS = 25,
146227 TIME_MICROS_TZ = 26,
146228 TIMESTAMP_MICROS_TZ = 27,
146229 INTERVAL = 28,
146230 OBJECT = 29,
146231 ARRAY = 30,
146232 BIGNUM = 31,
146233 BITSTRING = 32,
146234 GEOMETRY = 33,
146235 ENUM_SIZE
146236};
146237
146238struct UnifiedVariantVectorData {
146239public:
146240 explicit UnifiedVariantVectorData(const RecursiveUnifiedVectorFormat &variant);
146241
146242public:
146243 bool RowIsValid(idx_t row) const;
146244 bool KeysIndexIsValid(idx_t row, idx_t index) const;
146245 list_entry_t GetChildrenListEntry(idx_t row) const;
146246 list_entry_t GetValuesListEntry(idx_t row) const;
146247 const string_t &GetKey(idx_t row, idx_t index) const;
146248 uint32_t GetKeysIndex(idx_t row, idx_t child_index)
const;
146249 uint32_t GetValuesIndex(idx_t row, idx_t child_index)
const;
146250 VariantLogicalType
GetTypeId(idx_t row, idx_t value_index)
const;
146251 uint32_t GetByteOffset(idx_t row, idx_t value_index)
const;
146252 const string_t &GetData(idx_t row) const;
146253
146254public:
146255 const RecursiveUnifiedVectorFormat &variant;
146256 const UnifiedVectorFormat &keys;
146257 const UnifiedVectorFormat &keys_entry;
146258 const UnifiedVectorFormat &children;
146259 const UnifiedVectorFormat &keys_index;
146260 const UnifiedVectorFormat &values_index;
146261 const UnifiedVectorFormat &values;
146262 const UnifiedVectorFormat &type_id;
146263 const UnifiedVectorFormat &byte_offset;
146264 const UnifiedVectorFormat &data;
146265
146266 const list_entry_t *keys_data = nullptr;
146267 const string_t *keys_entry_data = nullptr;
146268 const list_entry_t *children_data = nullptr;
146269 const uint32_t *keys_index_data =
nullptr;
146270 const uint32_t *values_index_data =
nullptr;
146271 const list_entry_t *values_data = nullptr;
146272 const uint8_t *type_id_data =
nullptr;
146273 const uint32_t *byte_offset_data =
nullptr;
146274 const string_t *blob_data = nullptr;
146275
146276 const ValidityMask &keys_index_validity;
146277};
146278
146279struct VariantCasts {
146281 const RecursiveUnifiedVectorFormat &source, idx_t row,
146282 uint32_t values_idx);
146283};
146284
146285}
146286
146287
146288
146289
146290namespace duckdb {
146291class BaseStatistics;
146292
146295 UNINITIALIZED,
146302};
146303
146304struct VariantStatsData {
146307};
146308
146309struct VariantShreddedStats {
146310public:
146311 DUCKDB_API static bool IsFullyShredded(const BaseStatistics &stats);
146312 DUCKDB_API static optional_ptr<const BaseStatistics> FindChildStats(const BaseStatistics &stats,
146313 const VariantPathComponent &component);
146314};
146315
146320struct VariantStats {
146321public:
146322 static constexpr idx_t TYPED_VALUE_INDEX = 0;
146323 static constexpr idx_t UNTYPED_VALUE_INDEX = 1;
146324
146325public:
146326 DUCKDB_API static void Construct(BaseStatistics &stats);
146327
146328public:
146329 DUCKDB_API static BaseStatistics CreateUnknown(LogicalType type);
146330 DUCKDB_API static BaseStatistics CreateEmpty(LogicalType type);
146331 DUCKDB_API static BaseStatistics CreateShredded(const LogicalType &shredded_type);
146332
146333public:
146336 DUCKDB_API static void CreateUnshreddedStats(BaseStatistics &stats);
146337 DUCKDB_API static const BaseStatistics &GetUnshreddedStats(const BaseStatistics &stats);
146338 DUCKDB_API static BaseStatistics &GetUnshreddedStats(BaseStatistics &stats);
146339
146341 DUCKDB_API static const BaseStatistics &GetTypedStats(const BaseStatistics &stats);
146342 DUCKDB_API static const BaseStatistics &GetTypedStats(const BaseStatistics &&stats) = delete;
146343
146345 DUCKDB_API static optional_ptr<const BaseStatistics> GetUntypedStats(const BaseStatistics &stats);
146346 DUCKDB_API static optional_ptr<const BaseStatistics> GetUntypedStats(const BaseStatistics &&stats) = delete;
146347
146348 DUCKDB_API static void SetUnshreddedStats(BaseStatistics &stats, unique_ptr<BaseStatistics> new_stats);
146349 DUCKDB_API static void SetUnshreddedStats(BaseStatistics &stats, const BaseStatistics &new_stats);
146350 DUCKDB_API static void MarkAsNotShredded(BaseStatistics &stats);
146351
146352public:
146355 DUCKDB_API static LogicalType GetShreddedStructuredType(const BaseStatistics &stats);
146356 DUCKDB_API static void CreateShreddedStats(BaseStatistics &stats, const LogicalType &shredded_type);
146357 DUCKDB_API static bool IsShredded(const BaseStatistics &stats);
146358 DUCKDB_API static const BaseStatistics &GetShreddedStats(const BaseStatistics &stats);
146359 DUCKDB_API static BaseStatistics &GetShreddedStats(BaseStatistics &stats);
146360
146361 DUCKDB_API static void SetShreddedStats(BaseStatistics &stats, unique_ptr<BaseStatistics> new_stats);
146362 DUCKDB_API static void SetShreddedStats(BaseStatistics &stats, const BaseStatistics &new_stats);
146363
146364 DUCKDB_API static bool MergeShredding(const BaseStatistics &stats, const BaseStatistics &other,
146365 BaseStatistics &new_stats);
146366 DUCKDB_API static unique_ptr<BaseStatistics> WrapExtractedFieldAsVariant(const BaseStatistics &base_variant,
146367 const BaseStatistics &extracted_field);
146368
146369public:
146370 DUCKDB_API static void Serialize(const BaseStatistics &stats, Serializer &serializer);
146371 DUCKDB_API static void Deserialize(Deserializer &deserializer, BaseStatistics &base);
146372
146373 DUCKDB_API static string ToString(const BaseStatistics &stats);
146374
146375 DUCKDB_API static void Merge(BaseStatistics &stats, const BaseStatistics &other);
146376 DUCKDB_API static void Verify(const BaseStatistics &stats, Vector &vector, const SelectionVector &sel, idx_t count);
146377 DUCKDB_API static void Copy(BaseStatistics &stats, const BaseStatistics &other);
146378 DUCKDB_API static unique_ptr<BaseStatistics> PushdownExtract(const BaseStatistics &stats,
146379 const StorageIndex &index);
146380
146381private:
146382 static VariantStatsData &GetDataUnsafe(BaseStatistics &stats);
146383 static const VariantStatsData &GetDataUnsafe(const BaseStatistics &stats);
146384};
146385
146386}
146387
146388
146389namespace duckdb {
146390struct SelectionVector;
146391
146392class Serializer;
146393class Deserializer;
146394
146395class Vector;
146396struct UnifiedVectorFormat;
146397
146398enum class StatsInfo :
uint8_t {
146399 CAN_HAVE_NULL_VALUES = 0,
146400 CANNOT_HAVE_NULL_VALUES = 1,
146401 CAN_HAVE_VALID_VALUES = 2,
146402 CANNOT_HAVE_VALID_VALUES = 3,
146403 CAN_HAVE_NULL_AND_VALID_VALUES = 4
146404};
146405
146406enum class StatisticsType :
uint8_t {
146407 NUMERIC_STATS,
146408 STRING_STATS,
146409 LIST_STATS,
146410 STRUCT_STATS,
146411 BASE_STATS,
146412 ARRAY_STATS,
146413 GEOMETRY_STATS,
146414 VARIANT_STATS
146415};
146416
146417class BaseStatistics {
146418 friend struct NumericStats;
146419 friend struct StringStats;
146420 friend struct StructStats;
146421 friend struct ListStats;
146422 friend struct ArrayStats;
146423 friend struct GeometryStats;
146424 friend struct VariantStats;
146425
146426public:
146427 DUCKDB_API ~BaseStatistics();
146428
146429 BaseStatistics(const BaseStatistics &other) = delete;
146430 BaseStatistics &
operator=(
const BaseStatistics &) =
delete;
146432 DUCKDB_API BaseStatistics(BaseStatistics &&other) noexcept;
146433 DUCKDB_API BaseStatistics &
operator=(BaseStatistics &&) noexcept;
146434
146435public:
146439 static BaseStatistics CreateUnknown(LogicalType type);
146442 static BaseStatistics CreateEmpty(LogicalType type);
146443
146444 DUCKDB_API StatisticsType GetStatsType() const;
146445 DUCKDB_API static StatisticsType GetStatsType(const LogicalType &type);
146446
146447 DUCKDB_API bool CanHaveNull() const;
146448 DUCKDB_API bool CanHaveNoNull() const;
146449
146450 void SetDistinctCount(idx_t distinct_count);
146451
146452 bool IsConstant() const;
146453
146454 const LogicalType &GetType() const {
146455 return type;
146456 }
146457
146458 void Set(StatsInfo info);
146459 void CombineValidity(const BaseStatistics &left, const BaseStatistics &right);
146460 void CopyValidity(const BaseStatistics &stats);
146464 inline void SetHasNullFast() {
146465 has_null = true;
146466 }
146470 inline void SetHasNoNullFast() {
146471 has_no_null = true;
146472 }
146473 void SetHasNull();
146474 void SetHasNoNull();
146475
146476 void Merge(const BaseStatistics &other);
146477
146478 void Copy(const BaseStatistics &other);
146479
146480 unique_ptr<BaseStatistics> PushdownExtract(const StorageIndex &index) const;
146481 BaseStatistics Copy() const;
146482 unique_ptr<BaseStatistics> ToUnique() const;
146483 void CopyBase(const BaseStatistics &orig);
146484
146485 void Serialize(Serializer &serializer) const;
146486 static BaseStatistics Deserialize(Deserializer &deserializer);
146487
146489 void Verify(Vector &vector, const SelectionVector &sel, idx_t count, bool ignore_has_null = false) const;
146490 void Verify(Vector &vector, idx_t count) const;
146491
146492 string ToString() const;
146493
146494 idx_t GetDistinctCount();
146495 static BaseStatistics FromConstant(const Value &input);
146496
146497 template <class T>
146498 void UpdateNumericStats(T new_value) {
146499 D_ASSERT(GetStatsType() == StatisticsType::NUMERIC_STATS);
146500 NumericStats::Update(stats_union.numeric_data, new_value);
146501 }
146502
146503private:
146504 BaseStatistics();
146505 explicit BaseStatistics(LogicalType type);
146506
146507 static void Construct(BaseStatistics &stats, LogicalType type);
146508
146509 void InitializeUnknown();
146510 void InitializeEmpty();
146511
146512 static BaseStatistics CreateUnknownType(LogicalType type);
146513 static BaseStatistics CreateEmptyType(LogicalType type);
146514 static BaseStatistics FromConstantType(const Value &input);
146515
146516private:
146518 LogicalType type = LogicalType::INVALID;
146520 bool has_null;
146522 bool has_no_null;
146524 idx_t distinct_count;
146526 union {
146528 NumericStatsData numeric_data;
146530 StringStatsData string_data;
146532 GeometryStatsData geometry_data;
146534 VariantStatsData variant_data;
146535 } stats_union;
146537 unsafe_unique_array<BaseStatistics> child_stats;
146538};
146539
146540template <>
146541inline void BaseStatistics::UpdateNumericStats<interval_t>(interval_t new_value) {
146542}
146543template <>
146544inline void BaseStatistics::UpdateNumericStats<list_entry_t>(list_entry_t new_value) {
146545}
146546
146547}
146548
146549
146550
146551namespace duckdb {
146552
146553struct FunctionLocalState {
146554 DUCKDB_API virtual ~FunctionLocalState();
146555
146556 template <class TARGET>
146557 TARGET &Cast() {
146558 DynamicCastCheck<TARGET>(this);
146559 return reinterpret_cast<TARGET &>(*this);
146560 }
146561 template <class TARGET>
146562 const TARGET &Cast() const {
146563 DynamicCastCheck<TARGET>(this);
146564 return reinterpret_cast<const TARGET &>(*this);
146565 }
146566};
146567
146568struct ScalarFunctionInfo {
146569 DUCKDB_API virtual ~ScalarFunctionInfo();
146570
146571 template <class TARGET>
146572 TARGET &Cast() {
146573 DynamicCastCheck<TARGET>(this);
146574 return reinterpret_cast<TARGET &>(*this);
146575 }
146576 template <class TARGET>
146577 const TARGET &Cast() const {
146578 DynamicCastCheck<TARGET>(this);
146579 return reinterpret_cast<const TARGET &>(*this);
146580 }
146581};
146582
146583class Binder;
146584class BoundFunctionExpression;
146585class ScalarFunctionCatalogEntry;
146586
146587struct StatementProperties;
146588
146589struct FunctionStatisticsInput {
146590 FunctionStatisticsInput(BoundFunctionExpression &expr_p, optional_ptr<FunctionData> bind_data_p,
146591 vector<BaseStatistics> &child_stats_p, unique_ptr<Expression> *expr_ptr_p)
146592 : expr(expr_p), bind_data(bind_data_p), child_stats(child_stats_p), expr_ptr(expr_ptr_p) {
146593 }
146594
146595 BoundFunctionExpression &expr;
146596 optional_ptr<FunctionData> bind_data;
146597 vector<BaseStatistics> &child_stats;
146598 unique_ptr<Expression> *expr_ptr;
146599};
146600
146601struct FunctionModifiedDatabasesInput {
146602 FunctionModifiedDatabasesInput(optional_ptr<FunctionData> bind_data_p, StatementProperties &properties)
146603 : bind_data(bind_data_p), properties(properties) {
146604 }
146605
146606 optional_ptr<FunctionData> bind_data;
146607 StatementProperties &properties;
146608};
146609
146610struct FunctionBindExpressionInput {
146611 FunctionBindExpressionInput(ClientContext &context_p, optional_ptr<FunctionData> bind_data_p,
146612 vector<unique_ptr<Expression>> &children_p)
146613 : context(context_p), bind_data(bind_data_p), children(children_p) {
146614 }
146615
146616 ClientContext &context;
146617 optional_ptr<FunctionData> bind_data;
146618 vector<unique_ptr<Expression>> &children;
146619};
146620
146621struct ScalarFunctionBindInput {
146622 explicit ScalarFunctionBindInput(Binder &binder) : binder(binder) {
146623 }
146624
146625 Binder &binder;
146626};
146627
146629typedef std::function<void(DataChunk &, ExpressionState &, Vector &)>
scalar_function_t;
146631typedef unique_ptr<FunctionData> (*bind_scalar_function_t)(ClientContext &context, ScalarFunction &bound_function,
146632 vector<unique_ptr<Expression>> &arguments);
146633typedef unique_ptr<FunctionData> (*bind_scalar_function_extended_t)(ScalarFunctionBindInput &bind_input,
146634 ScalarFunction &bound_function,
146635 vector<unique_ptr<Expression>> &arguments);
146637typedef unique_ptr<FunctionLocalState> (*init_local_state_t)(ExpressionState &state,
146638 const BoundFunctionExpression &expr,
146639 FunctionData *bind_data);
146641typedef unique_ptr<BaseStatistics> (*function_statistics_t)(ClientContext &context, FunctionStatisticsInput &input);
146643typedef LogicalType (*bind_lambda_function_t)(ClientContext &context, const vector<LogicalType> &function_child_types,
146644 idx_t parameter_idx);
146645
146647typedef void (*get_modified_databases_t)(ClientContext &context, FunctionModifiedDatabasesInput &input);
146648
146649typedef void (*function_serialize_t)(Serializer &serializer, const optional_ptr<FunctionData> bind_data,
146650 const ScalarFunction &function);
146651typedef unique_ptr<FunctionData> (*function_deserialize_t)(Deserializer &deserializer, ScalarFunction &function);
146652
146654typedef unique_ptr<Expression> (*function_bind_expression_t)(FunctionBindExpressionInput &input);
146655
146656class ScalarFunction : public BaseScalarFunction {
146657public:
146658 DUCKDB_API ScalarFunction(string name, vector<LogicalType> arguments, LogicalType return_type,
146659 scalar_function_t function, bind_scalar_function_t bind = nullptr,
146660 bind_scalar_function_extended_t bind_extended = nullptr,
146661 function_statistics_t statistics = nullptr, init_local_state_t init_local_state = nullptr,
146662 LogicalType varargs = LogicalType(LogicalTypeId::INVALID),
146663 FunctionStability stability = FunctionStability::CONSISTENT,
146664 FunctionNullHandling null_handling = FunctionNullHandling::DEFAULT_NULL_HANDLING,
146665 bind_lambda_function_t bind_lambda = nullptr);
146666
146667 DUCKDB_API ScalarFunction(vector<LogicalType> arguments, LogicalType return_type, scalar_function_t function,
146668 bind_scalar_function_t bind = nullptr,
146669 bind_scalar_function_extended_t bind_extended = nullptr,
146670 function_statistics_t statistics = nullptr, init_local_state_t init_local_state = nullptr,
146671 LogicalType varargs = LogicalType(LogicalTypeId::INVALID),
146672 FunctionStability stability = FunctionStability::CONSISTENT,
146673 FunctionNullHandling null_handling = FunctionNullHandling::DEFAULT_NULL_HANDLING,
146674 bind_lambda_function_t bind_lambda = nullptr);
146675
146676
146677
146678 bool HasFunctionCallback() const { return function != nullptr; }
146680 void SetFunctionCallback(scalar_function_t callback) { function = std::move(callback); }
146681
146682 bool HasBindCallback()
const {
return bind !=
nullptr; };
146684 void SetBindCallback(bind_scalar_function_t callback) {
bind = callback; }
146685
146686 bool HasBindExtendedCallback() const { return bind_extended != nullptr; }
146687 bind_scalar_function_extended_t GetBindExtendedCallback() const { return bind_extended; }
146688 void SetBindExtendedCallback(bind_scalar_function_extended_t callback) { bind_extended = callback; }
146689
146690 bool HasBindLambdaCallback() const { return bind_lambda != nullptr; }
146692 void SetBindLambdaCallback(bind_lambda_function_t callback) { bind_lambda = callback; }
146693
146694 bool HasBindExpressionCallback() const { return bind_expression != nullptr; }
146696 void SetBindExpressionCallback(function_bind_expression_t callback) { bind_expression = callback; }
146697
146698 bool HasInitStateCallback() const { return init_local_state != nullptr; }
146700 void SetInitStateCallback(init_local_state_t callback) { init_local_state = callback; }
146701
146702 bool HasStatisticsCallback() const { return statistics != nullptr; }
146704 void SetStatisticsCallback(function_statistics_t callback) { statistics = callback; }
146705
146706 bool HasModifiedDatabasesCallback() const { return get_modified_databases != nullptr; }
146708 void SetModifiedDatabasesCallback(get_modified_databases_t callback) { get_modified_databases = callback; }
146709
146710 bool HasSerializationCallbacks()
const {
return serialize !=
nullptr &&
deserialize !=
nullptr; }
146711 void SetSerializeCallback(function_serialize_t callback) {
serialize = callback; }
146712 void SetDeserializeCallback(function_deserialize_t callback) {
deserialize = callback; }
146713 function_serialize_t GetSerializeCallback()
const {
return serialize; }
146714 function_deserialize_t GetDeserializeCallback()
const {
return deserialize; }
146715
146716
146717 bool HasExtraFunctionInfo() const {
146718 return function_info != nullptr;
146719 }
146720 ScalarFunctionInfo &GetExtraFunctionInfo() const {
146721 D_ASSERT(function_info.get());
146722 return *function_info;
146723 }
146724 void SetExtraFunctionInfo(shared_ptr<ScalarFunctionInfo> info) {
146725 function_info = std::move(info);
146726 }
146727 template <class T, class... ARGS>
146728 void SetExtraFunctionInfo(ARGS &&... args) {
146729 function_info = make_shared_ptr<T>(std::forward<ARGS>(args)...);
146730 }
146731
146732public:
146738 bind_scalar_function_extended_t bind_extended = nullptr;
146749
146753 shared_ptr<ScalarFunctionInfo> function_info;
146754
146755public:
146756 DUCKDB_API
bool operator==(
const ScalarFunction &rhs)
const;
146757 DUCKDB_API
bool operator!=(
const ScalarFunction &rhs)
const;
146758
146759 DUCKDB_API bool Equal(const ScalarFunction &rhs) const;
146760
146761public:
146762 DUCKDB_API static void NopFunction(DataChunk &input, ExpressionState &state, Vector &result);
146763
146764 template <class TA, class TR, class OP>
146765 static void UnaryFunction(DataChunk &input, ExpressionState &state, Vector &result) {
146766 D_ASSERT(input.ColumnCount() >= 1);
146767 UnaryExecutor::Execute<TA, TR, OP>(input.
data[0], result, input.size());
146768 }
146769
146770 template <class TA, class TB, class TR, class OP>
146771 static void BinaryFunction(DataChunk &input, ExpressionState &state, Vector &result) {
146772 D_ASSERT(input.ColumnCount() == 2);
146773 BinaryExecutor::ExecuteStandard<TA, TB, TR, OP>(input.
data[0], input.
data[1], result, input.size());
146774 }
146775
146776 template <class TA, class TB, class TC, class TR, class OP>
146777 static void TernaryFunction(DataChunk &input, ExpressionState &state, Vector &result) {
146778 D_ASSERT(input.ColumnCount() == 3);
146779 TernaryExecutor::ExecuteStandard<TA, TB, TC, TR, OP>(input.
data[0], input.
data[1], input.
data[2], result,
146780 input.size());
146781 }
146782
146783public:
146784 template <class OP>
146787 switch (type.id()) {
146788 case LogicalTypeId::TINYINT:
146789 function = &ScalarFunction::UnaryFunction<int8_t, int8_t, OP>;
146790 break;
146791 case LogicalTypeId::SMALLINT:
146792 function = &ScalarFunction::UnaryFunction<int16_t, int16_t, OP>;
146793 break;
146794 case LogicalTypeId::INTEGER:
146795 function = &ScalarFunction::UnaryFunction<int32_t, int32_t, OP>;
146796 break;
146797 case LogicalTypeId::BIGINT:
146798 function = &ScalarFunction::UnaryFunction<int64_t, int64_t, OP>;
146799 break;
146800 case LogicalTypeId::UTINYINT:
146801 function = &ScalarFunction::UnaryFunction<uint8_t, uint8_t, OP>;
146802 break;
146803 case LogicalTypeId::USMALLINT:
146804 function = &ScalarFunction::UnaryFunction<uint16_t, uint16_t, OP>;
146805 break;
146806 case LogicalTypeId::UINTEGER:
146807 function = &ScalarFunction::UnaryFunction<uint32_t, uint32_t, OP>;
146808 break;
146809 case LogicalTypeId::UBIGINT:
146810 function = &ScalarFunction::UnaryFunction<uint64_t, uint64_t, OP>;
146811 break;
146812 case LogicalTypeId::HUGEINT:
146813 function = &ScalarFunction::UnaryFunction<hugeint_t, hugeint_t, OP>;
146814 break;
146815 case LogicalTypeId::UHUGEINT:
146816 function = &ScalarFunction::UnaryFunction<uhugeint_t, uhugeint_t, OP>;
146817 break;
146818 case LogicalTypeId::FLOAT:
146819 function = &ScalarFunction::UnaryFunction<float, float, OP>;
146820 break;
146821 case LogicalTypeId::DOUBLE:
146822 function = &ScalarFunction::UnaryFunction<double, double, OP>;
146823 break;
146824 default:
146825 throw InternalException("Unimplemented type for GetScalarUnaryFunction");
146826 }
146827 return function;
146828 }
146829
146830 template <class TR, class OP>
146831 static scalar_function_t GetScalarUnaryFunctionFixedReturn(
const LogicalType &type) {
146833 switch (type.id()) {
146834 case LogicalTypeId::TINYINT:
146835 function = &ScalarFunction::UnaryFunction<int8_t, TR, OP>;
146836 break;
146837 case LogicalTypeId::SMALLINT:
146838 function = &ScalarFunction::UnaryFunction<int16_t, TR, OP>;
146839 break;
146840 case LogicalTypeId::INTEGER:
146841 function = &ScalarFunction::UnaryFunction<int32_t, TR, OP>;
146842 break;
146843 case LogicalTypeId::BIGINT:
146844 function = &ScalarFunction::UnaryFunction<int64_t, TR, OP>;
146845 break;
146846 case LogicalTypeId::UTINYINT:
146847 function = &ScalarFunction::UnaryFunction<uint8_t, TR, OP>;
146848 break;
146849 case LogicalTypeId::USMALLINT:
146850 function = &ScalarFunction::UnaryFunction<uint16_t, TR, OP>;
146851 break;
146852 case LogicalTypeId::UINTEGER:
146853 function = &ScalarFunction::UnaryFunction<uint32_t, TR, OP>;
146854 break;
146855 case LogicalTypeId::UBIGINT:
146856 function = &ScalarFunction::UnaryFunction<uint64_t, TR, OP>;
146857 break;
146858 case LogicalTypeId::HUGEINT:
146859 function = &ScalarFunction::UnaryFunction<hugeint_t, TR, OP>;
146860 break;
146861 case LogicalTypeId::UHUGEINT:
146862 function = &ScalarFunction::UnaryFunction<uhugeint_t, TR, OP>;
146863 break;
146864 case LogicalTypeId::FLOAT:
146865 function = &ScalarFunction::UnaryFunction<float, TR, OP>;
146866 break;
146867 case LogicalTypeId::DOUBLE:
146868 function = &ScalarFunction::UnaryFunction<double, TR, OP>;
146869 break;
146870 default:
146871 throw InternalException("Unimplemented type for GetScalarUnaryFunctionFixedReturn");
146872 }
146873 return function;
146874 }
146875};
146876
146877}
146878
146879
146880
146881
146882
146883
146884
146885
146886
146887
146888
146889
146890
146891
146892
146893
146894
146895
146896
146897
146898
146899#include <array>
146900
146901namespace duckdb {
146902using std::array;
146903}
146904
146905
146906
146907
146908
146909
146910
146911
146912
146913
146914
146915
146916
146917
146918
146919
146920
146921
146922
146923
146924
146925
146926
146927
146928
146929
146930
146931
146932
146933
146934
146935
146936
146937
146938
146939
146940
146941
146942namespace duckdb {
146943
146944class NodeStatistics {
146945public:
146946 NodeStatistics() : has_estimated_cardinality(false), has_max_cardinality(false) {
146947 }
146948 explicit NodeStatistics(idx_t estimated_cardinality)
146949 : has_estimated_cardinality(true), estimated_cardinality(estimated_cardinality), has_max_cardinality(false) {
146950 }
146951 NodeStatistics(idx_t estimated_cardinality, idx_t max_cardinality)
146952 : has_estimated_cardinality(true), estimated_cardinality(estimated_cardinality), has_max_cardinality(true),
146953 max_cardinality(max_cardinality) {
146954 }
146955
146957 bool has_estimated_cardinality;
146959 idx_t estimated_cardinality;
146961 bool has_max_cardinality;
146963 idx_t max_cardinality;
146964};
146965
146966}
146967
146968
146969namespace duckdb {
146970
146971enum class AggregateType :
uint8_t { NON_DISTINCT = 1, DISTINCT = 2 };
146978
146979class BoundAggregateExpression;
146980
146981struct AggregateInputData {
146982 AggregateInputData(optional_ptr<FunctionData> bind_data_p, ArenaAllocator &allocator_p,
146983 AggregateCombineType combine_type_p = AggregateCombineType::PRESERVE_INPUT)
146984 : bind_data(bind_data_p), allocator(allocator_p), combine_type(combine_type_p) {
146985 }
146986 optional_ptr<FunctionData> bind_data;
146987 ArenaAllocator &allocator;
146989};
146990
146991struct AggregateUnaryInput {
146992 AggregateUnaryInput(AggregateInputData &input_p, ValidityMask &input_mask_p)
146993 : input(input_p), input_mask(input_mask_p), input_idx(0) {
146994 }
146995
146996 AggregateInputData &input;
146997 ValidityMask &input_mask;
146999
147000 inline bool RowIsValid() {
147001 return input_mask.RowIsValid(input_idx);
147002 }
147003};
147004
147005struct AggregateBinaryInput {
147006 AggregateBinaryInput(AggregateInputData &input_p, ValidityMask &left_mask_p, ValidityMask &right_mask_p)
147007 : input(input_p), left_mask(left_mask_p), right_mask(right_mask_p) {
147008 }
147009
147010 AggregateInputData &input;
147011 ValidityMask &left_mask;
147012 ValidityMask &right_mask;
147015};
147016
147017struct AggregateFinalizeData {
147018 AggregateFinalizeData(Vector &result_p, AggregateInputData &input_p)
147019 : result(result_p), input(input_p), result_idx(0) {
147020 }
147021
147022 Vector &result;
147023 AggregateInputData &input;
147025
147026 inline void ReturnNull() {
147027 switch (result.GetVectorType()) {
147028 case VectorType::FLAT_VECTOR:
147029 FlatVector::SetNull(result, result_idx, true);
147030 break;
147031 case VectorType::CONSTANT_VECTOR:
147032 ConstantVector::SetNull(result, true);
147033 break;
147034 default:
147035 throw InternalException("Invalid result vector type for aggregate");
147036 }
147037 }
147038
147039 inline string_t ReturnString(string_t value) {
147040 return StringVector::AddStringOrBlob(result, value);
147041 }
147042};
147043
147044struct AggregateStatisticsInput {
147045 AggregateStatisticsInput(optional_ptr<FunctionData> bind_data_p, vector<BaseStatistics> &child_stats_p,
147046 optional_ptr<NodeStatistics> node_stats_p)
147047 : bind_data(bind_data_p), child_stats(child_stats_p), node_stats(node_stats_p) {
147048 }
147049
147050 optional_ptr<FunctionData> bind_data;
147051 vector<BaseStatistics> &child_stats;
147052 optional_ptr<NodeStatistics> node_stats;
147053};
147054
147055}
147056
147057
147058namespace duckdb {
147059
147060
147061struct AggregateInputData;
147062
147063
147064struct FrameBounds {
147065 FrameBounds() : start(0), end(0) {};
147066 FrameBounds(idx_t start, idx_t end) : start(start), end(end) {};
147069};
147070
147071
147072using SubFrames = vector<FrameBounds>;
147073
147074class AggregateExecutor {
147075private:
147076#ifndef DUCKDB_SMALLER_BINARY
147077 template <class STATE_TYPE, class OP>
147078 static inline void NullaryFlatLoop(STATE_TYPE **__restrict states, AggregateInputData &aggr_input_data,
147079 idx_t count) {
147080 for (idx_t i = 0; i < count; i++) {
147081 OP::template Operation<STATE_TYPE, OP>(*states[i], aggr_input_data, i);
147082 }
147083 }
147084#endif
147085
147086 template <class STATE_TYPE, class OP>
147087 static inline void NullaryScatterLoop(STATE_TYPE *__restrict const *__restrict const states,
147088 AggregateInputData &aggr_input_data, const SelectionVector &ssel,
147089 const idx_t count) {
147090 if (ssel.IsSet()) {
147091 for (idx_t i = 0; i < count; i++) {
147092 auto sidx = ssel.get_index_unsafe(i);
147093 OP::template Operation<STATE_TYPE, OP>(*states[sidx], aggr_input_data, sidx);
147094 }
147095 } else {
147096 for (idx_t i = 0; i < count; i++) {
147097 OP::template Operation<STATE_TYPE, OP>(*states[i], aggr_input_data, i);
147098 }
147099 }
147100 }
147101
147102#ifndef DUCKDB_SMALLER_BINARY
147103 template <class STATE_TYPE, class INPUT_TYPE, class OP>
147104 static inline void UnaryFlatLoop(const INPUT_TYPE *__restrict idata, AggregateInputData &aggr_input_data,
147105 STATE_TYPE **__restrict states, ValidityMask &mask, idx_t count) {
147106 if (OP::IgnoreNull() && !
mask.AllValid()) {
147107 AggregateUnaryInput input(aggr_input_data, mask);
147108 auto &base_idx = input.input_idx;
147109 base_idx = 0;
147110 auto entry_count = ValidityMask::EntryCount(count);
147111 for (idx_t entry_idx = 0; entry_idx < entry_count; entry_idx++) {
147112 auto validity_entry =
mask.GetValidityEntry(entry_idx);
147113 idx_t next = MinValue<idx_t>(base_idx + ValidityMask::BITS_PER_VALUE, count);
147114 if (ValidityMask::AllValid(validity_entry)) {
147115
147116 for (; base_idx < next; base_idx++) {
147117 OP::template Operation<INPUT_TYPE, STATE_TYPE, OP>(*states[base_idx], idata[base_idx], input);
147118 }
147119 } else if (ValidityMask::NoneValid(validity_entry)) {
147120
147121 base_idx = next;
147122 continue;
147123 } else {
147124
147125 idx_t start = base_idx;
147126 for (; base_idx < next; base_idx++) {
147127 if (ValidityMask::RowIsValid(validity_entry, base_idx - start)) {
147128 OP::template Operation<INPUT_TYPE, STATE_TYPE, OP>(*states[base_idx], idata[base_idx],
147129 input);
147130 }
147131 }
147132 }
147133 }
147134 } else {
147135 AggregateUnaryInput input(aggr_input_data, mask);
147136 auto &i = input.input_idx;
147137 for (i = 0; i < count; i++) {
147138 OP::template Operation<INPUT_TYPE, STATE_TYPE, OP>(*states[i], idata[i], input);
147139 }
147140 }
147141 }
147142#endif
147143
147144#ifndef DUCKDB_SMALLER_BINARY
147145 template <class STATE_TYPE, class INPUT_TYPE, class OP, bool HAS_ISEL, bool HAS_SSEL>
147146#else
147147 template <class STATE_TYPE, class INPUT_TYPE, class OP>
147148#endif
147149 static inline void UnaryScatterLoop(const INPUT_TYPE *__restrict idata, AggregateInputData &aggr_input_data,
147150 STATE_TYPE **__restrict states, const SelectionVector &isel,
147151 const SelectionVector &ssel, ValidityMask &mask, idx_t count) {
147152#ifdef DUCKDB_SMALLER_BINARY
147153 const auto HAS_ISEL = isel.IsSet();
147154 const auto HAS_SSEL = ssel.IsSet();
147155#endif
147156 if (OP::IgnoreNull() && !
mask.AllValid()) {
147157
147158 AggregateUnaryInput input(aggr_input_data, mask);
147159 for (idx_t i = 0; i < count; i++) {
147160 input.input_idx = HAS_ISEL ? isel.get_index_unsafe(i) : i;
147161 auto sidx = HAS_SSEL ? ssel.get_index_unsafe(i) : i;
147162 if (
mask.RowIsValidUnsafe(input.input_idx)) {
147163 OP::template Operation<INPUT_TYPE, STATE_TYPE, OP>(*states[sidx], idata[input.input_idx], input);
147164 }
147165 }
147166 } else {
147167
147168 AggregateUnaryInput input(aggr_input_data, mask);
147169 for (idx_t i = 0; i < count; i++) {
147170 input.input_idx = HAS_ISEL ? isel.get_index_unsafe(i) : i;
147171 auto sidx = HAS_SSEL ? ssel.get_index_unsafe(i) : i;
147172 OP::template Operation<INPUT_TYPE, STATE_TYPE, OP>(*states[sidx], idata[input.input_idx], input);
147173 }
147174 }
147175 }
147176
147177#ifndef DUCKDB_SMALLER_BINARY
147178 template <class STATE_TYPE, class INPUT_TYPE, class OP>
147179 static inline void UnaryFlatUpdateLoop(const INPUT_TYPE *__restrict idata, AggregateInputData &aggr_input_data,
147180 STATE_TYPE *__restrict state, idx_t count, ValidityMask &mask) {
147181 AggregateUnaryInput input(aggr_input_data, mask);
147182 auto &base_idx = input.input_idx;
147183 base_idx = 0;
147184 auto entry_count = ValidityMask::EntryCount(count);
147185 for (idx_t entry_idx = 0; entry_idx < entry_count; entry_idx++) {
147186 auto validity_entry =
mask.GetValidityEntry(entry_idx);
147187 idx_t next = MinValue<idx_t>(base_idx + ValidityMask::BITS_PER_VALUE, count);
147188 if (!OP::IgnoreNull() || ValidityMask::AllValid(validity_entry)) {
147189
147190 for (; base_idx < next; base_idx++) {
147191 OP::template Operation<INPUT_TYPE, STATE_TYPE, OP>(*state, idata[base_idx], input);
147192 }
147193 } else if (ValidityMask::NoneValid(validity_entry)) {
147194
147195 base_idx = next;
147196 continue;
147197 } else {
147198
147199 idx_t start = base_idx;
147200 for (; base_idx < next; base_idx++) {
147201 if (ValidityMask::RowIsValid(validity_entry, base_idx - start)) {
147202 OP::template Operation<INPUT_TYPE, STATE_TYPE, OP>(*state, idata[base_idx], input);
147203 }
147204 }
147205 }
147206 }
147207 }
147208#endif
147209
147210 template <class STATE_TYPE, class INPUT_TYPE, class OP>
147211 static inline void UnaryUpdateLoop(const INPUT_TYPE *__restrict idata, AggregateInputData &aggr_input_data,
147212 STATE_TYPE *__restrict state, idx_t count, ValidityMask &mask,
147213 const SelectionVector &__restrict sel_vector) {
147214 AggregateUnaryInput input(aggr_input_data, mask);
147215 if (OP::IgnoreNull() && !
mask.AllValid()) {
147216
147217 for (idx_t i = 0; i < count; i++) {
147218 input.input_idx = sel_vector.get_index(i);
147219 if (
mask.RowIsValid(input.input_idx)) {
147220 OP::template Operation<INPUT_TYPE, STATE_TYPE, OP>(*state, idata[input.input_idx], input);
147221 }
147222 }
147223 } else {
147224
147225 for (idx_t i = 0; i < count; i++) {
147226 input.input_idx = sel_vector.get_index(i);
147227 OP::template Operation<INPUT_TYPE, STATE_TYPE, OP>(*state, idata[input.input_idx], input);
147228 }
147229 }
147230 }
147231
147232 template <class STATE_TYPE, class A_TYPE, class B_TYPE, class OP>
147233 static inline void BinaryScatterLoop(const A_TYPE *__restrict adata, AggregateInputData &aggr_input_data,
147234 const B_TYPE *__restrict bdata, STATE_TYPE **__restrict states, idx_t count,
147235 const SelectionVector &asel, const SelectionVector &bsel,
147236 const SelectionVector &ssel, ValidityMask &avalidity,
147237 ValidityMask &bvalidity) {
147238 AggregateBinaryInput input(aggr_input_data, avalidity, bvalidity);
147239 if (OP::IgnoreNull() && (!avalidity.AllValid() || !bvalidity.AllValid())) {
147240
147241 for (idx_t i = 0; i < count; i++) {
147242 input.lidx = asel.get_index(i);
147243 input.ridx = bsel.get_index(i);
147244 auto sidx = ssel.get_index(i);
147245 if (avalidity.RowIsValid(input.lidx) && bvalidity.RowIsValid(input.ridx)) {
147246 OP::template Operation<A_TYPE, B_TYPE, STATE_TYPE, OP>(*states[sidx], adata[input.lidx],
147247 bdata[input.ridx], input);
147248 }
147249 }
147250 } else {
147251
147252 for (idx_t i = 0; i < count; i++) {
147253 input.lidx = asel.get_index(i);
147254 input.ridx = bsel.get_index(i);
147255 auto sidx = ssel.get_index(i);
147256 OP::template Operation<A_TYPE, B_TYPE, STATE_TYPE, OP>(*states[sidx], adata[input.lidx],
147257 bdata[input.ridx], input);
147258 }
147259 }
147260 }
147261
147262 template <class STATE_TYPE, class A_TYPE, class B_TYPE, class OP>
147263 static inline void BinaryUpdateLoop(const A_TYPE *__restrict adata, AggregateInputData &aggr_input_data,
147264 const B_TYPE *__restrict bdata, STATE_TYPE *__restrict state, idx_t count,
147265 const SelectionVector &asel, const SelectionVector &bsel,
147266 ValidityMask &avalidity, ValidityMask &bvalidity) {
147267 AggregateBinaryInput input(aggr_input_data, avalidity, bvalidity);
147268 if (OP::IgnoreNull() && (!avalidity.AllValid() || !bvalidity.AllValid())) {
147269
147270 for (idx_t i = 0; i < count; i++) {
147271 input.lidx = asel.get_index(i);
147272 input.ridx = bsel.get_index(i);
147273 if (avalidity.RowIsValid(input.lidx) && bvalidity.RowIsValid(input.ridx)) {
147274 OP::template Operation<A_TYPE, B_TYPE, STATE_TYPE, OP>(*state, adata[input.lidx], bdata[input.ridx],
147275 input);
147276 }
147277 }
147278 } else {
147279
147280 for (idx_t i = 0; i < count; i++) {
147281 input.lidx = asel.get_index(i);
147282 input.ridx = bsel.get_index(i);
147283 OP::template Operation<A_TYPE, B_TYPE, STATE_TYPE, OP>(*state, adata[input.lidx], bdata[input.ridx],
147284 input);
147285 }
147286 }
147287 }
147288
147289public:
147290 template <class STATE_TYPE, class OP>
147291 static void NullaryScatter(Vector &states, AggregateInputData &aggr_input_data, idx_t count) {
147292 if (states.GetVectorType() == VectorType::CONSTANT_VECTOR) {
147293 auto sdata = ConstantVector::GetData<STATE_TYPE *>(states);
147294 OP::template ConstantOperation<STATE_TYPE, OP>(**sdata, aggr_input_data, count);
147295#ifndef DUCKDB_SMALLER_BINARY
147296 } else if (states.GetVectorType() == VectorType::FLAT_VECTOR) {
147297 auto sdata = FlatVector::GetData<STATE_TYPE *>(states);
147298 NullaryFlatLoop<STATE_TYPE, OP>(sdata, aggr_input_data, count);
147299#endif
147300 } else {
147301 UnifiedVectorFormat sdata;
147302 states.ToUnifiedFormat(count, sdata);
147303 NullaryScatterLoop<STATE_TYPE, OP>((STATE_TYPE **)sdata.data, aggr_input_data, *sdata.sel, count);
147304 }
147305 }
147306
147307 template <class STATE_TYPE, class OP>
147308 static void NullaryUpdate(data_ptr_t state, AggregateInputData &aggr_input_data, idx_t count) {
147309 OP::template ConstantOperation<STATE_TYPE, OP>(*reinterpret_cast<STATE_TYPE *>(state), aggr_input_data, count);
147310 }
147311
147312 template <class STATE_TYPE, class INPUT_TYPE, class OP>
147313 static void UnaryScatter(Vector &input, Vector &states, AggregateInputData &aggr_input_data, idx_t count) {
147314 if (input.GetVectorType() == VectorType::CONSTANT_VECTOR &&
147315 states.GetVectorType() == VectorType::CONSTANT_VECTOR) {
147316 if (OP::IgnoreNull() && ConstantVector::IsNull(input)) {
147317
147318 return;
147319 }
147320
147321 auto idata = ConstantVector::GetData<INPUT_TYPE>(input);
147322 auto sdata = ConstantVector::GetData<STATE_TYPE *>(states);
147323 AggregateUnaryInput input_data(aggr_input_data, ConstantVector::Validity(input));
147324 OP::template ConstantOperation<INPUT_TYPE, STATE_TYPE, OP>(**sdata, *idata, input_data, count);
147325#ifndef DUCKDB_SMALLER_BINARY
147326 } else if (input.GetVectorType() == VectorType::FLAT_VECTOR &&
147327 states.GetVectorType() == VectorType::FLAT_VECTOR) {
147328 auto idata = FlatVector::GetData<INPUT_TYPE>(input);
147329 auto sdata = FlatVector::GetData<STATE_TYPE *>(states);
147330 UnaryFlatLoop<STATE_TYPE, INPUT_TYPE, OP>(idata, aggr_input_data, sdata, FlatVector::Validity(input),
147331 count);
147332#endif
147333 } else {
147334 UnifiedVectorFormat idata, sdata;
147335 input.ToUnifiedFormat(count, idata);
147336 states.ToUnifiedFormat(count, sdata);
147337#ifdef DUCKDB_SMALLER_BINARY
147338 UnaryScatterLoop<STATE_TYPE, INPUT_TYPE, OP>(UnifiedVectorFormat::GetData<INPUT_TYPE>(idata),
147339 aggr_input_data, (STATE_TYPE **)sdata.data, *idata.sel,
147340 *sdata.sel, idata.validity, count);
147341#else
147342 if (idata.sel->IsSet()) {
147343 if (sdata.sel->IsSet()) {
147344 UnaryScatterLoop<STATE_TYPE, INPUT_TYPE, OP, true, true>(
147345 UnifiedVectorFormat::GetData<INPUT_TYPE>(idata), aggr_input_data, (STATE_TYPE **)sdata.data,
147346 *idata.sel, *sdata.sel, idata.validity, count);
147347 } else {
147348 UnaryScatterLoop<STATE_TYPE, INPUT_TYPE, OP, true, false>(
147349 UnifiedVectorFormat::GetData<INPUT_TYPE>(idata), aggr_input_data, (STATE_TYPE **)sdata.data,
147350 *idata.sel, *sdata.sel, idata.validity, count);
147351 }
147352 } else {
147353 if (sdata.sel->IsSet()) {
147354 UnaryScatterLoop<STATE_TYPE, INPUT_TYPE, OP, false, true>(
147355 UnifiedVectorFormat::GetData<INPUT_TYPE>(idata), aggr_input_data, (STATE_TYPE **)sdata.data,
147356 *idata.sel, *sdata.sel, idata.validity, count);
147357 } else {
147358 UnaryScatterLoop<STATE_TYPE, INPUT_TYPE, OP, false, false>(
147359 UnifiedVectorFormat::GetData<INPUT_TYPE>(idata), aggr_input_data, (STATE_TYPE **)sdata.data,
147360 *idata.sel, *sdata.sel, idata.validity, count);
147361 }
147362 }
147363
147364#endif
147365 }
147366 }
147367
147368 template <class STATE_TYPE, class INPUT_TYPE, class OP>
147369 static void UnaryUpdate(Vector &input, AggregateInputData &aggr_input_data, data_ptr_t state, idx_t count) {
147370 switch (input.GetVectorType()) {
147371 case VectorType::CONSTANT_VECTOR: {
147372 if (OP::IgnoreNull() && ConstantVector::IsNull(input)) {
147373 return;
147374 }
147375 auto idata = ConstantVector::GetData<INPUT_TYPE>(input);
147376 AggregateUnaryInput input_data(aggr_input_data, ConstantVector::Validity(input));
147377 OP::template ConstantOperation<INPUT_TYPE, STATE_TYPE, OP>(*reinterpret_cast<STATE_TYPE *>(state), *idata,
147378 input_data, count);
147379 break;
147380 }
147381#ifndef DUCKDB_SMALLER_BINARY
147382 case VectorType::FLAT_VECTOR: {
147383 auto idata = FlatVector::GetData<INPUT_TYPE>(input);
147384 UnaryFlatUpdateLoop<STATE_TYPE, INPUT_TYPE, OP>(idata, aggr_input_data, (STATE_TYPE *)state, count,
147385 FlatVector::Validity(input));
147386 break;
147387 }
147388#endif
147389 default: {
147390 UnifiedVectorFormat idata;
147391 input.ToUnifiedFormat(count, idata);
147392 UnaryUpdateLoop<STATE_TYPE, INPUT_TYPE, OP>(UnifiedVectorFormat::GetData<INPUT_TYPE>(idata),
147393 aggr_input_data, (STATE_TYPE *)state, count, idata.validity,
147394 *idata.sel);
147395 break;
147396 }
147397 }
147398 }
147399
147400 template <class STATE_TYPE, class A_TYPE, class B_TYPE, class OP>
147401 static void BinaryScatter(AggregateInputData &aggr_input_data, Vector &a, Vector &b, Vector &states, idx_t count) {
147402 UnifiedVectorFormat adata, bdata, sdata;
147403
147404 a.ToUnifiedFormat(count, adata);
147405 b.ToUnifiedFormat(count, bdata);
147406 states.ToUnifiedFormat(count, sdata);
147407
147408 BinaryScatterLoop<STATE_TYPE, A_TYPE, B_TYPE, OP>(
147409 UnifiedVectorFormat::GetData<A_TYPE>(adata), aggr_input_data, UnifiedVectorFormat::GetData<B_TYPE>(bdata),
147410 (STATE_TYPE **)sdata.data, count, *adata.sel, *bdata.sel, *sdata.sel, adata.validity, bdata.validity);
147411 }
147412
147413 template <class STATE_TYPE, class A_TYPE, class B_TYPE, class OP>
147414 static void BinaryUpdate(AggregateInputData &aggr_input_data, Vector &a, Vector &b, data_ptr_t state, idx_t count) {
147415 UnifiedVectorFormat adata, bdata;
147416
147417 a.ToUnifiedFormat(count, adata);
147418 b.ToUnifiedFormat(count, bdata);
147419
147420 BinaryUpdateLoop<STATE_TYPE, A_TYPE, B_TYPE, OP>(
147421 UnifiedVectorFormat::GetData<A_TYPE>(adata), aggr_input_data, UnifiedVectorFormat::GetData<B_TYPE>(bdata),
147422 (STATE_TYPE *)state, count, *adata.sel, *bdata.sel, adata.validity, bdata.validity);
147423 }
147424
147425 template <class STATE_TYPE, class OP>
147426 static void Combine(Vector &source, Vector &target, AggregateInputData &aggr_input_data, idx_t count) {
147427 D_ASSERT(source.GetType().id() == LogicalTypeId::POINTER && target.GetType().id() == LogicalTypeId::POINTER);
147428 auto sdata = FlatVector::GetData<const STATE_TYPE *>(source);
147429 auto tdata = FlatVector::GetData<STATE_TYPE *>(target);
147430
147431 for (idx_t i = 0; i < count; i++) {
147432 OP::template Combine<STATE_TYPE, OP>(*sdata[i], *tdata[i], aggr_input_data);
147433 }
147434 }
147435
147436 template <class STATE_TYPE, class RESULT_TYPE, class OP>
147437 static void Finalize(Vector &states, AggregateInputData &aggr_input_data, Vector &result, idx_t count,
147438 idx_t offset) {
147439 if (states.GetVectorType() == VectorType::CONSTANT_VECTOR) {
147440 result.SetVectorType(VectorType::CONSTANT_VECTOR);
147441
147442 auto sdata = ConstantVector::GetData<STATE_TYPE *>(states);
147443 auto rdata = ConstantVector::GetData<RESULT_TYPE>(result);
147444 AggregateFinalizeData finalize_data(result, aggr_input_data);
147445 OP::template Finalize<RESULT_TYPE, STATE_TYPE>(**sdata, *rdata, finalize_data);
147446 } else {
147447 D_ASSERT(states.GetVectorType() == VectorType::FLAT_VECTOR);
147448 result.SetVectorType(VectorType::FLAT_VECTOR);
147449
147450 auto sdata = FlatVector::GetData<STATE_TYPE *>(states);
147451 auto rdata = FlatVector::GetData<RESULT_TYPE>(result);
147452 AggregateFinalizeData finalize_data(result, aggr_input_data);
147453 for (idx_t i = 0; i < count; i++) {
147454 finalize_data.result_idx = i + offset;
147455 OP::template Finalize<RESULT_TYPE, STATE_TYPE>(*sdata[i], rdata[finalize_data.result_idx],
147456 finalize_data);
147457 }
147458 }
147459 }
147460
147461 template <class STATE_TYPE, class OP>
147462 static void VoidFinalize(Vector &states, AggregateInputData &aggr_input_data, Vector &result, idx_t count,
147463 idx_t offset) {
147464 if (states.GetVectorType() == VectorType::CONSTANT_VECTOR) {
147465 result.SetVectorType(VectorType::CONSTANT_VECTOR);
147466
147467 auto sdata = ConstantVector::GetData<STATE_TYPE *>(states);
147468 AggregateFinalizeData finalize_data(result, aggr_input_data);
147469 OP::template Finalize<STATE_TYPE>(**sdata, finalize_data);
147470 } else {
147471 D_ASSERT(states.GetVectorType() == VectorType::FLAT_VECTOR);
147472 result.SetVectorType(VectorType::FLAT_VECTOR);
147473
147474 auto sdata = FlatVector::GetData<STATE_TYPE *>(states);
147475 AggregateFinalizeData finalize_data(result, aggr_input_data);
147476 for (idx_t i = 0; i < count; i++) {
147477 finalize_data.result_idx = i + offset;
147478 OP::template Finalize<STATE_TYPE>(*sdata[i], finalize_data);
147479 }
147480 }
147481 }
147482
147483 template <typename OP>
147484 static void IntersectFrames(const SubFrames &lefts, const SubFrames &rights, OP &op) {
147485 const auto cover_start = MinValue(rights[0].start, lefts[0].start);
147486 const auto cover_end = MaxValue(rights.back().end, lefts.back().end);
147487 const FrameBounds last(cover_end, cover_end);
147488
147489
147492 for (auto i = cover_start; i < cover_end;) {
147494
147495
147496 auto left = &last;
147497 if (l < lefts.size()) {
147498 left = &lefts[l];
147499 overlap |=
uint8_t(left->start <= i && i < left->end) << 0;
147500 }
147501
147502
147503 auto right = &last;
147504 if (r < rights.size()) {
147505 right = &rights[r];
147506 overlap |=
uint8_t(right->start <= i && i < right->end) << 1;
147507 }
147508
147509 auto limit = i;
147510 switch (overlap) {
147511 case 0x00:
147512
147513 limit = MinValue(right->start, left->start);
147514 op.Neither(i, limit);
147515 break;
147516 case 0x01:
147517
147518 limit = MinValue(left->end, right->start);
147519 op.Left(i, limit);
147520 break;
147521 case 0x02:
147522
147523 limit = MinValue(right->end, left->start);
147524 op.Right(i, limit);
147525 break;
147526 case 0x03:
147527 default:
147528 D_ASSERT(overlap == 0x03);
147529
147530 limit = MinValue(right->end, left->end);
147531 op.Both(i, limit);
147532 break;
147533 }
147534
147535
147536 i = limit;
147537 l += (i == left->end);
147538 r += (i == right->end);
147539 }
147540 }
147541
147542 template <class STATE_TYPE, class OP>
147543 static void Destroy(Vector &states, AggregateInputData &aggr_input_data, idx_t count) {
147544 auto sdata = FlatVector::GetData<STATE_TYPE *>(states);
147545 for (idx_t i = 0; i < count; i++) {
147546 OP::template Destroy<STATE_TYPE>(*sdata[i], aggr_input_data);
147547 }
147548 }
147549};
147550
147551}
147552
147553
147554
147555
147556
147557
147558
147559
147560
147561
147562
147563
147564
147565
147566
147567
147568
147569
147570
147571
147572
147573
147574
147575
147576
147577
147578
147579namespace duckdb {
147580
147581using GroupingSet = set<idx_t>;
147582
147583class GroupByNode {
147584public:
147586 vector<unique_ptr<ParsedExpression>> group_expressions;
147588 vector<GroupingSet> grouping_sets;
147589
147590public:
147591 GroupByNode Copy() {
147592 GroupByNode node;
147593 node.group_expressions.reserve(group_expressions.size());
147594 for (auto &expr : group_expressions) {
147595 node.group_expressions.push_back(expr->Copy());
147596 }
147597 node.grouping_sets = grouping_sets;
147598 return node;
147599 }
147600};
147601
147602}
147603
147604
147605
147606
147607
147608
147609
147610
147611
147612
147613
147614
147615
147616
147617
147618
147619
147620
147621
147622
147623
147624
147625
147626
147627
147628namespace duckdb {
147629
147630enum class OrderType :
uint8_t { INVALID = 0, ORDER_DEFAULT = 1, ASCENDING = 2, DESCENDING = 3 };
147631
147632enum class OrderByNullType :
uint8_t { INVALID = 0, ORDER_DEFAULT = 1, NULLS_FIRST = 2, NULLS_LAST = 3 };
147633
147634enum class DefaultOrderByNullType :
uint8_t {
147635 INVALID = 0,
147636 NULLS_FIRST = 2,
147637 NULLS_LAST = 3,
147638 NULLS_FIRST_ON_ASC_LAST_ON_DESC = 4,
147639 NULLS_LAST_ON_ASC_FIRST_ON_DESC = 5
147640};
147641
147642}
147643
147644
147645
147646namespace duckdb {
147647class Deserializer;
147648class Serializer;
147649
147650enum class ResultModifierType :
uint8_t {
147651 LIMIT_MODIFIER = 1,
147652 ORDER_MODIFIER = 2,
147653 DISTINCT_MODIFIER = 3,
147654 LIMIT_PERCENT_MODIFIER = 4
147655};
147656
147657const char *ToString(ResultModifierType value);
147658ResultModifierType ResultModifierFromString(const char *value);
147659
147661class ResultModifier {
147662public:
147663 explicit ResultModifier(ResultModifierType type) : type(type) {
147664 }
147665 virtual ~ResultModifier() {
147666 }
147667
147668 ResultModifierType type;
147669
147670public:
147672 virtual bool Equals(const ResultModifier &other) const;
147673
147675 virtual unique_ptr<ResultModifier> Copy() const = 0;
147676
147677 virtual void Serialize(Serializer &serializer) const;
147678 static unique_ptr<ResultModifier> Deserialize(Deserializer &deserializer);
147679
147680public:
147681 template <class TARGET>
147682 TARGET &Cast() {
147683 if (type != TARGET::TYPE) {
147684 throw InternalException("Failed to cast result modifier to type - result modifier type mismatch");
147685 }
147686 return reinterpret_cast<TARGET &>(*this);
147687 }
147688
147689 template <class TARGET>
147690 const TARGET &Cast() const {
147691 if (type != TARGET::TYPE) {
147692 throw InternalException("Failed to cast result modifier to type - result modifier type mismatch");
147693 }
147694 return reinterpret_cast<const TARGET &>(*this);
147695 }
147696};
147697
147699struct OrderByNode {
147700 OrderByNode(OrderType type, OrderByNullType null_order, unique_ptr<ParsedExpression> expression)
147701 : type(type), null_order(null_order), expression(std::move(expression)) {
147702 }
147703
147705 OrderType type;
147707 OrderByNullType null_order;
147709 unique_ptr<ParsedExpression> expression;
147710
147711public:
147712 string ToString() const;
147713
147714 void Serialize(Serializer &serializer) const;
147715 static OrderByNode Deserialize(Deserializer &deserializer);
147716};
147717
147718class LimitModifier : public ResultModifier {
147719public:
147720 static constexpr const ResultModifierType
TYPE = ResultModifierType::LIMIT_MODIFIER;
147721
147722public:
147723 LimitModifier() : ResultModifier(ResultModifierType::LIMIT_MODIFIER) {
147724 }
147725
147727 unique_ptr<ParsedExpression> limit;
147729 unique_ptr<ParsedExpression> offset;
147730
147731public:
147732 bool Equals(const ResultModifier &other) const override;
147733 unique_ptr<ResultModifier> Copy() const override;
147734
147735 void Serialize(Serializer &serializer) const override;
147736 static unique_ptr<ResultModifier> Deserialize(Deserializer &deserializer);
147737};
147738
147739class OrderModifier : public ResultModifier {
147740public:
147741 static constexpr const ResultModifierType
TYPE = ResultModifierType::ORDER_MODIFIER;
147742
147743public:
147744 OrderModifier() : ResultModifier(ResultModifierType::ORDER_MODIFIER) {
147745 }
147746
147748 vector<OrderByNode> orders;
147749
147750public:
147751 bool Equals(const ResultModifier &other) const override;
147752 unique_ptr<ResultModifier> Copy() const override;
147753
147754 void Serialize(Serializer &serializer) const override;
147755 static unique_ptr<ResultModifier> Deserialize(Deserializer &deserializer);
147756
147757 static bool Equals(const unique_ptr<OrderModifier> &left, const unique_ptr<OrderModifier> &right);
147758};
147759
147760class DistinctModifier : public ResultModifier {
147761public:
147762 static constexpr const ResultModifierType
TYPE = ResultModifierType::DISTINCT_MODIFIER;
147763
147764public:
147765 DistinctModifier() : ResultModifier(ResultModifierType::DISTINCT_MODIFIER) {
147766 }
147767
147769 vector<unique_ptr<ParsedExpression>> distinct_on_targets;
147770
147771public:
147772 bool Equals(const ResultModifier &other) const override;
147773 unique_ptr<ResultModifier> Copy() const override;
147774
147775 void Serialize(Serializer &serializer) const override;
147776 static unique_ptr<ResultModifier> Deserialize(Deserializer &deserializer);
147777};
147778
147779class LimitPercentModifier : public ResultModifier {
147780public:
147781 static constexpr const ResultModifierType
TYPE = ResultModifierType::LIMIT_PERCENT_MODIFIER;
147782
147783public:
147784 LimitPercentModifier() : ResultModifier(ResultModifierType::LIMIT_PERCENT_MODIFIER) {
147785 }
147786
147788 unique_ptr<ParsedExpression> limit;
147790 unique_ptr<ParsedExpression> offset;
147791
147792public:
147793 bool Equals(const ResultModifier &other) const override;
147794 unique_ptr<ResultModifier> Copy() const override;
147795
147796 void Serialize(Serializer &serializer) const override;
147797 static unique_ptr<ResultModifier> Deserialize(Deserializer &deserializer);
147798};
147799
147800}
147801
147802
147803
147804
147805
147806
147807
147808
147809
147810
147811
147812
147813
147814
147815
147816
147817
147818
147819
147820
147821
147822
147823
147824
147825
147826
147827namespace duckdb {
147828
147829enum class SetOperationType :
uint8_t { NONE = 0, UNION = 1, EXCEPT = 2, INTERSECT = 3, UNION_BY_NAME = 4 };
147830
147831}
147832
147833
147834
147835namespace duckdb {
147836
147837class LogicalOperator;
147838struct LogicalType;
147839struct BoundStatement;
147840class ParsedExpression;
147841class Binder;
147842
147843struct ExtraBoundInfo {
147844 SetOperationType setop_type = SetOperationType::NONE;
147845 vector<shared_ptr<Binder>> child_binders;
147846 vector<BoundStatement> bound_children;
147847 vector<unique_ptr<ParsedExpression>> original_expressions;
147848};
147849
147850struct BoundStatement {
147851 unique_ptr<LogicalOperator> plan;
147852 vector<LogicalType> types;
147853 vector<string> names;
147854 ExtraBoundInfo extra_info;
147855};
147856
147857}
147858
147859
147860
147861
147862
147863
147864
147865
147866
147867
147868
147869
147870
147871
147872namespace duckdb {
147873class BaseStatistics;
147874class ClientContext;
147875
147877class Expression : public BaseExpression {
147878public:
147879 Expression(ExpressionType type, ExpressionClass expression_class, LogicalType return_type);
147880 ~Expression() override;
147881
147883 LogicalType return_type;
147885 unique_ptr<BaseStatistics> verification_stats;
147886
147887public:
147888 bool IsAggregate() const override;
147889 bool IsWindow() const override;
147890 bool HasSubquery() const override;
147891 bool IsScalar() const override;
147892 bool HasParameter() const override;
147893
147894 virtual bool IsVolatile() const;
147895 virtual bool IsConsistent() const;
147896 virtual bool PropagatesNullValues() const;
147897 virtual bool IsFoldable() const;
147898 virtual bool CanThrow() const;
147899
147900 hash_t Hash()
const override;
147901
147902 bool Equals(const BaseExpression &other) const override {
147903 if (!BaseExpression::Equals(other)) {
147904 return false;
147905 }
147906 return return_type == reinterpret_cast<const Expression &>(other).return_type;
147907 }
147908 static bool Equals(const Expression &left, const Expression &right) {
147909 return left.Equals(right);
147910 }
147911 static bool Equals(const unique_ptr<Expression> &left, const unique_ptr<Expression> &right);
147912 static bool ListEquals(const vector<unique_ptr<Expression>> &left, const vector<unique_ptr<Expression>> &right);
147914 virtual unique_ptr<Expression> Copy() const = 0;
147915
147916 virtual void Serialize(Serializer &serializer) const;
147917 static unique_ptr<Expression> Deserialize(Deserializer &deserializer);
147918
147919protected:
147922 void CopyProperties(const Expression &other) {
147923 type = other.type;
147924 expression_class = other.expression_class;
147925 alias = other.alias;
147926 return_type = other.return_type;
147927 query_location = other.query_location;
147928 }
147929};
147930
147931}
147932
147933
147934
147935namespace duckdb {
147936
147938class BoundResultModifier {
147939public:
147940 explicit BoundResultModifier(ResultModifierType type);
147941 virtual ~BoundResultModifier();
147942
147943 ResultModifierType type;
147944
147945public:
147946 template <class TARGET>
147947 TARGET &Cast() {
147948 if (type != TARGET::TYPE) {
147949 throw InternalException("Failed to cast result modifier to type - result modifier type mismatch");
147950 }
147951 return reinterpret_cast<TARGET &>(*this);
147952 }
147953
147954 template <class TARGET>
147955 const TARGET &Cast() const {
147956 if (type != TARGET::TYPE) {
147957 throw InternalException("Failed to cast result modifier to type - result modifier type mismatch");
147958 }
147959 return reinterpret_cast<const TARGET &>(*this);
147960 }
147961};
147962
147963struct BoundOrderByNode {
147964public:
147965 static constexpr const ResultModifierType
TYPE = ResultModifierType::ORDER_MODIFIER;
147966
147967public:
147968 BoundOrderByNode(OrderType type, OrderByNullType null_order, unique_ptr<Expression> expression);
147969 BoundOrderByNode(OrderType type, OrderByNullType null_order, unique_ptr<Expression> expression,
147970 unique_ptr<BaseStatistics> stats);
147971
147972 OrderType type;
147973 OrderByNullType null_order;
147974 unique_ptr<Expression> expression;
147975 unique_ptr<BaseStatistics> stats;
147976
147977public:
147978 BoundOrderByNode Copy() const;
147979 bool Equals(const BoundOrderByNode &other) const;
147980 string GetOrderModifier() const;
147981 string ToString() const;
147982
147983 void Serialize(Serializer &serializer) const;
147984 static BoundOrderByNode Deserialize(Deserializer &deserializer);
147985};
147986
147987enum class LimitNodeType :
uint8_t {
147988 UNSET = 0,
147989 CONSTANT_VALUE = 1,
147990 CONSTANT_PERCENTAGE = 2,
147991 EXPRESSION_VALUE = 3,
147992 EXPRESSION_PERCENTAGE = 4
147993};
147994
147995struct BoundLimitNode {
147996public:
147997 BoundLimitNode();
147998 BoundLimitNode(LimitNodeType type, idx_t constant_integer, double constant_percentage,
147999 unique_ptr<Expression> expression);
148000
148001public:
148002 static BoundLimitNode ConstantValue(int64_t value);
148003 static BoundLimitNode ConstantPercentage(double percentage);
148004 static BoundLimitNode ExpressionValue(unique_ptr<Expression> expression);
148005 static BoundLimitNode ExpressionPercentage(unique_ptr<Expression> expression);
148006
148007 LimitNodeType Type() const {
148008 return type;
148009 }
148010
148012 idx_t GetConstantValue()
const;
148014 double GetConstantPercentage() const;
148016 const Expression &GetValueExpression() const;
148018 const Expression &GetPercentageExpression() const;
148019
148022 unique_ptr<Expression> &GetExpression() {
148023 return expression;
148024 }
148025
148026 void Serialize(Serializer &serializer) const;
148027 static BoundLimitNode Deserialize(Deserializer &deserializer);
148028
148029private:
148030 LimitNodeType type = LimitNodeType::UNSET;
148032 idx_t constant_integer = 0;
148034 double constant_percentage = -1;
148036 unique_ptr<Expression> expression;
148037
148038private:
148039 explicit BoundLimitNode(int64_t constant_value);
148040 explicit BoundLimitNode(double percentage_value);
148041 explicit BoundLimitNode(unique_ptr<Expression> expression, bool is_percentage);
148042};
148043
148044class BoundLimitModifier : public BoundResultModifier {
148045public:
148046 static constexpr const ResultModifierType
TYPE = ResultModifierType::LIMIT_MODIFIER;
148047
148048public:
148049 BoundLimitModifier();
148050
148052 BoundLimitNode limit_val;
148054 BoundLimitNode offset_val;
148055};
148056
148057class BoundOrderModifier : public BoundResultModifier {
148058public:
148059 static constexpr const ResultModifierType
TYPE = ResultModifierType::ORDER_MODIFIER;
148060
148061public:
148062 BoundOrderModifier();
148063
148065 vector<BoundOrderByNode> orders;
148066
148067 unique_ptr<BoundOrderModifier> Copy() const;
148068 static bool Equals(const BoundOrderModifier &left, const BoundOrderModifier &right);
148069 static bool Equals(const unique_ptr<BoundOrderModifier> &left, const unique_ptr<BoundOrderModifier> &right);
148070
148071 void Serialize(Serializer &serializer) const;
148072 static unique_ptr<BoundOrderModifier> Deserialize(Deserializer &deserializer);
148073
148076 static bool Simplify(vector<BoundOrderByNode> &orders, const vector<unique_ptr<Expression>> &groups,
148077 optional_ptr<vector<GroupingSet>> grouping_sets);
148078 bool Simplify(const vector<unique_ptr<Expression>> &groups, optional_ptr<vector<GroupingSet>> grouping_sets);
148079};
148080
148081enum class DistinctType :
uint8_t { DISTINCT = 0, DISTINCT_ON = 1 };
148082
148083class BoundDistinctModifier : public BoundResultModifier {
148084public:
148085 static constexpr const ResultModifierType
TYPE = ResultModifierType::DISTINCT_MODIFIER;
148086
148087public:
148088 BoundDistinctModifier();
148089
148091 DistinctType distinct_type;
148093 vector<unique_ptr<Expression>> target_distincts;
148094};
148095
148096}
148097
148098
148099
148100namespace duckdb {
148101
148102class BufferManager;
148103class InterruptState;
148104
148107struct FrameDelta {
148108 FrameDelta() : begin(0), end(0) {};
148109 FrameDelta(int64_t begin, int64_t end) : begin(begin), end(end) {};
148112};
148113
148116
148120class ColumnDataCollection;
148121struct WindowPartitionInput {
148122 WindowPartitionInput(ExecutionContext &context, const ColumnDataCollection *inputs, const idx_t count,
148123 const vector<column_t> &column_ids, const vector<bool> &all_valid,
148124 const ValidityMask &filter_mask, const FrameStats &stats, InterruptState &interrupt_state)
148125 : context(context), inputs(inputs), count(count), column_ids(column_ids), all_valid(all_valid),
148126 filter_mask(filter_mask), stats(stats), interrupt_state(interrupt_state) {
148127 }
148128 ExecutionContext &context;
148129 const ColumnDataCollection *inputs;
148130 const idx_t count;
148131 const vector<column_t> column_ids;
148132 const vector<bool> &all_valid;
148133 const ValidityMask &filter_mask;
148135 InterruptState &interrupt_state;
148136};
148137
148139typedef idx_t (*aggregate_size_t)(
const AggregateFunction &function);
148141typedef void (*aggregate_initialize_t)(const AggregateFunction &function, data_ptr_t state);
148143typedef void (*aggregate_update_t)(Vector inputs[], AggregateInputData &aggr_input_data,
idx_t input_count,
148144 Vector &state,
idx_t count);
148146typedef void (*aggregate_combine_t)(Vector &state, Vector &combined, AggregateInputData &aggr_input_data,
idx_t count);
148148typedef void (*aggregate_finalize_t)(Vector &state, AggregateInputData &aggr_input_data, Vector &result,
idx_t count,
148151typedef unique_ptr<BaseStatistics> (*aggregate_statistics_t)(ClientContext &context, BoundAggregateExpression &expr,
148152 AggregateStatisticsInput &input);
148154typedef unique_ptr<FunctionData> (*bind_aggregate_function_t)(ClientContext &context, AggregateFunction &function,
148155 vector<unique_ptr<Expression>> &arguments);
148157typedef void (*aggregate_destructor_t)(Vector &state, AggregateInputData &aggr_input_data,
idx_t count);
148158
148160typedef void (*aggregate_simple_update_t)(Vector inputs[], AggregateInputData &aggr_input_data,
idx_t input_count,
148161 data_ptr_t state,
idx_t count);
148162
148164typedef void (*aggregate_window_t)(AggregateInputData &aggr_input_data,
const WindowPartitionInput &
partition,
148165 const_data_ptr_t g_state, data_ptr_t l_state, const SubFrames &subframes,
148166 Vector &result,
idx_t rid);
148167
148169typedef void (*aggregate_wininit_t)(AggregateInputData &aggr_input_data,
const WindowPartitionInput &
partition,
148170 data_ptr_t g_state);
148171
148172typedef void (*aggregate_serialize_t)(Serializer &serializer, const optional_ptr<FunctionData> bind_data,
148173 const AggregateFunction &function);
148174typedef unique_ptr<FunctionData> (*aggregate_deserialize_t)(Deserializer &deserializer, AggregateFunction &function);
148175
148176struct AggregateFunctionInfo {
148177 DUCKDB_API virtual ~AggregateFunctionInfo();
148178
148179 template <class TARGET>
148180 TARGET &Cast() {
148181 DynamicCastCheck<TARGET>(this);
148182 return reinterpret_cast<TARGET &>(*this);
148183 }
148184 template <class TARGET>
148185 const TARGET &Cast() const {
148186 DynamicCastCheck<TARGET>(this);
148187 return reinterpret_cast<const TARGET &>(*this);
148188 }
148189};
148190
148191enum class AggregateDestructorType {
148192 STANDARD,
148193
148194
148195 LEGACY
148196};
148197
148198class AggregateFunction : public BaseScalarFunction {
148199public:
148200 AggregateFunction(const string &name, const vector<LogicalType> &arguments, const LogicalType &return_type,
148201 aggregate_size_t state_size, aggregate_initialize_t initialize, aggregate_update_t update,
148202 aggregate_combine_t combine, aggregate_finalize_t finalize,
148203 FunctionNullHandling null_handling = FunctionNullHandling::DEFAULT_NULL_HANDLING,
148204 aggregate_simple_update_t simple_update = nullptr, bind_aggregate_function_t bind = nullptr,
148205 aggregate_destructor_t destructor = nullptr, aggregate_statistics_t statistics = nullptr,
148206 aggregate_window_t window = nullptr, aggregate_serialize_t serialize = nullptr,
148207 aggregate_deserialize_t deserialize = nullptr)
148208 : BaseScalarFunction(name, arguments, return_type,
FunctionStability::CONSISTENT,
148210 state_size(state_size), initialize(initialize), update(update),
combine(
combine), finalize(finalize),
148211 simple_update(simple_update), window(window),
bind(
bind), destructor(destructor), statistics(statistics),
148214 }
148215
148216 AggregateFunction(const string &name, const vector<LogicalType> &arguments, const LogicalType &return_type,
148217 aggregate_size_t state_size, aggregate_initialize_t initialize, aggregate_update_t update,
148218 aggregate_combine_t combine, aggregate_finalize_t finalize,
148219 aggregate_simple_update_t simple_update = nullptr, bind_aggregate_function_t bind = nullptr,
148220 aggregate_destructor_t destructor = nullptr, aggregate_statistics_t statistics = nullptr,
148221 aggregate_window_t window = nullptr, aggregate_serialize_t serialize = nullptr,
148222 aggregate_deserialize_t deserialize = nullptr)
148223 : BaseScalarFunction(name, arguments, return_type,
FunctionStability::CONSISTENT,
148225 state_size(state_size), initialize(initialize), update(update),
combine(
combine), finalize(finalize),
148226 simple_update(simple_update), window(window),
bind(
bind), destructor(destructor), statistics(statistics),
148229 }
148230
148231 AggregateFunction(const vector<LogicalType> &arguments, const LogicalType &return_type, aggregate_size_t state_size,
148232 aggregate_initialize_t initialize, aggregate_update_t update, aggregate_combine_t combine,
148233 aggregate_finalize_t finalize,
148234 FunctionNullHandling null_handling = FunctionNullHandling::DEFAULT_NULL_HANDLING,
148235 aggregate_simple_update_t simple_update = nullptr, bind_aggregate_function_t bind = nullptr,
148236 aggregate_destructor_t destructor = nullptr, aggregate_statistics_t statistics = nullptr,
148237 aggregate_window_t window = nullptr, aggregate_serialize_t serialize = nullptr,
148238 aggregate_deserialize_t deserialize = nullptr)
148239 : AggregateFunction(string(), arguments, return_type, state_size, initialize, update,
combine, finalize,
148240 null_handling, simple_update,
bind, destructor, statistics, window,
serialize,
148242 }
148243
148244 AggregateFunction(const vector<LogicalType> &arguments, const LogicalType &return_type, aggregate_size_t state_size,
148245 aggregate_initialize_t initialize, aggregate_update_t update, aggregate_combine_t combine,
148246 aggregate_finalize_t finalize, aggregate_simple_update_t simple_update = nullptr,
148247 bind_aggregate_function_t bind = nullptr, aggregate_destructor_t destructor = nullptr,
148248 aggregate_statistics_t statistics = nullptr, aggregate_window_t window = nullptr,
148249 aggregate_serialize_t serialize = nullptr, aggregate_deserialize_t deserialize = nullptr)
148250 : AggregateFunction(string(), arguments, return_type, state_size, initialize, update,
combine, finalize,
148253 }
148254
148255
148256 AggregateFunction(const vector<LogicalType> &arguments, const LogicalType &return_type, aggregate_size_t state_size,
148257 aggregate_initialize_t initialize, aggregate_wininit_t window_init, aggregate_window_t window,
148258 bind_aggregate_function_t bind = nullptr, aggregate_destructor_t destructor = nullptr,
148259 aggregate_statistics_t statistics = nullptr, aggregate_serialize_t serialize = nullptr,
148260 aggregate_deserialize_t deserialize = nullptr)
148261 : BaseScalarFunction(name, arguments, return_type,
FunctionStability::CONSISTENT,
148263 state_size(state_size), initialize(initialize), update(nullptr),
combine(nullptr), finalize(nullptr),
148264 simple_update(nullptr), window(window), window_init(window_init),
bind(
bind), destructor(destructor),
148268 }
148269
148270
148271 bool HasBindCallback()
const {
return bind !=
nullptr; }
148273 void SetBindCallback(bind_aggregate_function_t callback) {
bind = callback; }
148274
148275 bool HasStateInitCallback() const { return initialize != nullptr; }
148277 void SetStateInitCallback(aggregate_initialize_t callback) { initialize = callback; }
148278
148279 bool HasStateSizeCallback() const { return state_size != nullptr; }
148281 void SetStateSizeCallback(aggregate_size_t callback) { state_size = callback; }
148282
148283 bool HasStateDestructorCallback() const { return destructor != nullptr; }
148285 void SetStateDestructorCallback(aggregate_destructor_t callback) { destructor = callback; }
148286
148287 bool HasStateUpdateCallback() const { return update != nullptr; }
148289 void SetStateUpdateCallback(aggregate_update_t callback) { update = callback; }
148290
148291 bool HasStateSimpleUpdateCallback() const { return simple_update != nullptr; }
148293 void SetStateSimpleUpdateCallback(aggregate_simple_update_t callback) { simple_update = callback; }
148294
148295 void SetStateCombineCallback(aggregate_combine_t callback) {
combine = callback; }
148297 bool HasStateCombineCallback()
const {
return combine !=
nullptr; }
148298
148299 void SetStateFinalizeCallback(aggregate_finalize_t callback) { finalize = callback; }
148301 bool HasStateFinalizeCallback() const { return finalize != nullptr; }
148302
148303 bool HasWindowCallback() const { return window != nullptr; }
148305 void SetWindowCallback(aggregate_window_t callback) { window = callback; }
148306
148307 void SetWindowInitCallback(aggregate_wininit_t callback) { window_init = callback; }
148309 bool HasWindowInitCallback() const { return window_init != nullptr; }
148310
148311 bool HasStatisticsCallback() const { return statistics != nullptr; }
148313 void SetStatisticsCallback(aggregate_statistics_t callback) { statistics = callback; }
148314
148315 bool HasSerializationCallbacks()
const {
return serialize !=
nullptr &&
deserialize !=
nullptr; }
148316 void SetSerializeCallback(aggregate_serialize_t callback) {
serialize = callback; }
148317 void SetDeserializeCallback(aggregate_deserialize_t callback) {
deserialize = callback; }
148318 aggregate_serialize_t GetSerializeCallback()
const {
return serialize; }
148319 aggregate_deserialize_t GetDeserializeCallback()
const {
return deserialize; }
148320
148321
148322public:
148339
148344
148347
148350
148355
148357 return order_dependent;
148358 }
148359 void SetOrderDependent(AggregateOrderDependent value) {
148360 order_dependent = value;
148361 }
148363 return distinct_dependent;
148364 }
148365 void SetDistinctDependent(AggregateDistinctDependent value) {
148366 distinct_dependent = value;
148367 }
148368
148370 shared_ptr<AggregateFunctionInfo> function_info;
148371
148372public:
148373 bool operator==(
const AggregateFunction &rhs)
const {
148374 return state_size == rhs.state_size && initialize == rhs.initialize && update == rhs.update &&
148375 combine == rhs.combine && finalize == rhs.finalize && window == rhs.window;
148376 }
148377 bool operator!=(
const AggregateFunction &rhs)
const {
148378 return !(*this == rhs);
148379 }
148380
148381 bool CanAggregate() const {
148382 return update ||
combine || finalize;
148383 }
148384 bool CanWindow() const {
148385 return window;
148386 }
148387
148388public:
148389 template <class STATE, class RESULT_TYPE, class OP>
148390 static AggregateFunction NullaryAggregate(LogicalType return_type) {
148391 return AggregateFunction(
148392 {}, return_type, AggregateFunction::StateSize<STATE>, AggregateFunction::StateInitialize<STATE, OP>,
148393 AggregateFunction::NullaryScatterUpdate<STATE, OP>, AggregateFunction::StateCombine<STATE, OP>,
148394 AggregateFunction::StateFinalize<STATE, RESULT_TYPE, OP>, AggregateFunction::NullaryUpdate<STATE, OP>);
148395 }
148396
148397 template <class STATE, class INPUT_TYPE, class RESULT_TYPE, class OP,
148398 AggregateDestructorType destructor_type = AggregateDestructorType::STANDARD>
148399 static AggregateFunction
148400 UnaryAggregate(const LogicalType &input_type, LogicalType return_type,
148401 FunctionNullHandling null_handling = FunctionNullHandling::DEFAULT_NULL_HANDLING) {
148402 return AggregateFunction({input_type}, return_type, AggregateFunction::StateSize<STATE>,
148403 AggregateFunction::StateInitialize<STATE, OP, destructor_type>,
148404 AggregateFunction::UnaryScatterUpdate<STATE, INPUT_TYPE, OP>,
148405 AggregateFunction::StateCombine<STATE, OP>,
148406 AggregateFunction::StateFinalize<STATE, RESULT_TYPE, OP>, null_handling,
148407 AggregateFunction::UnaryUpdate<STATE, INPUT_TYPE, OP>);
148408 }
148409
148410 template <class STATE, class INPUT_TYPE, class RESULT_TYPE, class OP,
148411 AggregateDestructorType destructor_type = AggregateDestructorType::STANDARD>
148412 static AggregateFunction UnaryAggregateDestructor(LogicalType input_type, LogicalType return_type) {
148413 auto aggregate = UnaryAggregate<STATE, INPUT_TYPE, RESULT_TYPE, OP, destructor_type>(input_type, return_type);
148414 aggregate.destructor = AggregateFunction::StateDestroy<STATE, OP>;
148415 return aggregate;
148416 }
148417
148418 template <class STATE, class A_TYPE, class B_TYPE, class RESULT_TYPE, class OP,
148419 AggregateDestructorType destructor_type = AggregateDestructorType::STANDARD>
148420 static AggregateFunction BinaryAggregate(const LogicalType &a_type, const LogicalType &b_type,
148421 LogicalType return_type) {
148422 return AggregateFunction({a_type, b_type}, return_type, AggregateFunction::StateSize<STATE>,
148423 AggregateFunction::StateInitialize<STATE, OP, destructor_type>,
148424 AggregateFunction::BinaryScatterUpdate<STATE, A_TYPE, B_TYPE, OP>,
148425 AggregateFunction::StateCombine<STATE, OP>,
148426 AggregateFunction::StateFinalize<STATE, RESULT_TYPE, OP>,
148427 AggregateFunction::BinaryUpdate<STATE, A_TYPE, B_TYPE, OP>);
148428 }
148429
148430public:
148431 template <class STATE>
148432 static idx_t StateSize(
const AggregateFunction &) {
148433 return sizeof(STATE);
148434 }
148435
148436 template <class STATE, class OP, AggregateDestructorType destructor_type = AggregateDestructorType::STANDARD>
148437 static void StateInitialize(const AggregateFunction &, data_ptr_t state) {
148438
148439#if !defined(__GNUC__) || (__GNUC__ >= 5)
148440 static_assert(std::is_trivially_move_constructible<STATE>::value ||
148441 destructor_type == AggregateDestructorType::LEGACY,
148442 "Aggregate state must be trivially move constructible");
148443#endif
148444 OP::Initialize(*reinterpret_cast<STATE *>(state));
148445 }
148446
148447 template <class STATE, class OP>
148448 static void NullaryScatterUpdate(Vector inputs[], AggregateInputData &aggr_input_data, idx_t input_count,
148449 Vector &states, idx_t count) {
148450 D_ASSERT(input_count == 0);
148451 AggregateExecutor::NullaryScatter<STATE, OP>(states, aggr_input_data, count);
148452 }
148453
148454 template <class STATE, class OP>
148455 static void NullaryUpdate(Vector inputs[], AggregateInputData &aggr_input_data, idx_t input_count, data_ptr_t state,
148456 idx_t count) {
148457 D_ASSERT(input_count == 0);
148458 AggregateExecutor::NullaryUpdate<STATE, OP>(state, aggr_input_data, count);
148459 }
148460
148461 template <class STATE, class T, class OP>
148462 static void UnaryScatterUpdate(Vector inputs[], AggregateInputData &aggr_input_data, idx_t input_count,
148463 Vector &states, idx_t count) {
148464 D_ASSERT(input_count == 1);
148465 AggregateExecutor::UnaryScatter<STATE, T, OP>(inputs[0], states, aggr_input_data, count);
148466 }
148467
148468 template <class STATE, class INPUT_TYPE, class OP>
148469 static void UnaryUpdate(Vector inputs[], AggregateInputData &aggr_input_data, idx_t input_count, data_ptr_t state,
148470 idx_t count) {
148471 D_ASSERT(input_count == 1);
148472 AggregateExecutor::UnaryUpdate<STATE, INPUT_TYPE, OP>(inputs[0], aggr_input_data, state, count);
148473 }
148474
148475 template <class STATE, class A_TYPE, class B_TYPE, class OP>
148476 static void BinaryScatterUpdate(Vector inputs[], AggregateInputData &aggr_input_data, idx_t input_count,
148477 Vector &states, idx_t count) {
148478 D_ASSERT(input_count == 2);
148479 AggregateExecutor::BinaryScatter<STATE, A_TYPE, B_TYPE, OP>(aggr_input_data, inputs[0], inputs[1], states,
148480 count);
148481 }
148482
148483 template <class STATE, class A_TYPE, class B_TYPE, class OP>
148484 static void BinaryUpdate(Vector inputs[], AggregateInputData &aggr_input_data, idx_t input_count, data_ptr_t state,
148485 idx_t count) {
148486 D_ASSERT(input_count == 2);
148487 AggregateExecutor::BinaryUpdate<STATE, A_TYPE, B_TYPE, OP>(aggr_input_data, inputs[0], inputs[1], state, count);
148488 }
148489
148490 template <class STATE, class OP>
148491 static void StateCombine(Vector &source, Vector &target, AggregateInputData &aggr_input_data, idx_t count) {
148492 AggregateExecutor::Combine<STATE, OP>(source, target, aggr_input_data, count);
148493 }
148494
148495 template <class STATE, class RESULT_TYPE, class OP>
148496 static void StateFinalize(Vector &states, AggregateInputData &aggr_input_data, Vector &result, idx_t count,
148497 idx_t offset) {
148498 AggregateExecutor::Finalize<STATE, RESULT_TYPE, OP>(states, aggr_input_data, result, count, offset);
148499 }
148500
148501 template <class STATE, class OP>
148502 static void StateVoidFinalize(Vector &states, AggregateInputData &aggr_input_data, Vector &result, idx_t count,
148503 idx_t offset) {
148504 AggregateExecutor::VoidFinalize<STATE, OP>(states, aggr_input_data, result, count, offset);
148505 }
148506
148507 template <class STATE, class OP>
148508 static void StateDestroy(Vector &states, AggregateInputData &aggr_input_data, idx_t count) {
148509 AggregateExecutor::Destroy<STATE, OP>(states, aggr_input_data, count);
148510 }
148511};
148512
148513}
148514
148515
148516namespace duckdb {
148517
148518
148519
148520struct UDFWrapper {
148521public:
148522 template <typename TR, typename... ARGS>
148523 inline static scalar_function_t CreateScalarFunction(
const string &name, TR (*udf_func)(ARGS...)) {
148524 const std::size_t num_template_argc = sizeof...(ARGS);
148525 switch (num_template_argc) {
148526 case 1:
148527 return CreateUnaryFunction<TR, ARGS...>(name, udf_func);
148528 case 2:
148529 return CreateBinaryFunction<TR, ARGS...>(name, udf_func);
148530 case 3:
148531 return CreateTernaryFunction<TR, ARGS...>(name, udf_func);
148532 default:
148533 throw std::runtime_error("UDF function only supported until ternary!");
148534 }
148535 }
148536
148537 template <typename TR, typename... ARGS>
148538 inline static scalar_function_t CreateScalarFunction(
const string &name,
const vector<LogicalType> &args,
148539 const LogicalType &ret_type, TR (*udf_func)(ARGS...)) {
148540 if (!TypesMatch<TR>(ret_type)) {
148541 throw std::runtime_error("Return type doesn't match with the first template type.");
148542 }
148543
148544 const std::size_t num_template_types = sizeof...(ARGS);
148545 if (num_template_types != args.size()) {
148546 throw std::runtime_error(
148547 "The number of templated types should be the same quantity of the LogicalType arguments.");
148548 }
148549
148550 switch (num_template_types) {
148551 case 1:
148552 return CreateUnaryFunction<TR, ARGS...>(name, args, ret_type, udf_func);
148553 case 2:
148554 return CreateBinaryFunction<TR, ARGS...>(name, args, ret_type, udf_func);
148555 case 3:
148556 return CreateTernaryFunction<TR, ARGS...>(name, args, ret_type, udf_func);
148557 default:
148558 throw std::runtime_error("UDF function only supported until ternary!");
148559 }
148560 }
148561
148562 template <typename TR, typename... ARGS>
148563 inline static void RegisterFunction(const string &name, scalar_function_t udf_function, ClientContext &context,
148564 LogicalType varargs = LogicalType(LogicalTypeId::INVALID)) {
148565 vector<LogicalType> arguments;
148566 GetArgumentTypesRecursive<ARGS...>(arguments);
148567
148568 LogicalType ret_type = GetArgumentType<TR>();
148569
148570 RegisterFunction(name, arguments, ret_type, std::move(udf_function), context, std::move(varargs));
148571 }
148572
148573 static void RegisterFunction(string name, vector<LogicalType> args, LogicalType ret_type,
148574 scalar_function_t udf_function, ClientContext &context,
148575 LogicalType varargs = LogicalType(LogicalTypeId::INVALID));
148576
148577
148578 template <typename UDF_OP, typename STATE, typename TR, typename TA>
148579 inline static AggregateFunction CreateAggregateFunction(const string &name) {
148580 return CreateUnaryAggregateFunction<UDF_OP, STATE, TR, TA>(name);
148581 }
148582
148583 template <typename UDF_OP, typename STATE, typename TR, typename TA, typename TB>
148584 inline static AggregateFunction CreateAggregateFunction(const string &name) {
148585 return CreateBinaryAggregateFunction<UDF_OP, STATE, TR, TA, TB>(name);
148586 }
148587
148588 template <typename UDF_OP, typename STATE, typename TR, typename TA>
148589 inline static AggregateFunction CreateAggregateFunction(const string &name, const LogicalType &ret_type,
148590 const LogicalType &input_type) {
148591 if (!TypesMatch<TR>(ret_type)) {
148592 throw std::runtime_error("The return argument don't match!");
148593 }
148594
148595 if (!TypesMatch<TA>(input_type)) {
148596 throw std::runtime_error("The input argument don't match!");
148597 }
148598
148599 return CreateUnaryAggregateFunction<UDF_OP, STATE, TR, TA>(name, ret_type, input_type);
148600 }
148601
148602 template <typename UDF_OP, typename STATE, typename TR, typename TA, typename TB>
148603 inline static AggregateFunction CreateAggregateFunction(const string &name, const LogicalType &ret_type,
148604 const LogicalType &input_type_a,
148605 const LogicalType &input_type_b) {
148606 if (!TypesMatch<TR>(ret_type)) {
148607 throw std::runtime_error("The return argument don't match!");
148608 }
148609
148610 if (!TypesMatch<TA>(input_type_a)) {
148611 throw std::runtime_error("The first input argument don't match!");
148612 }
148613
148614 if (!TypesMatch<TB>(input_type_b)) {
148615 throw std::runtime_error("The second input argument don't match!");
148616 }
148617
148618 return CreateBinaryAggregateFunction<UDF_OP, STATE, TR, TA, TB>(name, ret_type, input_type_a, input_type_b);
148619 }
148620
148622 inline static AggregateFunction
148623 CreateAggregateFunction(const string &name, const vector<LogicalType> &arguments, const LogicalType &return_type,
148624 aggregate_size_t state_size, aggregate_initialize_t initialize, aggregate_update_t update,
148625 aggregate_combine_t combine, aggregate_finalize_t finalize,
148626 aggregate_simple_update_t simple_update = nullptr, bind_aggregate_function_t bind = nullptr,
148627 aggregate_destructor_t destructor = nullptr) {
148628 AggregateFunction aggr_function(name, arguments, return_type, state_size, initialize, update, combine, finalize,
148629 simple_update, bind, destructor);
148630 aggr_function.SetNullHandling(FunctionNullHandling::SPECIAL_HANDLING);
148631 return aggr_function;
148632 }
148633
148634 static void RegisterAggrFunction(AggregateFunction aggr_function, ClientContext &context,
148635 LogicalType varargs = LogicalType(LogicalTypeId::INVALID));
148636
148637private:
148638
148639 struct UnaryUDFExecutor {
148640 template <class INPUT_TYPE, class RESULT_TYPE>
148641 static RESULT_TYPE Operation(INPUT_TYPE input, ValidityMask &mask, idx_t idx, void *dataptr) {
148642 typedef RESULT_TYPE (*unary_function_t)(INPUT_TYPE);
148643 auto udf = (unary_function_t)dataptr;
148644 return udf(input);
148645 }
148646 };
148647
148648 template <typename TR, typename TA>
148649 inline static scalar_function_t CreateUnaryFunction(
const string &name, TR (*udf_func)(TA)) {
148650 scalar_function_t udf_function = [=](DataChunk &input, ExpressionState &state, Vector &result) ->
void {
148651 UnaryExecutor::GenericExecute<TA, TR, UnaryUDFExecutor>(input.
data[0], result, input.size(),
148652 (void *)udf_func);
148653 };
148654 return udf_function;
148655 }
148656
148657 template <typename TR, typename TA, typename TB>
148658 inline static scalar_function_t CreateBinaryFunction(
const string &name, TR (*udf_func)(TA, TB)) {
148659 scalar_function_t udf_function = [=](DataChunk &input, ExpressionState &state, Vector &result) ->
void {
148660 BinaryExecutor::Execute<TA, TB, TR>(input.
data[0], input.
data[1], result, input.size(), udf_func);
148661 };
148662 return udf_function;
148663 }
148664
148665 template <typename TR, typename TA, typename TB, typename TC>
148666 inline static scalar_function_t CreateTernaryFunction(
const string &name, TR (*udf_func)(TA, TB, TC)) {
148667 scalar_function_t udf_function = [=](DataChunk &input, ExpressionState &state, Vector &result) ->
void {
148668 TernaryExecutor::Execute<TA, TB, TC, TR>(input.
data[0], input.
data[1], input.
data[2], result, input.size(),
148669 udf_func);
148670 };
148671 return udf_function;
148672 }
148673
148674 template <typename TR, typename... ARGS>
148676 TR (*udf_func)(ARGS...)) {
148677 throw std::runtime_error("Incorrect number of arguments for unary function");
148678 }
148679
148680 template <typename TR, typename... ARGS>
148682 TR (*udf_func)(ARGS...)) {
148683 throw std::runtime_error("Incorrect number of arguments for binary function");
148684 }
148685
148686 template <typename TR, typename... ARGS>
148688 TR (*udf_func)(ARGS...)) {
148689 throw std::runtime_error("Incorrect number of arguments for ternary function");
148690 }
148691
148692 template <typename T>
148693 inline static LogicalType GetArgumentType() {
148694 if (std::is_same<T, bool>()) {
148695 return LogicalType(LogicalTypeId::BOOLEAN);
148696 } else if (std::is_same<T, int8_t>()) {
148697 return LogicalType(LogicalTypeId::TINYINT);
148698 } else if (std::is_same<T, int16_t>()) {
148699 return LogicalType(LogicalTypeId::SMALLINT);
148700 } else if (std::is_same<T, int32_t>()) {
148701 return LogicalType(LogicalTypeId::INTEGER);
148702 } else if (std::is_same<T, int64_t>()) {
148703 return LogicalType(LogicalTypeId::BIGINT);
148704 } else if (std::is_same<T, float>()) {
148705 return LogicalType(LogicalTypeId::FLOAT);
148706 } else if (std::is_same<T, double>()) {
148707 return LogicalType(LogicalTypeId::DOUBLE);
148708 } else if (std::is_same<T, string_t>()) {
148709 return LogicalType(LogicalTypeId::VARCHAR);
148710 } else {
148711 throw std::runtime_error("Unrecognized type!");
148712 }
148713 }
148714
148715 template <typename TA, typename TB, typename... ARGS>
148716 inline static void GetArgumentTypesRecursive(vector<LogicalType> &arguments) {
148717 arguments.push_back(GetArgumentType<TA>());
148718 GetArgumentTypesRecursive<TB, ARGS...>(arguments);
148719 }
148720
148721 template <typename TA>
148722 inline static void GetArgumentTypesRecursive(vector<LogicalType> &arguments) {
148723 arguments.push_back(GetArgumentType<TA>());
148724 }
148725
148726private:
148727
148728
148729 template <typename TR, typename... ARGS>
148730 inline static scalar_function_t CreateUnaryFunction(
const string &name,
const vector<LogicalType> &args,
148731 const LogicalType &ret_type,
148732 TR (*udf_func)(ARGS...)) {
148733 throw std::runtime_error("Incorrect number of arguments for unary function");
148734 }
148735
148736 template <typename TR, typename TA>
148737 inline static scalar_function_t CreateUnaryFunction(
const string &name,
const vector<LogicalType> &args,
148738 const LogicalType &ret_type, TR (*udf_func)(TA)) {
148739 if (args.size() != 1) {
148740 throw std::runtime_error("The number of LogicalType arguments (\"args\") should be 1!");
148741 }
148742 if (!TypesMatch<TA>(args[0])) {
148743 throw std::runtime_error("The first arguments don't match!");
148744 }
148745
148746 scalar_function_t udf_function = [=](DataChunk &input, ExpressionState &state, Vector &result) ->
void {
148747 UnaryExecutor::GenericExecute<TA, TR, UnaryUDFExecutor>(input.
data[0], result, input.size(),
148748 (void *)udf_func);
148749 };
148750 return udf_function;
148751 }
148752
148753 template <typename TR, typename... ARGS>
148754 inline static scalar_function_t CreateBinaryFunction(
const string &name,
const vector<LogicalType> &args,
148755 const LogicalType &ret_type,
148756 TR (*udf_func)(ARGS...)) {
148757 throw std::runtime_error("Incorrect number of arguments for binary function");
148758 }
148759
148760 template <typename TR, typename TA, typename TB>
148761 inline static scalar_function_t CreateBinaryFunction(
const string &name,
const vector<LogicalType> &args,
148762 const LogicalType &ret_type, TR (*udf_func)(TA, TB)) {
148763 if (args.size() != 2) {
148764 throw std::runtime_error("The number of LogicalType arguments (\"args\") should be 2!");
148765 }
148766 if (!TypesMatch<TA>(args[0])) {
148767 throw std::runtime_error("The first arguments don't match!");
148768 }
148769 if (!TypesMatch<TB>(args[1])) {
148770 throw std::runtime_error("The second arguments don't match!");
148771 }
148772
148773 scalar_function_t udf_function = [=](DataChunk &input, ExpressionState &state, Vector &result) {
148774 BinaryExecutor::Execute<TA, TB, TR>(input.
data[0], input.
data[1], result, input.size(), udf_func);
148775 };
148776 return udf_function;
148777 }
148778
148779 template <typename TR, typename... ARGS>
148780 inline static scalar_function_t CreateTernaryFunction(
const string &name,
const vector<LogicalType> &args,
148781 const LogicalType &ret_type,
148782 TR (*udf_func)(ARGS...)) {
148783 throw std::runtime_error("Incorrect number of arguments for ternary function");
148784 }
148785
148786 template <typename TR, typename TA, typename TB, typename TC>
148787 inline static scalar_function_t CreateTernaryFunction(
const string &name,
const vector<LogicalType> &args,
148788 const LogicalType &ret_type, TR (*udf_func)(TA, TB, TC)) {
148789 if (args.size() != 3) {
148790 throw std::runtime_error("The number of LogicalType arguments (\"args\") should be 3!");
148791 }
148792 if (!TypesMatch<TA>(args[0])) {
148793 throw std::runtime_error("The first arguments don't match!");
148794 }
148795 if (!TypesMatch<TB>(args[1])) {
148796 throw std::runtime_error("The second arguments don't match!");
148797 }
148798 if (!TypesMatch<TC>(args[2])) {
148799 throw std::runtime_error("The second arguments don't match!");
148800 }
148801
148802 scalar_function_t udf_function = [=](DataChunk &input, ExpressionState &state, Vector &result) ->
void {
148803 TernaryExecutor::Execute<TA, TB, TC, TR>(input.
data[0], input.
data[1], input.
data[2], result, input.size(),
148804 udf_func);
148805 };
148806 return udf_function;
148807 }
148808
148809 template <typename T>
148810 inline static bool TypesMatch(const LogicalType &sql_type) {
148811 switch (sql_type.id()) {
148812 case LogicalTypeId::BOOLEAN:
148813 return std::is_same<T, bool>();
148814 case LogicalTypeId::TINYINT:
148815 return std::is_same<T, int8_t>();
148816 case LogicalTypeId::SMALLINT:
148817 return std::is_same<T, int16_t>();
148818 case LogicalTypeId::INTEGER:
148819 return std::is_same<T, int32_t>();
148820 case LogicalTypeId::BIGINT:
148821 return std::is_same<T, int64_t>();
148822 case LogicalTypeId::DATE:
148823 return std::is_same<T, date_t>();
148824 case LogicalTypeId::TIME:
148825 return std::is_same<T, dtime_t>();
148826 case LogicalTypeId::TIME_NS:
148827 return std::is_same<T, dtime_ns_t>();
148828 case LogicalTypeId::TIME_TZ:
148829 return std::is_same<T, dtime_tz_t>();
148830 case LogicalTypeId::TIMESTAMP:
148831 case LogicalTypeId::TIMESTAMP_MS:
148832 case LogicalTypeId::TIMESTAMP_NS:
148833 case LogicalTypeId::TIMESTAMP_SEC:
148834 case LogicalTypeId::TIMESTAMP_TZ:
148835 return std::is_same<T, timestamp_t>();
148836 case LogicalTypeId::FLOAT:
148837 return std::is_same<T, float>();
148838 case LogicalTypeId::DOUBLE:
148839 return std::is_same<T, double>();
148840 case LogicalTypeId::VARCHAR:
148841 case LogicalTypeId::CHAR:
148842 case LogicalTypeId::BLOB:
148843 return std::is_same<T, string_t>();
148844 default:
148845 throw std::runtime_error("Type is not supported!");
148846 }
148847 }
148848
148849private:
148850
148851 template <typename UDF_OP, typename STATE, typename TR, typename TA>
148852 inline static AggregateFunction CreateUnaryAggregateFunction(const string &name) {
148853 LogicalType return_type = GetArgumentType<TR>();
148854 LogicalType input_type = GetArgumentType<TA>();
148855 return CreateUnaryAggregateFunction<UDF_OP, STATE, TR, TA>(name, return_type, input_type);
148856 }
148857
148858 template <typename UDF_OP, typename STATE, typename TR, typename TA>
148859 inline static AggregateFunction CreateUnaryAggregateFunction(const string &name, const LogicalType &ret_type,
148860 const LogicalType &input_type) {
148861 AggregateFunction aggr_function =
148862 AggregateFunction::UnaryAggregate<STATE, TR, TA, UDF_OP>(input_type, ret_type);
148863 aggr_function.name = name;
148864 return aggr_function;
148865 }
148866
148867 template <typename UDF_OP, typename STATE, typename TR, typename TA, typename TB>
148868 inline static AggregateFunction CreateBinaryAggregateFunction(const string &name) {
148869 LogicalType return_type = GetArgumentType<TR>();
148870 LogicalType input_type_a = GetArgumentType<TA>();
148871 LogicalType input_type_b = GetArgumentType<TB>();
148872 return CreateBinaryAggregateFunction<UDF_OP, STATE, TR, TA, TB>(name, return_type, input_type_a, input_type_b);
148873 }
148874
148875 template <typename UDF_OP, typename STATE, typename TR, typename TA, typename TB>
148876 inline static AggregateFunction CreateBinaryAggregateFunction(const string &name, const LogicalType &ret_type,
148877 const LogicalType &input_type_a,
148878 const LogicalType &input_type_b) {
148879 AggregateFunction aggr_function =
148880 AggregateFunction::BinaryAggregate<STATE, TA, TB, TR, UDF_OP>(input_type_a, input_type_b, ret_type);
148881 aggr_function.name = name;
148882 return aggr_function;
148883 }
148884};
148885
148886
148887
148888}
148889
148890
148891
148892
148893
148894
148895
148896
148897
148898
148899
148900
148901
148902
148903
148904
148905
148906
148907
148908
148909
148910
148911
148912
148913
148914
148915
148916
148917
148918
148919
148920
148921
148922
148923
148924
148925
148926
148927
148928
148929
148930
148931
148932
148933
148934
148935namespace duckdb {
148936
148945};
148946
148948 INVALID,
148955};
148956
148959 REGULAR,
148963};
148964
148965struct ChunkManagementState {
148966 unordered_map<idx_t, BufferHandle> handles;
148968};
148969
148970struct ColumnDataAppendState {
148971 ChunkManagementState current_chunk_state;
148972 vector<UnifiedVectorFormat> vector_data;
148973};
148974
148975struct ColumnDataScanState {
148977 shared_ptr<DatabaseInstance>
db;
148978
148979 ChunkManagementState current_chunk_state;
148980 idx_t segment_index;
148981 idx_t chunk_index;
148982 idx_t current_row_index;
148983 idx_t next_row_index;
148985 vector<column_t> column_ids;
148986};
148987
148988struct ColumnDataParallelScanState {
148989 ColumnDataScanState scan_state;
148990 mutex lock;
148991};
148992
148993struct ColumnDataLocalScanState {
148994 ChunkManagementState current_chunk_state;
148995 idx_t current_segment_index = DConstants::INVALID_INDEX;
148996 idx_t current_row_index;
148997};
148998
148999class ColumnDataRow {
149000public:
149001 ColumnDataRow(DataChunk &chunk, idx_t row_index, idx_t base_index);
149002
149003 DataChunk &chunk;
149006
149007public:
149008 Value GetValue(idx_t column_index) const;
149009 idx_t RowIndex()
const;
149010};
149011
149012}
149013
149014
149015namespace duckdb {
149016class ColumnDataCollection;
149017
149018class ColumnDataChunkIterationHelper {
149019public:
149020 DUCKDB_API ColumnDataChunkIterationHelper(const ColumnDataCollection &collection, vector<column_t> column_ids);
149021
149022private:
149023 const ColumnDataCollection &collection;
149024 vector<column_t> column_ids;
149025
149026private:
149027 class ColumnDataChunkIterator;
149028
149029 class ColumnDataChunkIterator {
149030 public:
149031 DUCKDB_API ColumnDataChunkIterator(optional_ptr<const ColumnDataCollection> collection_p,
149032 vector<column_t> column_ids);
149034 DUCKDB_API ColumnDataChunkIterator(ColumnDataChunkIterator &&other) noexcept;
149035
149036 optional_ptr<const ColumnDataCollection> collection;
149037 ColumnDataScanState scan_state;
149038 unique_ptr<DataChunk> scan_chunk;
149040
149041 public:
149042 DUCKDB_API void Next();
149043
149044 DUCKDB_API ColumnDataChunkIterator &operator++();
149045 DUCKDB_API
bool operator!=(
const ColumnDataChunkIterator &other)
const;
149046 DUCKDB_API DataChunk &
operator*()
const;
149047 };
149048
149049public:
149050 ColumnDataChunkIterator begin() {
149051 return ColumnDataChunkIterator(&collection, column_ids);
149052 }
149053 ColumnDataChunkIterator end() {
149054 return ColumnDataChunkIterator(nullptr, vector<column_t>());
149055 }
149056};
149057
149058class ColumnDataRowIterationHelper {
149059public:
149060 DUCKDB_API explicit ColumnDataRowIterationHelper(const ColumnDataCollection &collection);
149061
149062private:
149063 const ColumnDataCollection &collection;
149064
149065private:
149066 class ColumnDataRowIterator;
149067
149068 class ColumnDataRowIterator {
149069 public:
149070 DUCKDB_API explicit ColumnDataRowIterator(
149071 const ColumnDataCollection *collection_p,
149072 ColumnDataScanProperties properties = ColumnDataScanProperties::DISALLOW_ZERO_COPY);
149073
149074 const ColumnDataCollection *collection;
149075 ColumnDataScanState scan_state;
149076 shared_ptr<DataChunk> scan_chunk;
149077 ColumnDataRow current_row;
149078
149079 public:
149080 void Next();
149081
149082 DUCKDB_API ColumnDataRowIterator &operator++();
149083 DUCKDB_API
bool operator!=(
const ColumnDataRowIterator &other)
const;
149084 DUCKDB_API
const ColumnDataRow &
operator*()
const;
149085 };
149086
149087public:
149088 DUCKDB_API ColumnDataRowIterator begin();
149089 DUCKDB_API ColumnDataRowIterator end();
149090};
149091
149092}
149093
149094
149095namespace duckdb {
149096
149097class BufferManager;
149098class BlockHandle;
149099class ClientContext;
149100struct ColumnDataCopyFunction;
149101class ColumnDataAllocator;
149102class ColumnDataCollection;
149103class ColumnDataCollectionSegment;
149104class ColumnDataRowCollection;
149105
149108class ColumnDataCollection {
149109public:
149111 DUCKDB_API ColumnDataCollection(Allocator &allocator, vector<LogicalType> types);
149113 DUCKDB_API explicit ColumnDataCollection(Allocator &allocator);
149115 DUCKDB_API
149116 ColumnDataCollection(BufferManager &buffer_manager, vector<LogicalType> types,
149117 ColumnDataCollectionLifetime lifetime = ColumnDataCollectionLifetime::REGULAR);
149119 DUCKDB_API
149120 ColumnDataCollection(ClientContext &context, vector<LogicalType> types,
149121 ColumnDataAllocatorType type = ColumnDataAllocatorType::BUFFER_MANAGER_ALLOCATOR,
149122 ColumnDataCollectionLifetime lifetime = ColumnDataCollectionLifetime::REGULAR);
149127 DUCKDB_API ColumnDataCollection(ColumnDataCollection &parent);
149128 DUCKDB_API ColumnDataCollection(shared_ptr<ColumnDataAllocator> allocator, vector<LogicalType> types);
149129 DUCKDB_API ~ColumnDataCollection();
149130
149131public:
149133 vector<LogicalType> &Types() {
149134 return types;
149135 }
149136 const vector<LogicalType> &Types() const {
149137 return types;
149138 }
149139
149141 const idx_t &Count()
const {
149142 return count;
149143 }
149144
149146 idx_t ColumnCount()
const {
149147 return types.size();
149148 }
149149
149151 idx_t SizeInBytes()
const;
149153 idx_t AllocationSize()
const;
149155 void SetPartitionIndex(idx_t index);
149156
149158 DUCKDB_API Allocator &GetAllocator() const;
149159
149161 DUCKDB_API void InitializeAppend(ColumnDataAppendState &state);
149163 DUCKDB_API void Append(ColumnDataAppendState &state, DataChunk &new_chunk);
149164
149166 DUCKDB_API void InitializeScanChunk(DataChunk &chunk) const;
149167 DUCKDB_API void InitializeScanChunk(Allocator &allocator, DataChunk &chunk) const;
149169 DUCKDB_API void InitializeScanChunk(ColumnDataScanState &state, DataChunk &chunk) const;
149171 DUCKDB_API void
149172 InitializeScan(ColumnDataScanState &state,
149173 ColumnDataScanProperties properties = ColumnDataScanProperties::ALLOW_ZERO_COPY) const;
149175 DUCKDB_API void
149176 InitializeScan(ColumnDataScanState &state, vector<column_t> column_ids,
149177 ColumnDataScanProperties properties = ColumnDataScanProperties::ALLOW_ZERO_COPY) const;
149179 DUCKDB_API void
149180 InitializeScan(ColumnDataParallelScanState &state,
149181 ColumnDataScanProperties properties = ColumnDataScanProperties::ALLOW_ZERO_COPY) const;
149183 DUCKDB_API void
149184 InitializeScan(ColumnDataParallelScanState &state, vector<column_t> column_ids,
149185 ColumnDataScanProperties properties = ColumnDataScanProperties::ALLOW_ZERO_COPY) const;
149187 DUCKDB_API bool Scan(ColumnDataScanState &state, DataChunk &result) const;
149189 DUCKDB_API bool Scan(ColumnDataParallelScanState &state, ColumnDataLocalScanState &lstate, DataChunk &result) const;
149190
149192 DUCKDB_API void Append(DataChunk &new_chunk);
149193
149195 DUCKDB_API void Combine(ColumnDataCollection &other);
149196
149197 DUCKDB_API void Verify();
149198
149199 DUCKDB_API string ToString() const;
149200 DUCKDB_API void Print() const;
149201
149202 DUCKDB_API void Reset();
149203
149205 DUCKDB_API
idx_t ChunkCount()
const;
149207 DUCKDB_API void FetchChunk(idx_t chunk_idx, DataChunk &result) const;
149208
149211 DUCKDB_API ColumnDataChunkIterationHelper Chunks() const;
149214 DUCKDB_API ColumnDataChunkIterationHelper Chunks(vector<column_t> column_ids) const;
149215
149218 DUCKDB_API ColumnDataRowIterationHelper Rows() const;
149219
149223 DUCKDB_API ColumnDataRowCollection GetRows() const;
149224
149228 static bool ResultEquals(const ColumnDataCollection &left, const ColumnDataCollection &right, string &error_message,
149229 bool ordered = false);
149230
149232 bool NextScanIndex(ColumnDataScanState &state, idx_t &chunk_index, idx_t &segment_index, idx_t &row_index) const;
149234 bool PrevScanIndex(ColumnDataScanState &state, idx_t &chunk_index, idx_t &segment_index, idx_t &row_index) const;
149236 void ScanAtIndex(ColumnDataParallelScanState &state, ColumnDataLocalScanState &lstate, DataChunk &result,
149237 idx_t chunk_index, idx_t segment_index, idx_t row_index) const;
149238
149242 bool Seek(idx_t row_idx, ColumnDataScanState &state, DataChunk &result) const;
149243
149245 void Initialize(vector<LogicalType> types);
149246
149248 vector<shared_ptr<StringHeap>> GetHeapReferences();
149252 BufferManager &GetBufferManager() const;
149253
149255 const vector<unique_ptr<ColumnDataCollectionSegment>> &GetSegments() const;
149256
149257 void Serialize(Serializer &serializer) const;
149258 static unique_ptr<ColumnDataCollection> Deserialize(Deserializer &deserializer);
149259
149260private:
149262 void CreateSegment();
149263
149264 static ColumnDataCopyFunction GetCopyFunction(const LogicalType &type);
149265
149266private:
149268 buffer_ptr<ColumnDataAllocator> allocator;
149270 vector<LogicalType> types;
149274 vector<unique_ptr<ColumnDataCollectionSegment>> segments;
149276 vector<ColumnDataCopyFunction> copy_functions;
149278 bool finished_append;
149280 optional_idx partition_index;
149281};
149282
149284class ColumnDataRowCollection {
149285public:
149286 DUCKDB_API explicit ColumnDataRowCollection(
149287 const ColumnDataCollection &collection,
149288 ColumnDataScanProperties properties = ColumnDataScanProperties::DISALLOW_ZERO_COPY);
149289
149290public:
149291 DUCKDB_API Value GetValue(idx_t column, idx_t index) const;
149292
149293public:
149294
149295 bool empty() const {
149296 return rows.empty();
149297 }
149299 return rows.size();
149300 }
149301
149302 DUCKDB_API ColumnDataRow &operator[](idx_t i);
149303 DUCKDB_API const ColumnDataRow &operator[](idx_t i) const;
149304
149305 vector<ColumnDataRow>::iterator begin() {
149306 return rows.begin();
149307 }
149308 vector<ColumnDataRow>::iterator end() {
149309 return rows.end();
149310 }
149311 vector<ColumnDataRow>::const_iterator cbegin() const {
149312 return rows.cbegin();
149313 }
149314 vector<ColumnDataRow>::const_iterator cend() const {
149315 return rows.cend();
149316 }
149317 vector<ColumnDataRow>::const_iterator begin() const {
149318 return rows.begin();
149319 }
149320 vector<ColumnDataRow>::const_iterator end() const {
149321 return rows.end();
149322 }
149323
149324private:
149325 vector<ColumnDataRow>
rows;
149326 vector<unique_ptr<DataChunk>> chunks;
149327 ColumnDataScanState scan_state;
149328};
149329
149330}
149331
149332
149333
149334
149335
149336
149337
149338
149339
149340
149341
149342
149343
149344
149345
149346
149347
149348
149349
149350
149351
149352
149353
149354
149355
149356
149357
149358
149359
149360
149361
149362
149363
149364
149365
149366
149367
149368namespace duckdb {
149369
149370enum class QueryResultOutputType :
uint8_t { FORCE_MATERIALIZED, ALLOW_STREAMING };
149371
149373
149374struct QueryParameters {
149375 QueryParameters() {
149376 }
149377 QueryParameters(bool allow_streaming)
149378 : output_type(allow_streaming ? QueryResultOutputType::ALLOW_STREAMING
149379 : QueryResultOutputType::FORCE_MATERIALIZED) {
149380 }
149381 QueryParameters(QueryResultOutputType output_type)
149382 : output_type(output_type) {
149383 }
149384 QueryResultOutputType output_type = QueryResultOutputType::FORCE_MATERIALIZED;
149385 QueryResultMemoryType memory_type = QueryResultMemoryType::IN_MEMORY;
149386};
149387
149388}
149389
149390
149391
149392
149393
149394
149395
149396
149397
149398
149399
149400
149401
149402namespace duckdb {
149403
149404struct DatabaseModificationType {
149405public:
149406 static constexpr idx_t INSERT_DATA = 1ULL << 0ULL;
149407 static constexpr idx_t DELETE_DATA = 1ULL << 1ULL;
149408 static constexpr idx_t UPDATE_DATA = 1ULL << 2ULL;
149409 static constexpr idx_t ALTER_TABLE = 1ULL << 3ULL;
149410 static constexpr idx_t CREATE_CATALOG_ENTRY = 1ULL << 4ULL;
149411 static constexpr idx_t DROP_CATALOG_ENTRY = 1ULL << 5ULL;
149412 static constexpr idx_t SEQUENCE = 1ULL << 6ULL;
149413 static constexpr idx_t CREATE_INDEX = 1ULL << 7ULL;
149414
149415 constexpr DatabaseModificationType() : value(0) {
149416 }
149417 constexpr DatabaseModificationType(idx_t value) : value(value) {
149418 }
149419
149420 inline constexpr DatabaseModificationType
operator|(DatabaseModificationType b)
const {
149421 return DatabaseModificationType(value | b.value);
149422 }
149423 inline DatabaseModificationType &
operator|=(DatabaseModificationType b) {
149424 value |= b.value;
149425 return *this;
149426 }
149427
149428 bool InsertData() const {
149429 return value & INSERT_DATA;
149430 }
149431 bool DeleteData() const {
149432 return value & DELETE_DATA;
149433 }
149434 bool UpdateData() const {
149435 return value & UPDATE_DATA;
149436 }
149437 bool AlterTable() const {
149438 return value & ALTER_TABLE;
149439 }
149440 bool CreateCatalogEntry() const {
149441 return value & CREATE_CATALOG_ENTRY;
149442 }
149443 bool DropCatalogEntry() const {
149444 return value & DROP_CATALOG_ENTRY;
149445 }
149446 bool Sequence() const {
149447 return value & SEQUENCE;
149448 }
149449 bool CreateIndex() const {
149450 return value & CREATE_INDEX;
149451 }
149452
149453private:
149455};
149456
149457}
149458
149459
149460namespace duckdb {
149461
149462
149463
149464
149465enum class StatementType :
uint8_t {
149466 INVALID_STATEMENT,
149467 SELECT_STATEMENT,
149468 INSERT_STATEMENT,
149469 UPDATE_STATEMENT,
149470 CREATE_STATEMENT,
149471 DELETE_STATEMENT,
149472 PREPARE_STATEMENT,
149473 EXECUTE_STATEMENT,
149474 ALTER_STATEMENT,
149475 TRANSACTION_STATEMENT,
149476 COPY_STATEMENT,
149477 ANALYZE_STATEMENT,
149478 VARIABLE_SET_STATEMENT,
149479 CREATE_FUNC_STATEMENT,
149480 EXPLAIN_STATEMENT,
149481 DROP_STATEMENT,
149482 EXPORT_STATEMENT,
149483 PRAGMA_STATEMENT,
149484 VACUUM_STATEMENT,
149485 CALL_STATEMENT,
149486 SET_STATEMENT,
149487 LOAD_STATEMENT,
149488 RELATION_STATEMENT,
149489 EXTENSION_STATEMENT,
149490 LOGICAL_PLAN_STATEMENT,
149491 ATTACH_STATEMENT,
149492 DETACH_STATEMENT,
149493 MULTI_STATEMENT,
149494 COPY_DATABASE_STATEMENT,
149495 UPDATE_EXTENSIONS_STATEMENT,
149496 MERGE_INTO_STATEMENT
149497};
149498
149499DUCKDB_API string StatementTypeToString(StatementType type);
149500
149501enum class StatementReturnType :
uint8_t {
149502 QUERY_RESULT,
149503 CHANGED_ROWS,
149504 NOTHING
149505};
149506
149507string StatementReturnTypeToString(StatementReturnType type);
149508
149509class Catalog;
149510class ClientContext;
149511
149513struct StatementProperties {
149514 StatementProperties()
149515 : requires_valid_transaction(true), output_type(QueryResultOutputType::FORCE_MATERIALIZED),
149516 bound_all_parameters(true), return_type(StatementReturnType::QUERY_RESULT), parameter_count(0),
149517 always_require_rebind(false) {
149518 }
149519
149520 struct CatalogIdentity {
149521 idx_t catalog_oid;
149522 optional_idx catalog_version;
149523
149524 bool operator==(
const CatalogIdentity &rhs)
const {
149525 return catalog_oid == rhs.catalog_oid && catalog_version == rhs.catalog_version;
149526 }
149527
149528 bool operator!=(
const CatalogIdentity &rhs)
const {
149530 }
149531 };
149532
149533 struct ModificationInfo {
149534 CatalogIdentity identity;
149535 DatabaseModificationType modifications;
149536 };
149537
149539 unordered_map<string, CatalogIdentity> read_databases;
149541 unordered_map<string, ModificationInfo> modified_databases;
149544 bool requires_valid_transaction;
149546 QueryResultOutputType output_type;
149548 bool bound_all_parameters;
149550 StatementReturnType return_type;
149552 idx_t parameter_count;
149554 bool always_require_rebind;
149555
149556 bool IsReadOnly() {
149557 return modified_databases.empty();
149558 }
149559
149560 void RegisterDBRead(Catalog &catalog, ClientContext &context);
149561 void RegisterDBModify(Catalog &catalog, ClientContext &context, DatabaseModificationType modification);
149562};
149563
149564}
149565
149566
149567
149568
149569
149570
149571
149572
149573
149574
149575
149576
149577
149578
149579
149580
149581
149582
149583
149584
149585
149586
149587
149588
149589
149590
149591
149592
149593namespace duckdb {
149594
149595enum class ArrowOffsetSize :
uint8_t { REGULAR, LARGE };
149596
149611};
149612
149613}
149614
149615
149616namespace duckdb {
149617
149619struct ClientProperties {
149620 ClientProperties(string time_zone_p, const ArrowOffsetSize arrow_offset_size_p, const bool arrow_use_list_view_p,
149621 const bool produce_arrow_string_view_p, const bool lossless_conversion,
149622 const ArrowFormatVersion arrow_output_version, const optional_ptr<ClientContext> client_context)
149623 : time_zone(std::move(time_zone_p)), arrow_offset_size(arrow_offset_size_p),
149624 arrow_use_list_view(arrow_use_list_view_p), produce_arrow_string_view(produce_arrow_string_view_p),
149625 arrow_lossless_conversion(lossless_conversion), arrow_output_version(arrow_output_version),
149626 client_context(client_context) {
149627 }
149628 ClientProperties() {};
149629
149630 string time_zone = "UTC";
149631 ArrowOffsetSize arrow_offset_size = ArrowOffsetSize::REGULAR;
149632 bool arrow_use_list_view = false;
149633 bool produce_arrow_string_view = false;
149634 bool arrow_lossless_conversion = false;
149636 optional_ptr<ClientContext> client_context;
149637};
149638}
149639
149640
149641namespace duckdb {
149642struct BoxRendererConfig;
149643
149644enum class QueryResultType :
uint8_t { MATERIALIZED_RESULT, STREAM_RESULT, PENDING_RESULT, ARROW_RESULT };
149645
149646class BaseQueryResult {
149647public:
149649 DUCKDB_API BaseQueryResult(QueryResultType type, StatementType statement_type, StatementProperties properties,
149650 vector<LogicalType> types, vector<string> names);
149652 DUCKDB_API BaseQueryResult(QueryResultType type, ErrorData error);
149653 DUCKDB_API virtual ~BaseQueryResult();
149654
149656 QueryResultType type;
149658 StatementType statement_type;
149660 StatementProperties properties;
149662 vector<LogicalType> types;
149664 vector<string> names;
149665
149666public:
149667 [[noreturn]] DUCKDB_API void ThrowError(const string &prepended_message = "") const;
149668 DUCKDB_API
void SetError(ErrorData error);
149669 DUCKDB_API bool HasError() const;
149670 DUCKDB_API const ExceptionType &GetErrorType() const;
149671 DUCKDB_API const std::string &GetError() const;
149672 DUCKDB_API ErrorData &GetErrorObject();
149673 DUCKDB_API
idx_t ColumnCount();
149674
149675protected:
149677 bool success;
149679 ErrorData error;
149680};
149681
149685class QueryResult : public BaseQueryResult {
149686public:
149688 DUCKDB_API QueryResult(QueryResultType type, StatementType statement_type, StatementProperties properties,
149689 vector<LogicalType> types, vector<string> names, ClientProperties client_properties);
149691 DUCKDB_API QueryResult(QueryResultType type, ErrorData error);
149692 DUCKDB_API ~QueryResult() override;
149693
149695 ClientProperties client_properties;
149697 unique_ptr<QueryResult> next;
149698
149699public:
149700 template <class TARGET>
149701 TARGET &Cast() {
149702 if (type != TARGET::TYPE) {
149703 throw InternalException("Failed to cast query result to type - query result type mismatch");
149704 }
149705 return reinterpret_cast<TARGET &>(*this);
149706 }
149707
149708 template <class TARGET>
149709 const TARGET &Cast() const {
149710 if (type != TARGET::TYPE) {
149711 throw InternalException("Failed to cast query result to type - query result type mismatch");
149712 }
149713 return reinterpret_cast<const TARGET &>(*this);
149714 }
149715
149716public:
149718 static void DeduplicateColumns(vector<string> &names);
149719
149720public:
149722 DUCKDB_API const string &ColumnName(idx_t index) const;
149725 DUCKDB_API unique_ptr<DataChunk> Fetch();
149728 DUCKDB_API unique_ptr<DataChunk> FetchRaw();
149730 DUCKDB_API virtual string ToString() = 0;
149732 DUCKDB_API virtual string ToBox(ClientContext &context, const BoxRendererConfig &config);
149734 DUCKDB_API void Print();
149737 DUCKDB_API bool Equals(QueryResult &other);
149738
149739 bool TryFetch(unique_ptr<DataChunk> &result, ErrorData &error) {
149740 try {
149741 result = Fetch();
149742 return success;
149743 } catch (std::exception &ex) {
149744 error = ErrorData(ex);
149745 return false;
149746 } catch (...) {
149747 error = ErrorData("Unknown error in Fetch");
149748 return false;
149749 }
149750 }
149751
149752protected:
149753 DUCKDB_API virtual unique_ptr<DataChunk> FetchInternal() = 0;
149754
149755private:
149756 class QueryResultIterator;
149757 class QueryResultRow {
149758 friend class QueryResultIterator;
149759
149760 public:
149761 explicit QueryResultRow() : row(0) {
149762 }
149763
149764 bool IsNull(idx_t col_idx) const {
149765 return chunk->GetValue(col_idx, row).IsNull();
149766 }
149767 template <class T>
149768 T GetValue(idx_t col_idx) const {
149769 return chunk->GetValue(col_idx, row).GetValue<T>();
149770 }
149771 Value GetBaseValue(idx_t col_idx) const {
149772 return chunk->GetValue(col_idx, row);
149773 }
149774 DataChunk &GetChunk() const {
149775 return *chunk;
149776 }
149777 idx_t GetRowInChunk()
const {
149778 return row;
149779 }
149780
149781 private:
149782 shared_ptr<DataChunk> chunk;
149784 };
149786 class QueryResultIterator {
149787 public:
149788 explicit QueryResultIterator(optional_ptr<QueryResult> result_p = nullptr) : result(result_p), base_row(0) {
149789 if (result) {
149790 current_row.chunk = shared_ptr<DataChunk>(result->Fetch().release());
149791 if (!current_row.chunk) {
149792 result = nullptr;
149793 }
149794 }
149795 }
149796
149797 QueryResultRow current_row;
149798 optional_ptr<QueryResult> result;
149800
149801 public:
149802 void Next() {
149803 if (!current_row.chunk) {
149804 return;
149805 }
149806 current_row.row++;
149807 if (current_row.row >= current_row.chunk->size()) {
149808 base_row += current_row.chunk->size();
149809 current_row.chunk = shared_ptr<DataChunk>(result->Fetch().release());
149810 current_row.row = 0;
149811 if (!current_row.chunk || current_row.chunk->size() == 0) {
149812
149813 base_row = 0;
149814 result = nullptr;
149815 current_row.chunk.reset();
149816 }
149817 }
149818 }
149819
149820 QueryResultIterator &operator++() {
149821 Next();
149822 return *this;
149823 }
149824 bool operator!=(
const QueryResultIterator &other)
const {
149825 return result != other.result || base_row != other.base_row || current_row.row != other.current_row.row;
149826 }
149827 bool operator==(
const QueryResultIterator &other)
const {
149828 return !(*this != other);
149829 }
149830 const QueryResultRow &
operator*()
const {
149831 return current_row;
149832 }
149833 };
149834
149835public:
149836 using iterator = QueryResultIterator;
149837
149838 iterator begin() {
149839 return QueryResultIterator(this);
149840 }
149841 iterator end() {
149842 return QueryResultIterator(nullptr);
149843 }
149844
149845protected:
149846 DUCKDB_API string HeaderToString();
149847
149848private:
149849 QueryResult(const QueryResult &) = delete;
149850};
149851
149852}
149853
149854
149855namespace duckdb {
149856
149857class ClientContext;
149858
149859class MaterializedQueryResult : public QueryResult {
149860public:
149861 static constexpr const QueryResultType
TYPE = QueryResultType::MATERIALIZED_RESULT;
149862
149863public:
149864 friend class ClientContext;
149866 DUCKDB_API MaterializedQueryResult(StatementType statement_type, StatementProperties properties,
149867 vector<string> names, unique_ptr<ColumnDataCollection> collection,
149868 ClientProperties client_properties);
149870 DUCKDB_API explicit MaterializedQueryResult(ErrorData error);
149871
149872public:
149874 DUCKDB_API string ToString() override;
149875 DUCKDB_API string ToBox(ClientContext &context, const BoxRendererConfig &config) override;
149876
149879 DUCKDB_API Value GetValue(idx_t column, idx_t index);
149880
149881 template <class T>
149882 T GetValue(idx_t column, idx_t index) {
149883 auto value = GetValue(column, index);
149884 return (T)value.GetValue<
int64_t>();
149885 }
149886
149887 DUCKDB_API
idx_t RowCount()
const;
149888
149890 ColumnDataCollection &Collection();
149891
149893 unique_ptr<ColumnDataCollection> TakeCollection();
149894
149895protected:
149896 DUCKDB_API unique_ptr<DataChunk> FetchInternal() override;
149897
149898private:
149899 unique_ptr<ColumnDataCollection> collection;
149901 unique_ptr<ColumnDataRowCollection> row_collection;
149903 ColumnDataScanState scan_state;
149904 bool scan_initialized;
149905};
149906
149907}
149908
149909
149910
149911
149912
149913
149914
149915
149916
149917
149918
149919
149920
149921
149922
149923
149924
149925
149926
149927
149928
149929
149930
149931
149932namespace duckdb {
149933
149934enum class PendingExecutionResult :
uint8_t {
149935 RESULT_READY,
149936 RESULT_NOT_READY,
149937 EXECUTION_ERROR,
149938 BLOCKED,
149939 NO_TASKS_AVAILABLE,
149940 EXECUTION_FINISHED
149941};
149942
149943}
149944
149945
149946
149947
149948
149949
149950
149951
149952
149953
149954
149955
149956
149957
149958
149959
149960
149961
149962
149963
149964
149965
149966
149967
149968
149969
149970
149971
149972
149973
149974
149975
149976namespace duckdb {
149977
149978class TaskErrorManager {
149979public:
149980 TaskErrorManager() : has_error(false) {
149981 }
149982
149983 void PushError(ErrorData error) {
149984 lock_guard<mutex> elock(error_lock);
149985 this->exceptions.push_back(std::move(error));
149986 has_error = true;
149987 }
149988
149989 ErrorData GetError() {
149990 lock_guard<mutex> elock(error_lock);
149991 D_ASSERT(!exceptions.empty());
149992
149993
149994
149995
149996 auto &entry = exceptions[0];
149997 return entry;
149998 }
149999
150000 bool HasError() {
150001 return has_error;
150002 }
150003
150004 void ThrowException() {
150005 lock_guard<mutex> elock(error_lock);
150006 D_ASSERT(!exceptions.empty());
150007 auto &entry = exceptions[0];
150008 entry.Throw();
150009 }
150010
150011 void Reset() {
150012 lock_guard<mutex> elock(error_lock);
150013 exceptions.clear();
150014 has_error = false;
150015 }
150016
150017private:
150018 mutex error_lock;
150020 vector<ErrorData> exceptions;
150022 atomic<bool> has_error;
150023};
150024}
150025
150026
150027
150028
150029
150030
150031
150032
150033
150034
150035
150036
150037
150038namespace duckdb {
150039
150040struct ProgressData {
150041 double done = 0.0;
150042 double total = 0.0;
150043 bool invalid = false;
150044
150045public:
150046 double ProgressDone() const {
150047
150048 D_ASSERT(IsValid());
150049
150050 return done / total;
150051 }
150052
150053 void Add(const ProgressData &other) {
150054
150055 done += other.done;
150056 total += other.total;
150057 invalid = invalid || other.invalid;
150058 }
150059 void Normalize(const double target = 1.0) {
150060
150061 D_ASSERT(target > 0.0);
150062 if (IsValid()) {
150063 if (total > 0.0) {
150064 done /= total;
150065 }
150066 total = 1.0;
150067 done *= target;
150068 total *= target;
150069 } else {
150070 SetInvalid();
150071 }
150072 }
150073 void SetInvalid() {
150074 invalid = true;
150075 done = 0.0;
150076 total = 1.0;
150077 }
150078 bool IsValid() const {
150079 return (!invalid) && (done >= 0.0) && (done <= total) && (total >= 0.0);
150080 }
150081};
150082
150083}
150084
150085
150086
150087
150088
150089
150090
150091
150092
150093
150094
150095
150096
150097
150098
150099
150100
150101
150102
150103
150104
150105
150106
150107
150108
150109
150110
150111
150112
150113#include <type_traits>
150114
150115namespace duckdb {
150116
150117template <class T>
150118class ArenaLinkedList {
150119public:
150120 static_assert(std::is_trivially_destructible<T>::value, "T must be trivially destructible");
150121
150122public:
150123 explicit ArenaLinkedList(ArenaAllocator &arena) : arena(arena) {
150124 }
150125
150126 ArenaLinkedList(const ArenaLinkedList &) = delete;
150127 ArenaLinkedList &
operator=(
const ArenaLinkedList &) =
delete;
150128
150129 ArenaLinkedList(ArenaLinkedList &&other) noexcept : head(other.head), tail(other.tail) {
150130 other.head = nullptr;
150131 other.tail = nullptr;
150132 }
150133 ArenaLinkedList &
operator=(ArenaLinkedList &&other)
noexcept {
150134 if (this != &other) {
150135 head = other.head;
150136 tail = other.tail;
150137 other.head = nullptr;
150138 other.tail = nullptr;
150139 }
150140 return *this;
150141 }
150142
150143public:
150144 bool empty() const {
150145 return head == nullptr;
150146 }
150147
150149 return _size;
150150 }
150151
150152 void push_back(const T &value) {
150153 auto node = arena.Make<Node>(value);
150154 auto ptr = head ? &tail->next : &head;
150155 *ptr = node;
150156 tail = node;
150157 _size++;
150158 }
150159
150160 template <class... ARGS>
150161 void emplace_back(ARGS &&... args) {
150162 auto node = arena.Make<Node>(std::forward<ARGS>(args)...);
150163 auto ptr = head ? &tail->next : &head;
150164 *ptr = node;
150165 tail = node;
150166 _size++;
150167 }
150168
150170 T &operator[](const idx_t index) {
150172 for (auto &elem : *this) {
150173 if (i == index) {
150174 return elem;
150175 }
150176 i++;
150177 }
150178 throw InternalException("index out of bounds in ArenaLinkedList");
150179 }
150180
150182 const T &operator[](const idx_t index) const {
150184 for (const auto &elem : *this) {
150185 if (i == index) {
150186 return elem;
150187 }
150188 i++;
150189 }
150190 throw InternalException("index out of bounds in ArenaLinkedList");
150191 }
150192
150193 struct Iterator;
150194 struct ConstIterator;
150195
150196 Iterator begin();
150197 Iterator end();
150198 ConstIterator begin() const;
150199 ConstIterator end() const;
150200
150201private:
150202 struct Node {
150203 explicit Node(const T &value_p) : next(nullptr), value(value_p) {
150204 }
150205 Node *next;
150206 T value;
150207 };
150208
150209 ArenaAllocator &arena;
150210 Node *head = nullptr;
150211 Node *tail = nullptr;
150213};
150214
150215template <class T>
150216struct ArenaLinkedList<T>::Iterator {
150217 Node *node;
150218
150219 explicit Iterator(Node *node_p) : node(node_p) {
150220 }
150221
150223 return node->value;
150224 }
150225
150226 Iterator &operator++() {
150227 node = node->next;
150228 return *this;
150229 }
150230
150231 bool operator!=(
const Iterator &other)
const {
150232 return node != other.node;
150233 }
150234};
150235
150236template <class T>
150237struct ArenaLinkedList<T>::ConstIterator {
150238 const Node *node;
150239
150240 explicit ConstIterator(const Node *node_p) : node(node_p) {
150241 }
150242
150244 return node->value;
150245 }
150246
150247 ConstIterator &operator++() {
150248 node = node->next;
150249 return *this;
150250 }
150251
150252 bool operator!=(
const ConstIterator &other)
const {
150253 return node != other.node;
150254 }
150255};
150256
150257template <class T>
150258typename ArenaLinkedList<T>::Iterator ArenaLinkedList<T>::begin() {
150259 return Iterator(head);
150260}
150261
150262template <class T>
150263typename ArenaLinkedList<T>::Iterator ArenaLinkedList<T>::end() {
150264 return Iterator(nullptr);
150265}
150266
150267template <class T>
150268typename ArenaLinkedList<T>::ConstIterator ArenaLinkedList<T>::begin() const {
150269 return ConstIterator(head);
150270}
150271
150272template <class T>
150273typename ArenaLinkedList<T>::ConstIterator ArenaLinkedList<T>::end() const {
150274 return ConstIterator(nullptr);
150275}
150276
150277}
150278
150279
150280
150281
150282
150283
150284
150285
150286
150287
150288
150289
150290
150291
150292
150293namespace duckdb {
150294
150295enum class ExplainFormat :
uint8_t { DEFAULT, TEXT, JSON, HTML, GRAPHVIZ, YAML, MERMAID };
150296
150297}
150298
150299
150300
150301
150302
150303
150304
150305
150306
150307
150308
150309
150310
150311namespace duckdb {
150312
150326
150331
150334
150342
150345 INVALID,
150346 IMPLICIT,
150347
150348 HAVE_MORE_OUTPUT,
150349
150350 FINISHED,
150351 BLOCKED
150352
150353};
150354
150355bool ExtractSourceResultType(AsyncResultType in, SourceResultType &out);
150356
150363
150364
150365enum class SinkCombineResultType :
uint8_t { FINISHED, BLOCKED };
150366
150373
150379
150380}
150381
150382
150383
150384
150385
150386
150387
150388
150389
150390
150391
150392
150393
150394namespace duckdb {
150395
150396
150397
150398
150399enum class OrderPreservationType :
uint8_t {
150400 NO_ORDER,
150401 INSERTION_ORDER,
150402 FIXED_ORDER
150403};
150404
150405}
150406
150407
150408
150409
150410
150411
150412
150413
150414
150415
150416
150417
150418
150419namespace duckdb {
150420
150421
150422
150423
150424enum class PhysicalOperatorType :
uint8_t {
150425 INVALID,
150426 ORDER_BY,
150427 LIMIT,
150428 STREAMING_LIMIT,
150429 LIMIT_PERCENT,
150430 TOP_N,
150431 WINDOW,
150432 UNNEST,
150433 UNGROUPED_AGGREGATE,
150434 HASH_GROUP_BY,
150435 PERFECT_HASH_GROUP_BY,
150436 PARTITIONED_AGGREGATE,
150437 FILTER,
150438 PROJECTION,
150439 COPY_TO_FILE,
150440 BATCH_COPY_TO_FILE,
150441 RESERVOIR_SAMPLE,
150442 STREAMING_SAMPLE,
150443 STREAMING_WINDOW,
150444 PIVOT,
150445 COPY_DATABASE,
150446
150447
150448
150449
150450 TABLE_SCAN,
150451 DUMMY_SCAN,
150452 COLUMN_DATA_SCAN,
150453 CHUNK_SCAN,
150454 RECURSIVE_CTE_SCAN,
150455 RECURSIVE_RECURRING_CTE_SCAN,
150456 CTE_SCAN,
150457 DELIM_SCAN,
150458 EXPRESSION_SCAN,
150459 POSITIONAL_SCAN,
150460
150461
150462
150463 BLOCKWISE_NL_JOIN,
150464 NESTED_LOOP_JOIN,
150465 HASH_JOIN,
150466 CROSS_PRODUCT,
150467 PIECEWISE_MERGE_JOIN,
150468 IE_JOIN,
150469 LEFT_DELIM_JOIN,
150470 RIGHT_DELIM_JOIN,
150471 POSITIONAL_JOIN,
150472 ASOF_JOIN,
150473
150474
150475
150476 UNION,
150477 RECURSIVE_CTE,
150478 RECURSIVE_KEY_CTE,
150479 CTE,
150480
150481
150482
150483
150484 INSERT,
150485 BATCH_INSERT,
150486 DELETE_OPERATOR,
150487 UPDATE,
150488 MERGE_INTO,
150489
150490
150491
150492
150493 CREATE_TABLE,
150494 CREATE_TABLE_AS,
150495 BATCH_CREATE_TABLE_AS,
150496 CREATE_INDEX,
150497 ALTER,
150498 CREATE_SEQUENCE,
150499 CREATE_VIEW,
150500 CREATE_SCHEMA,
150501 CREATE_MACRO,
150502 DROP,
150503 PRAGMA,
150504 TRANSACTION,
150505 CREATE_TYPE,
150506 ATTACH,
150507 DETACH,
150508
150509
150510
150511
150512 EXPLAIN,
150513 EXPLAIN_ANALYZE,
150514 EMPTY_RESULT,
150515 EXECUTE,
150516 PREPARE,
150517 VACUUM,
150518 EXPORT,
150519 SET,
150520 SET_VARIABLE,
150521 LOAD,
150522 INOUT_FUNCTION,
150523 RESULT_COLLECTOR,
150524 RESET,
150525 EXTENSION,
150526 VERIFY_VECTOR,
150527 UPDATE_EXTENSIONS,
150528
150529
150530
150531
150532 CREATE_SECRET,
150533};
150534
150535string PhysicalOperatorToString(PhysicalOperatorType type);
150536
150537}
150538
150539
150540
150541
150542
150543
150544
150545
150546
150547
150548
150549
150550
150551
150552
150553
150554namespace duckdb {
150555class ClientContext;
150556class ThreadContext;
150557class Pipeline;
150558
150559class ExecutionContext {
150560public:
150561 ExecutionContext(ClientContext &client_p, ThreadContext &thread_p, optional_ptr<Pipeline> pipeline_p)
150562 : client(client_p), thread(thread_p), pipeline(pipeline_p) {
150563 }
150564
150566 ClientContext &client;
150568 ThreadContext &thread;
150570 optional_ptr<Pipeline> pipeline;
150571};
150572
150573}
150574
150575
150576
150577
150578
150579
150580
150581
150582
150583
150584
150585
150586
150587
150588
150589namespace duckdb {
150590
150591enum class PartitionInfo { NONE, REQUIRES_BATCH_INDEX };
150592
150593struct ColumnPartitionData {
150594 explicit ColumnPartitionData(Value partition_val) : min_val(partition_val), max_val(std::move(partition_val)) {
150595 }
150596
150597 Value min_val;
150598 Value max_val;
150599};
150600
150601struct SourcePartitionInfo {
150607 optional_idx batch_index;
150609 optional_idx min_batch_index;
150611 vector<ColumnPartitionData> partition_data;
150612};
150613
150614struct OperatorPartitionInfo {
150615 OperatorPartitionInfo() = default;
150616 explicit OperatorPartitionInfo(bool batch_index) : batch_index(batch_index) {
150617 }
150618 explicit OperatorPartitionInfo(vector<column_t> partition_columns_p)
150619 : partition_columns(std::move(partition_columns_p)) {
150620 }
150621
150622 bool batch_index = false;
150623 vector<column_t> partition_columns;
150624
150625 static OperatorPartitionInfo NoPartitionInfo() {
150626 return OperatorPartitionInfo(false);
150627 }
150628 static OperatorPartitionInfo BatchIndex() {
150629 return OperatorPartitionInfo(true);
150630 }
150631 static OperatorPartitionInfo PartitionColumns(vector<column_t> columns) {
150632 return OperatorPartitionInfo(std::move(columns));
150633 }
150634 bool RequiresPartitionColumns() const {
150635 return !partition_columns.empty();
150636 }
150637 bool RequiresBatchIndex() const {
150638 return batch_index;
150639 }
150640 bool AnyRequired() const {
150641 return RequiresPartitionColumns() || RequiresBatchIndex();
150642 }
150643};
150644
150645struct OperatorPartitionData {
150646 explicit OperatorPartitionData(idx_t batch_index) : batch_index(batch_index) {
150647 }
150648
150649 idx_t batch_index;
150650 vector<ColumnPartitionData> partition_data;
150651};
150652
150653}
150654
150655
150656
150657
150658
150659
150660
150661
150662
150663
150664
150665
150666
150667
150668
150669
150670
150671
150672
150673
150674
150675
150676
150677
150678
150679
150680
150681
150682
150683
150684
150685
150686
150687
150688
150689
150690
150691
150692
150693
150694namespace duckdb {
150695
150697struct JoinRelationSet {
150698 JoinRelationSet(unsafe_unique_array<idx_t> relations, idx_t count) : relations(std::move(relations)), count(count) {
150699 }
150700
150701 string ToString() const;
150702
150703 unsafe_unique_array<idx_t> relations;
150705
150706 static bool IsSubset(JoinRelationSet &super, JoinRelationSet &sub);
150707};
150708
150711class JoinRelationSetManager {
150712public:
150714
150715 struct JoinRelationTreeNode {
150716 unique_ptr<JoinRelationSet> relation;
150717 unordered_map<idx_t, unique_ptr<JoinRelationTreeNode>> children;
150718 };
150719
150720public:
150722 JoinRelationSet &GetJoinRelation(idx_t index);
150724 JoinRelationSet &GetJoinRelation(const unordered_set<idx_t> &bindings);
150726 JoinRelationSet &GetJoinRelation(unsafe_unique_array<idx_t> relations, idx_t count);
150728 JoinRelationSet &Union(JoinRelationSet &left, JoinRelationSet &right);
150729
150730
150731 string ToString() const;
150732 void Print();
150733
150734private:
150735 JoinRelationTreeNode root;
150736};
150737
150738}
150739
150740
150741
150742
150743
150744
150745
150746
150747
150748
150749
150750
150751
150752
150753
150754
150755
150756
150757
150758
150759
150760
150761
150762
150763
150764
150765
150766
150767
150768
150769
150770
150771
150772
150773
150774
150775
150776
150777
150778
150779
150780
150781
150782
150783
150784
150785
150786
150787
150788
150789
150790
150791
150792
150793
150794
150795
150796
150797
150798
150799
150800
150801#include <functional>
150802
150803namespace duckdb {
150804class Serializer;
150805class Deserializer;
150806
150807struct ColumnBinding {
150808 idx_t table_index;
150809
150810 idx_t column_index;
150811
150812 ColumnBinding() : table_index(DConstants::INVALID_INDEX), column_index(DConstants::INVALID_INDEX) {
150813 }
150814 ColumnBinding(idx_t table, idx_t column) : table_index(table), column_index(column) {
150815 }
150816
150817 string ToString() const {
150819 }
150820
150821 bool operator==(
const ColumnBinding &rhs)
const {
150822 return table_index == rhs.table_index && column_index == rhs.column_index;
150823 }
150824
150825 bool operator!=(
const ColumnBinding &rhs)
const {
150826 return !(*this == rhs);
150827 }
150828
150829 void Serialize(Serializer &serializer) const;
150830 static ColumnBinding Deserialize(Deserializer &deserializer);
150831};
150832
150833}
150834
150835
150836namespace duckdb {
150837
150838struct ColumnBindingHashFunction {
150840 return CombineHash(Hash<idx_t>(a.table_index), Hash<idx_t>(a.column_index));
150841 }
150842};
150843
150844struct ColumnBindingEquality {
150845 bool operator()(
const ColumnBinding &a,
const ColumnBinding &b)
const {
150846 return a == b;
150847 }
150848};
150849
150850template <typename T>
150851using column_binding_map_t = unordered_map<ColumnBinding, T, ColumnBindingHashFunction, ColumnBindingEquality>;
150852
150853using column_binding_set_t = unordered_set<ColumnBinding, ColumnBindingHashFunction, ColumnBindingEquality>;
150854
150855}
150856
150857
150858
150859
150860
150861
150862
150863
150864
150865
150866
150867
150868
150869
150870
150871
150872
150873
150874
150875
150876
150877
150878
150879
150880
150881
150882
150883
150884
150885
150886
150887
150888
150889
150890
150891
150892
150893
150894
150895
150896
150897namespace duckdb {
150898class BaseStatistics;
150899class Expression;
150900class PhysicalOperator;
150901class PhysicalTableScan;
150902
150903enum class TableFilterType :
uint8_t {
150904 CONSTANT_COMPARISON = 0,
150905 IS_NULL = 1,
150906 IS_NOT_NULL = 2,
150907 CONJUNCTION_OR = 3,
150908 CONJUNCTION_AND = 4,
150909 STRUCT_EXTRACT = 5,
150910 OPTIONAL_FILTER = 6,
150911 IN_FILTER = 7,
150912 DYNAMIC_FILTER = 8,
150913 EXPRESSION_FILTER = 9,
150914 BLOOM_FILTER = 10,
150915};
150916
150918class TableFilter {
150919public:
150920 explicit TableFilter(TableFilterType filter_type_p) : filter_type(filter_type_p) {
150921 }
150922 virtual ~TableFilter() {
150923 }
150924
150925 TableFilterType filter_type;
150926
150927public:
150929 virtual FilterPropagateResult CheckStatistics(BaseStatistics &stats) const = 0;
150930 virtual string ToString(const string &column_name) const = 0;
150931 string DebugToString() const;
150932 virtual unique_ptr<TableFilter> Copy() const = 0;
150933 virtual bool Equals(const TableFilter &other) const {
150934 return filter_type == other.filter_type;
150935 }
150936 virtual unique_ptr<Expression> ToExpression(const Expression &column) const = 0;
150937
150938 virtual void Serialize(Serializer &serializer) const;
150939 static unique_ptr<TableFilter> Deserialize(Deserializer &deserializer);
150940
150941public:
150942 template <class TARGET>
150943 TARGET &Cast() {
150944 if (filter_type != TARGET::TYPE) {
150945 throw InternalException("Failed to cast to type - table filter type mismatch");
150946 }
150947 return reinterpret_cast<TARGET &>(*this);
150948 }
150949
150950 template <class TARGET>
150951 const TARGET &Cast() const {
150952 if (filter_type != TARGET::TYPE) {
150953 throw InternalException("Failed to cast to type - table filter type mismatch");
150954 }
150955 return reinterpret_cast<const TARGET &>(*this);
150956 }
150957};
150958
150961class TableFilterSet {
150962public:
150963 map<idx_t, unique_ptr<TableFilter>> filters;
150964
150965public:
150966 void PushFilter(const ColumnIndex &col_idx, unique_ptr<TableFilter> filter);
150967
150968 bool Equals(TableFilterSet &other) {
150969 if (filters.size() != other.filters.size()) {
150970 return false;
150971 }
150972 for (auto &entry : filters) {
150973 auto other_entry = other.filters.find(entry.first);
150974 if (other_entry == other.filters.end()) {
150975 return false;
150976 }
150977 if (!entry.second->Equals(*other_entry->second)) {
150978 return false;
150979 }
150980 }
150981 return true;
150982 }
150983 static bool Equals(TableFilterSet *left, TableFilterSet *right) {
150984 if (left == right) {
150985 return true;
150986 }
150987 if (!left || !right) {
150988 return false;
150989 }
150990 return left->Equals(*right);
150991 }
150992
150993 unique_ptr<TableFilterSet> Copy() const {
150994 auto copy = make_uniq<TableFilterSet>();
150995 for (auto &it : filters) {
150996 copy->filters.emplace(it.first, it.second->Copy());
150997 }
150998 return copy;
150999 }
151000
151001 void Serialize(Serializer &serializer) const;
151002 static TableFilterSet Deserialize(Deserializer &deserializer);
151003};
151004
151005class DynamicTableFilterSet {
151006public:
151007 void ClearFilters(const PhysicalOperator &op);
151008 void PushFilter(const PhysicalOperator &op, idx_t column_index, unique_ptr<TableFilter> filter);
151009
151010 bool HasFilters() const;
151011 unique_ptr<TableFilterSet> GetFinalTableFilters(const PhysicalTableScan &scan,
151012 optional_ptr<TableFilterSet> existing_filters) const;
151013
151014private:
151015 mutable mutex lock;
151016 reference_map_t<const PhysicalOperator, unique_ptr<TableFilterSet>> filters;
151017};
151018
151019}
151020
151021
151022
151023namespace duckdb {
151024
151025class ConjunctionFilter : public TableFilter {
151026public:
151027 explicit ConjunctionFilter(TableFilterType filter_type_p) : TableFilter(filter_type_p) {
151028 }
151029
151030 ~ConjunctionFilter() override {
151031 }
151032
151034 vector<unique_ptr<TableFilter>> child_filters;
151035
151036public:
151037 bool Equals(const TableFilter &other) const override {
151038 return TableFilter::Equals(other);
151039 }
151040};
151041
151042class ConjunctionOrFilter : public ConjunctionFilter {
151043public:
151044 static constexpr const TableFilterType
TYPE = TableFilterType::CONJUNCTION_OR;
151045
151046public:
151047 ConjunctionOrFilter();
151048 FilterPropagateResult CheckStatistics(BaseStatistics &stats) const override;
151049 string ToString(const string &column_name) const override;
151050 bool Equals(const TableFilter &other) const override;
151051 unique_ptr<TableFilter> Copy() const override;
151052 unique_ptr<Expression> ToExpression(const Expression &column) const override;
151053 void Serialize(Serializer &serializer) const override;
151054 static unique_ptr<TableFilter> Deserialize(Deserializer &deserializer);
151055};
151056
151057class ConjunctionAndFilter : public ConjunctionFilter {
151058public:
151059 static constexpr const TableFilterType
TYPE = TableFilterType::CONJUNCTION_AND;
151060
151061public:
151062 ConjunctionAndFilter();
151063
151064public:
151065 FilterPropagateResult CheckStatistics(BaseStatistics &stats) const override;
151066 string ToString(const string &column_name) const override;
151067 bool Equals(const TableFilter &other) const override;
151068 unique_ptr<TableFilter> Copy() const override;
151069 unique_ptr<Expression> ToExpression(const Expression &column) const override;
151070 void Serialize(Serializer &serializer) const override;
151071 static unique_ptr<TableFilter> Deserialize(Deserializer &deserializer);
151072};
151073
151074}
151075
151076
151077
151078
151079
151080
151081
151082
151083
151084
151085
151086
151087
151088
151089
151090
151091
151092
151093
151094
151095
151096
151097
151098
151099
151100namespace duckdb {
151101
151102
151103
151104
151105enum class LogicalOperatorType :
uint8_t {
151106 LOGICAL_INVALID = 0,
151107 LOGICAL_PROJECTION = 1,
151108 LOGICAL_FILTER = 2,
151109 LOGICAL_AGGREGATE_AND_GROUP_BY = 3,
151110 LOGICAL_WINDOW = 4,
151111 LOGICAL_UNNEST = 5,
151112 LOGICAL_LIMIT = 6,
151113 LOGICAL_ORDER_BY = 7,
151114 LOGICAL_TOP_N = 8,
151115 LOGICAL_COPY_TO_FILE = 10,
151116 LOGICAL_DISTINCT = 11,
151117 LOGICAL_SAMPLE = 12,
151118 LOGICAL_PIVOT = 14,
151119 LOGICAL_COPY_DATABASE = 15,
151120
151121
151122
151123
151124 LOGICAL_GET = 25,
151125 LOGICAL_CHUNK_GET = 26,
151126 LOGICAL_DELIM_GET = 27,
151127 LOGICAL_EXPRESSION_GET = 28,
151128 LOGICAL_DUMMY_SCAN = 29,
151129 LOGICAL_EMPTY_RESULT = 30,
151130 LOGICAL_CTE_REF = 31,
151131
151132
151133
151134 LOGICAL_JOIN = 50,
151135 LOGICAL_DELIM_JOIN = 51,
151136 LOGICAL_COMPARISON_JOIN = 52,
151137 LOGICAL_ANY_JOIN = 53,
151138 LOGICAL_CROSS_PRODUCT = 54,
151139 LOGICAL_POSITIONAL_JOIN = 55,
151140 LOGICAL_ASOF_JOIN = 56,
151141 LOGICAL_DEPENDENT_JOIN = 57,
151142
151143
151144
151145 LOGICAL_UNION = 75,
151146 LOGICAL_EXCEPT = 76,
151147 LOGICAL_INTERSECT = 77,
151148 LOGICAL_RECURSIVE_CTE = 78,
151149 LOGICAL_MATERIALIZED_CTE = 79,
151150
151151
151152
151153
151154 LOGICAL_INSERT = 100,
151155 LOGICAL_DELETE = 101,
151156 LOGICAL_UPDATE = 102,
151157 LOGICAL_MERGE_INTO = 103,
151158
151159
151160
151161
151162 LOGICAL_ALTER = 125,
151163 LOGICAL_CREATE_TABLE = 126,
151164 LOGICAL_CREATE_INDEX = 127,
151165 LOGICAL_CREATE_SEQUENCE = 128,
151166 LOGICAL_CREATE_VIEW = 129,
151167 LOGICAL_CREATE_SCHEMA = 130,
151168 LOGICAL_CREATE_MACRO = 131,
151169 LOGICAL_DROP = 132,
151170 LOGICAL_PRAGMA = 133,
151171 LOGICAL_TRANSACTION = 134,
151172 LOGICAL_CREATE_TYPE = 135,
151173 LOGICAL_ATTACH = 136,
151174 LOGICAL_DETACH = 137,
151175
151176
151177
151178
151179 LOGICAL_EXPLAIN = 150,
151180
151181
151182
151183
151184 LOGICAL_PREPARE = 175,
151185 LOGICAL_EXECUTE = 176,
151186 LOGICAL_EXPORT = 177,
151187 LOGICAL_VACUUM = 178,
151188 LOGICAL_SET = 179,
151189 LOGICAL_LOAD = 180,
151190 LOGICAL_RESET = 181,
151191 LOGICAL_UPDATE_EXTENSIONS = 182,
151192
151193
151194
151195
151196 LOGICAL_CREATE_SECRET = 190,
151197
151198 LOGICAL_EXTENSION_OPERATOR = 255
151199};
151200
151201DUCKDB_API string LogicalOperatorToString(LogicalOperatorType type);
151202
151203}
151204
151205
151206
151207
151208
151209
151210
151211
151212
151213
151214
151215
151216
151217
151218
151219
151220
151221
151222
151223
151224
151225
151226
151227
151228
151229namespace duckdb {
151230
151231
151232
151233
151234class BoundQueryNode;
151235class BoundSelectNode;
151236class BoundSetOperationNode;
151237
151238
151239
151240
151241class Expression;
151242
151243class BoundAggregateExpression;
151244class BoundBetweenExpression;
151245class BoundCaseExpression;
151246class BoundCastExpression;
151247class BoundColumnRefExpression;
151248class BoundComparisonExpression;
151249class BoundConjunctionExpression;
151250class BoundConstantExpression;
151251class BoundDefaultExpression;
151252class BoundFunctionExpression;
151253class BoundLambdaRefExpression;
151254class BoundOperatorExpression;
151255class BoundParameterExpression;
151256class BoundReferenceExpression;
151257class BoundSubqueryExpression;
151258class BoundUnnestExpression;
151259class BoundWindowExpression;
151260
151261
151262
151263
151264class BoundJoinRef;
151265class BoundMergeIntoAction;
151266
151267}
151268
151269
151270
151271
151272
151273
151274
151275
151276
151277
151278
151279namespace duckdb {
151280
151281class LogicalOperator;
151282
151283class LogicalAggregate;
151284class LogicalAnyJoin;
151285class LogicalColumnDataGet;
151286class LogicalComparisonJoin;
151287class LogicalCopyDatabase;
151288class LogicalCopyToFile;
151289class LogicalCreate;
151290class LogicalCreateTable;
151291class LogicalCreateIndex;
151292class LogicalCreateTable;
151293class LogicalCreateSecret;
151294class LogicalCrossProduct;
151295class LogicalCTERef;
151296class LogicalDelete;
151297class LogicalDelimGet;
151298class LogicalDistinct;
151299class LogicalDummyScan;
151300class LogicalEmptyResult;
151301class LogicalExecute;
151302class LogicalExplain;
151303class LogicalExport;
151304class LogicalExpressionGet;
151305class LogicalFilter;
151306class LogicalGet;
151307class LogicalInsert;
151308class LogicalJoin;
151309class LogicalLimit;
151310class LogicalMergeInto;
151311class LogicalOrder;
151312class LogicalPivot;
151313class LogicalPositionalJoin;
151314class LogicalPragma;
151315class LogicalPrepare;
151316class LogicalProjection;
151317class LogicalRecursiveCTE;
151318class LogicalMaterializedCTE;
151319class LogicalSetOperation;
151320class LogicalSample;
151321class LogicalSimple;
151322class LogicalVacuum;
151323class LogicalSet;
151324class LogicalReset;
151325class LogicalTopN;
151326class LogicalUnnest;
151327class LogicalUpdate;
151328class LogicalWindow;
151329
151330}
151331
151332
151333#include <functional>
151334
151335namespace duckdb {
151338class LogicalOperatorVisitor {
151339public:
151340 virtual ~LogicalOperatorVisitor() {
151341 }
151342
151343 virtual void VisitOperator(LogicalOperator &op);
151344 virtual void VisitExpression(unique_ptr<Expression> *expression);
151345
151346 static void EnumerateExpressions(LogicalOperator &op,
151347 const std::function<void(unique_ptr<Expression> *child)> &callback);
151348
151349protected:
151352 void VisitOperatorChildren(LogicalOperator &op);
151355 void VisitOperatorExpressions(LogicalOperator &op);
151357 void VisitOperatorWithProjectionMapChildren(LogicalOperator &op);
151358 void VisitChildOfOperatorWithProjectionMap(LogicalOperator &child, vector<idx_t> &projection_map);
151359
151360
151361
151362 virtual void VisitExpressionChildren(Expression &expression);
151363
151364 virtual unique_ptr<Expression> VisitReplace(BoundAggregateExpression &expr, unique_ptr<Expression> *expr_ptr);
151365 virtual unique_ptr<Expression> VisitReplace(BoundBetweenExpression &expr, unique_ptr<Expression> *expr_ptr);
151366 virtual unique_ptr<Expression> VisitReplace(BoundCaseExpression &expr, unique_ptr<Expression> *expr_ptr);
151367 virtual unique_ptr<Expression> VisitReplace(BoundCastExpression &expr, unique_ptr<Expression> *expr_ptr);
151368 virtual unique_ptr<Expression> VisitReplace(BoundColumnRefExpression &expr, unique_ptr<Expression> *expr_ptr);
151369 virtual unique_ptr<Expression> VisitReplace(BoundComparisonExpression &expr, unique_ptr<Expression> *expr_ptr);
151370 virtual unique_ptr<Expression> VisitReplace(BoundConjunctionExpression &expr, unique_ptr<Expression> *expr_ptr);
151371 virtual unique_ptr<Expression> VisitReplace(BoundConstantExpression &expr, unique_ptr<Expression> *expr_ptr);
151372 virtual unique_ptr<Expression> VisitReplace(BoundDefaultExpression &expr, unique_ptr<Expression> *expr_ptr);
151373 virtual unique_ptr<Expression> VisitReplace(BoundFunctionExpression &expr, unique_ptr<Expression> *expr_ptr);
151374 virtual unique_ptr<Expression> VisitReplace(BoundOperatorExpression &expr, unique_ptr<Expression> *expr_ptr);
151375 virtual unique_ptr<Expression> VisitReplace(BoundReferenceExpression &expr, unique_ptr<Expression> *expr_ptr);
151376 virtual unique_ptr<Expression> VisitReplace(BoundSubqueryExpression &expr, unique_ptr<Expression> *expr_ptr);
151377 virtual unique_ptr<Expression> VisitReplace(BoundParameterExpression &expr, unique_ptr<Expression> *expr_ptr);
151378 virtual unique_ptr<Expression> VisitReplace(BoundWindowExpression &expr, unique_ptr<Expression> *expr_ptr);
151379 virtual unique_ptr<Expression> VisitReplace(BoundUnnestExpression &expr, unique_ptr<Expression> *expr_ptr);
151380};
151381}
151382
151383
151384
151385
151386#include <algorithm>
151387#include <functional>
151388
151389namespace duckdb {
151390
151393class LogicalOperator {
151394public:
151395 explicit LogicalOperator(LogicalOperatorType type);
151396 LogicalOperator(LogicalOperatorType type, vector<unique_ptr<Expression>> expressions);
151397 virtual ~LogicalOperator();
151398
151400 LogicalOperatorType type;
151402 vector<unique_ptr<LogicalOperator>> children;
151404 vector<unique_ptr<Expression>> expressions;
151406 vector<LogicalType> types;
151408 idx_t estimated_cardinality;
151409 bool has_estimated_cardinality;
151410
151411public:
151412 virtual vector<ColumnBinding> GetColumnBindings();
151413 virtual idx_t GetRootIndex();
151414 static string ColumnBindingsToString(const vector<ColumnBinding> &bindings);
151415 void PrintColumnBindings();
151416 static vector<ColumnBinding> GenerateColumnBindings(idx_t table_idx, idx_t column_count);
151417 static vector<LogicalType> MapTypes(const vector<LogicalType> &types, const vector<idx_t> &projection_map);
151418 static vector<ColumnBinding> MapBindings(const vector<ColumnBinding> &types, const vector<idx_t> &projection_map);
151419
151421 void ResolveOperatorTypes();
151422
151423 virtual string GetName() const;
151424 virtual InsertionOrderPreservingMap<string> ParamsToString() const;
151425 virtual string ToString(ExplainFormat
format = ExplainFormat::DEFAULT)
const;
151426 DUCKDB_API void Print();
151428 virtual void Verify(ClientContext &context);
151429
151430 void AddChild(unique_ptr<LogicalOperator> child);
151431 virtual idx_t EstimateCardinality(ClientContext &context);
151432 void SetEstimatedCardinality(idx_t _estimated_cardinality);
151433 void SetParamsEstimatedCardinality(InsertionOrderPreservingMap<string> &result) const;
151434
151435 virtual void Serialize(Serializer &serializer) const;
151436 static unique_ptr<LogicalOperator> Deserialize(Deserializer &deserializer);
151437
151438 virtual unique_ptr<LogicalOperator> Copy(ClientContext &context) const;
151439
151440 virtual bool RequireOptimizer() const {
151441 return true;
151442 }
151443
151445 virtual bool SupportSerialization() const {
151446 return true;
151447 };
151448
151449 virtual bool HasProjectionMap() const {
151450 return false;
151451 }
151452
151454 virtual vector<idx_t> GetTableIndex() const;
151455
151456protected:
151458 virtual void ResolveTypes() = 0;
151459
151460public:
151461 template <class TARGET>
151462 TARGET &Cast() {
151463 if (TARGET::TYPE != LogicalOperatorType::LOGICAL_INVALID && type != TARGET::TYPE) {
151464 throw InternalException("Failed to cast logical operator to type - logical operator type mismatch");
151465 }
151466 return reinterpret_cast<TARGET &>(*this);
151467 }
151468
151469 template <class TARGET>
151470 const TARGET &Cast() const {
151471 if (TARGET::TYPE != LogicalOperatorType::LOGICAL_INVALID && type != TARGET::TYPE) {
151472 throw InternalException("Failed to cast logical operator to type - logical operator type mismatch");
151473 }
151474 return reinterpret_cast<const TARGET &>(*this);
151475 }
151476};
151477}
151478
151479
151480namespace duckdb {
151481
151482class CardinalityEstimator;
151483
151484struct DistinctCount {
151485 idx_t distinct_count;
151486 bool from_hll;
151487};
151488
151489struct ExpressionBinding {
151490public:
151491 bool FoundExpression() const {
151492 return expression;
151493 }
151494 bool FoundColumnRef() const {
151495 if (!FoundExpression()) {
151496 return false;
151497 }
151498 return expression->type == ExpressionType::BOUND_COLUMN_REF;
151499 }
151500
151501public:
151502 optional_ptr<Expression> expression;
151503 ColumnBinding child_binding;
151504 bool expression_is_constant = false;
151505};
151506
151507struct RelationStats {
151508
151509 vector<DistinctCount> column_distinct_count;
151510 idx_t cardinality;
151511 double filter_strength = 1;
151512 bool stats_initialized = false;
151513
151514
151515 vector<string> column_names;
151516 string table_name;
151517
151518 RelationStats() : cardinality(1), filter_strength(1), stats_initialized(false) {
151519 }
151520};
151521
151522class RelationStatisticsHelper {
151523public:
151524 static constexpr double DEFAULT_SELECTIVITY = 0.2;
151525
151526public:
151527 static idx_t InspectTableFilter(idx_t cardinality, idx_t column_index,
const TableFilter &filter,
151528 BaseStatistics &base_stats);
151529
151530
151532 static RelationStats ExtractGetStats(LogicalGet &
get, ClientContext &context);
151533 static RelationStats ExtractDelimGetStats(LogicalDelimGet &delim_get, ClientContext &context);
151536 static RelationStats ExtractDummyScanStats(LogicalDummyScan &dummy_scan, ClientContext &context);
151537 static RelationStats ExtractExpressionGetStats(LogicalExpressionGet &expression_get, ClientContext &context);
151539 static RelationStats ExtractProjectionStats(LogicalProjection &proj, RelationStats &child_stats);
151540 static RelationStats ExtractAggregationStats(LogicalAggregate &aggr, RelationStats &child_stats);
151541 static RelationStats ExtractWindowStats(LogicalWindow &window, RelationStats &child_stats);
151542 static RelationStats ExtractEmptyResultStats(LogicalEmptyResult &empty);
151544 static RelationStats CombineStatsOfReorderableOperator(vector<ColumnBinding> &bindings,
151545 vector<RelationStats> relation_stats);
151547 static RelationStats CombineStatsOfNonReorderableOperator(LogicalOperator &op,
151548 const vector<RelationStats> &child_stats);
151549 static void CopyRelationStats(RelationStats &to, const RelationStats &from);
151550
151551private:
151552 static idx_t GetDistinctCount(LogicalGet &
get, ClientContext &context,
const ColumnIndex &column_id);
151553};
151554
151555}
151556
151557
151558namespace duckdb {
151559
151560class FilterInfo;
151561
151562struct DenomInfo {
151563 DenomInfo(JoinRelationSet &numerator_relations, double filter_strength, double denominator)
151564 : numerator_relations(numerator_relations), filter_strength(filter_strength), denominator(denominator) {
151565 }
151566
151567 JoinRelationSet &numerator_relations;
151568 double filter_strength;
151569 double denominator;
151570};
151571
151572struct RelationsSetToStats {
151575 column_binding_set_t equivalent_relations;
151577 idx_t distinct_count_hll;
151579 idx_t distinct_count_no_hll;
151580 bool has_distinct_count_hll;
151581 vector<optional_ptr<FilterInfo>> filters;
151582 vector<string> column_names;
151583
151584 explicit RelationsSetToStats(const column_binding_set_t &column_binding_set)
151585 : equivalent_relations(column_binding_set), distinct_count_hll(0),
151586 distinct_count_no_hll(NumericLimits<
idx_t>::Maximum()), has_distinct_count_hll(false) {};
151587};
151588
151589
151590class FilterInfoWithTotalDomains {
151591public:
151592 FilterInfoWithTotalDomains(optional_ptr<FilterInfo> filter_info, RelationsSetToStats &relation_set_to_stats)
151593 : filter_info(filter_info), distinct_count_hll(relation_set_to_stats.distinct_count_hll),
151594 distinct_count_no_hll(relation_set_to_stats.distinct_count_no_hll),
151595 has_distinct_count_hll(relation_set_to_stats.has_distinct_count_hll) {
151596 }
151597
151598 optional_ptr<FilterInfo> filter_info;
151600 idx_t distinct_count_hll;
151602 idx_t distinct_count_no_hll;
151603 bool has_distinct_count_hll;
151604};
151605
151606struct Subgraph2Denominator {
151607 optional_ptr<JoinRelationSet> relations;
151608 optional_ptr<JoinRelationSet> numerator_relations;
151609 double denom;
151610
151611 Subgraph2Denominator() : relations(nullptr), numerator_relations(nullptr), denom(1) {};
151612};
151613
151614class CardinalityHelper {
151615public:
151616 CardinalityHelper() {
151617 }
151618 explicit CardinalityHelper(double cardinality_before_filters)
151619 : cardinality_before_filters(cardinality_before_filters) {};
151620
151621public:
151622
151623
151624
151625
151626
151627 double cardinality_before_filters;
151628
151629 vector<string> table_names_joined;
151630 vector<string> column_names;
151631};
151632
151633class CardinalityEstimator {
151634public:
151635 static constexpr double DEFAULT_SEMI_ANTI_SELECTIVITY = 5;
151636 explicit CardinalityEstimator() {};
151637
151638private:
151639 vector<RelationsSetToStats> relation_set_stats;
151640 unordered_map<string, CardinalityHelper> relation_set_2_cardinality;
151641 JoinRelationSetManager set_manager;
151642 vector<RelationStats> relation_stats;
151643
151644public:
151645 void RemoveEmptyTotalDomains();
151646 void UpdateTotalDomains(optional_ptr<JoinRelationSet> set, RelationStats &stats);
151647 void InitEquivalentRelations(const vector<unique_ptr<FilterInfo>> &filter_infos);
151648
151649 void InitCardinalityEstimatorProps(optional_ptr<JoinRelationSet> set, RelationStats &stats);
151650
151653 template <class T>
151654 T EstimateCardinalityWithSet(JoinRelationSet &new_set);
151655
151657 void AddRelationNamesToRelationStats(vector<RelationStats> &stats);
151658 void PrintRelationStats();
151659
151660private:
151661 double GetNumerator(JoinRelationSet &set);
151662 DenomInfo GetDenominator(JoinRelationSet &set);
151663
151664 bool SingleColumnFilter(FilterInfo &filter_info);
151665 vector<idx_t> DetermineMatchingEquivalentSets(optional_ptr<FilterInfo> filter_info);
151669 void AddToEquivalenceSets(optional_ptr<FilterInfo> filter_info, vector<idx_t> matching_equivalent_sets);
151670
151671 double CalculateUpdatedDenom(Subgraph2Denominator left, Subgraph2Denominator right,
151672 FilterInfoWithTotalDomains &filter);
151673 JoinRelationSet &UpdateNumeratorRelations(Subgraph2Denominator left, Subgraph2Denominator right,
151674 FilterInfoWithTotalDomains &filter);
151675
151676 void AddRelationStats(FilterInfo &filter_info);
151677 bool EmptyFilter(FilterInfo &filter_info);
151678};
151679
151680}
151681
151682
151683
151684
151685
151686
151687
151688
151689
151690
151691
151692
151693
151694
151695
151696
151697
151698
151699
151700namespace duckdb {
151701class Expression;
151702
151703template <class T>
151704struct ExpressionHashFunction {
151706 return (uint64_t)expr.get().Hash();
151707 }
151708};
151709
151710template <class T>
151711struct ExpressionEquality {
151712 bool operator()(
const reference<T> &a,
const reference<T> &b)
const {
151713 return a.get().Equals(b.get());
151714 }
151715};
151716
151717template <typename T>
151718using expression_map_t =
151719 unordered_map<reference<Expression>, T, ExpressionHashFunction<Expression>, ExpressionEquality<Expression>>;
151720
151721using expression_set_t =
151722 unordered_set<reference<Expression>, ExpressionHashFunction<Expression>, ExpressionEquality<Expression>>;
151723
151724template <typename T>
151725using parsed_expression_map_t = unordered_map<reference<ParsedExpression>, T, ExpressionHashFunction<ParsedExpression>,
151726 ExpressionEquality<ParsedExpression>>;
151727
151728using parsed_expression_set_t = unordered_set<reference<ParsedExpression>, ExpressionHashFunction<ParsedExpression>,
151729 ExpressionEquality<ParsedExpression>>;
151730
151731}
151732
151733
151734
151735
151736namespace duckdb {
151737
151738class JoinOrderOptimizer;
151739class FilterInfo;
151740
151742struct SingleJoinRelation {
151743 LogicalOperator &op;
151744 optional_ptr<LogicalOperator> parent;
151745 RelationStats stats;
151746
151747 SingleJoinRelation(LogicalOperator &op, optional_ptr<LogicalOperator> parent) : op(op), parent(parent) {
151748 }
151749 SingleJoinRelation(LogicalOperator &op, optional_ptr<LogicalOperator> parent, RelationStats stats)
151750 : op(op), parent(parent), stats(std::move(stats)) {
151751 }
151752};
151753
151754class RelationManager {
151755public:
151756 explicit RelationManager(ClientContext &context) : context(context) {
151757 }
151758
151759 idx_t NumRelations();
151760
151761 bool ExtractJoinRelations(JoinOrderOptimizer &optimizer, LogicalOperator &input_op,
151762 vector<reference<LogicalOperator>> &filter_operators,
151763 optional_ptr<LogicalOperator> parent = nullptr);
151764
151767 vector<unique_ptr<FilterInfo>> ExtractEdges(LogicalOperator &op,
151768 vector<reference<LogicalOperator>> &filter_operators,
151769 JoinRelationSetManager &set_manager);
151770
151772 bool ExtractBindings(Expression &expression, unordered_set<idx_t> &bindings);
151773 void AddRelation(LogicalOperator &op, optional_ptr<LogicalOperator> parent, const RelationStats &stats);
151775 void AddRelationWithChildren(JoinOrderOptimizer &optimizer, LogicalOperator &op, LogicalOperator &input_op,
151776 optional_ptr<LogicalOperator> parent, RelationStats &child_stats,
151777 optional_ptr<LogicalOperator> limit_op,
151778 vector<reference<LogicalOperator>> &datasource_filters);
151779 void AddAggregateOrWindowRelation(LogicalOperator &op, optional_ptr<LogicalOperator> parent,
151780 const RelationStats &stats, LogicalOperatorType op_type);
151781 vector<unique_ptr<SingleJoinRelation>> GetRelations();
151782
151783 const vector<RelationStats> GetRelationStats();
151785 unordered_map<idx_t, idx_t> relation_mapping;
151786
151787 bool CrossProductWithRelationAllowed(idx_t relation_id);
151788
151789 void PrintRelationStats();
151790
151791private:
151792 ClientContext &context;
151794 vector<unique_ptr<SingleJoinRelation>> relations;
151795 unordered_set<idx_t> no_cross_product_relations;
151796};
151797
151798}
151799
151800
151801
151802
151803
151804
151805
151806#include <functional>
151807
151808namespace duckdb {
151809
151810class FilterInfo;
151811
151812struct NeighborInfo {
151813 explicit NeighborInfo(optional_ptr<JoinRelationSet> neighbor) : neighbor(neighbor) {
151814 }
151815
151816 optional_ptr<JoinRelationSet> neighbor;
151817 vector<optional_ptr<FilterInfo>> filters;
151818};
151819
151821class QueryGraphEdges {
151822public:
151824 struct QueryEdge {
151825 vector<unique_ptr<NeighborInfo>> neighbors;
151826 unordered_map<idx_t, unique_ptr<QueryEdge>> children;
151827 };
151828
151829public:
151830 string ToString() const;
151831 void Print();
151832
151834 const vector<reference<NeighborInfo>> GetConnections(JoinRelationSet &node, JoinRelationSet &other) const;
151837 const vector<idx_t> GetNeighbors(JoinRelationSet &node, unordered_set<idx_t> &exclusion_set) const;
151838
151840 void EnumerateNeighbors(JoinRelationSet &node, const std::function<bool(NeighborInfo &)> &callback) const;
151842 void CreateEdge(JoinRelationSet &left, JoinRelationSet &right, optional_ptr<FilterInfo> info);
151843
151844private:
151846 optional_ptr<QueryEdge> GetQueryEdge(JoinRelationSet &left);
151847
151848 void EnumerateNeighborsDFS(JoinRelationSet &node, reference<QueryEdge> info, idx_t index,
151849 const std::function<bool(NeighborInfo &)> &callback) const;
151850
151851 QueryEdge root;
151852};
151853
151854}
151855
151856
151857namespace duckdb {
151858
151859struct NeighborInfo;
151860
151861class DPJoinNode {
151862public:
151864 JoinRelationSet &set;
151866 optional_ptr<NeighborInfo> info;
151867 bool is_leaf;
151869 JoinRelationSet &left_set;
151870 JoinRelationSet &right_set;
151871
151876 double cost;
151878 idx_t cardinality;
151879
151881 DPJoinNode(JoinRelationSet &set, optional_ptr<NeighborInfo> info, JoinRelationSet &left, JoinRelationSet &right,
151882 double cost);
151883
151887 explicit DPJoinNode(JoinRelationSet &set);
151888};
151889
151890}
151891
151892
151893
151894
151895
151896
151897
151898
151899
151900
151901
151902
151903
151904
151905
151906
151907
151908
151909
151910
151911
151912
151913
151914
151915
151916
151917
151918
151919namespace duckdb {
151920class ClientContext;
151921class Executor;
151922class Task;
151923class DatabaseInstance;
151924struct ProducerToken;
151925
151926enum class TaskExecutionMode :
uint8_t { PROCESS_ALL, PROCESS_PARTIAL };
151927
151928enum class TaskExecutionResult :
uint8_t { TASK_FINISHED, TASK_NOT_FINISHED, TASK_ERROR, TASK_BLOCKED };
151929
151931class Task : public enable_shared_from_this<Task> {
151932public:
151933 virtual ~Task() {
151934 }
151935
151936public:
151942 virtual TaskExecutionResult Execute(TaskExecutionMode mode) = 0;
151943
151947 virtual void Deschedule() {
151948 throw InternalException("Cannot deschedule task of base Task class");
151949 };
151950
151952 virtual void Reschedule() {
151953 throw InternalException("Cannot reschedule task of base Task class");
151954 }
151955
151956 virtual bool TaskBlockedOnResult() const {
151957 return false;
151958 }
151959
151960 virtual string TaskType() const {
151961 return "UnnamedTask";
151962 }
151963
151964public:
151965 optional_ptr<ProducerToken> token;
151966};
151967
151968}
151969
151970
151971#include <condition_variable>
151972
151973namespace duckdb {
151974
151983
151985struct InterruptDoneSignalState {
151987 void Signal();
151989 void Await();
151990
151991protected:
151992 mutex lock;
151993 std::condition_variable cv;
151994 bool done = false;
151995};
151996
151998class InterruptState {
151999public:
152001 InterruptState();
152003 explicit InterruptState(weak_ptr<Task> task);
152005 explicit InterruptState(weak_ptr<InterruptDoneSignalState> done_signal);
152006
152008 DUCKDB_API void Callback() const;
152009
152010protected:
152014 weak_ptr<Task> current_task;
152016 weak_ptr<InterruptDoneSignalState> signal_state;
152017};
152018
152019class StateWithBlockableTasks {
152020public:
152021 unique_lock<mutex> Lock() {
152022 return unique_lock<mutex>(lock);
152023 }
152024
152025 void PreventBlocking(const unique_lock<mutex> &guard) {
152026 VerifyLock(guard);
152027 can_block = false;
152028 }
152029
152031 bool BlockTask(const unique_lock<mutex> &guard, const InterruptState &interrupt_state) {
152032 VerifyLock(guard);
152033 if (can_block) {
152034 blocked_tasks.push_back(interrupt_state);
152035 return true;
152036 }
152037 return false;
152038 }
152039
152040 bool CanBlock(const unique_lock<mutex> &guard) const {
152041 VerifyLock(guard);
152042 return can_block;
152043 }
152044
152046 bool UnblockTasks(const unique_lock<mutex> &guard) {
152047 VerifyLock(guard);
152048 if (blocked_tasks.empty()) {
152049 return false;
152050 }
152051 for (auto &entry : blocked_tasks) {
152052 entry.Callback();
152053 }
152054 blocked_tasks.clear();
152055 return true;
152056 }
152057
152058 SinkResultType BlockSink(
const unique_lock<mutex> &guard,
const InterruptState &interrupt_state) {
152059 return BlockTask(guard, interrupt_state) ? SinkResultType::BLOCKED : SinkResultType::FINISHED;
152060 }
152061
152062 SourceResultType BlockSource(
const unique_lock<mutex> &guard,
const InterruptState &interrupt_state) {
152063 return BlockTask(guard, interrupt_state) ? SourceResultType::BLOCKED : SourceResultType::FINISHED;
152064 }
152065
152066 void VerifyLock(const unique_lock<mutex> &guard) const {
152067#ifdef DEBUG
152069#endif
152070 }
152071
152072private:
152074 atomic<bool> can_block {true};
152076 mutable mutex lock;
152078 mutable vector<InterruptState> blocked_tasks;
152079};
152080
152081}
152082
152083
152084
152085namespace duckdb {
152087class Executor;
152088class PhysicalOperator;
152089class Pipeline;
152090class PipelineBuildState;
152091class MetaPipeline;
152092class InterruptState;
152093
152094
152095class OperatorState {
152096public:
152097 virtual ~OperatorState() {
152098 }
152099
152100 virtual void Finalize(const PhysicalOperator &op, ExecutionContext &context) {
152101 }
152102
152103 template <class TARGET>
152104 TARGET &Cast() {
152105 DynamicCastCheck<TARGET>(this);
152106 return reinterpret_cast<TARGET &>(*this);
152107 }
152108 template <class TARGET>
152109 const TARGET &Cast() const {
152110 DynamicCastCheck<TARGET>(this);
152111 return reinterpret_cast<const TARGET &>(*this);
152112 }
152113};
152114
152115class GlobalOperatorState {
152116public:
152117 virtual ~GlobalOperatorState() {
152118 }
152119
152120 template <class TARGET>
152121 TARGET &Cast() {
152122 DynamicCastCheck<TARGET>(this);
152123 return reinterpret_cast<TARGET &>(*this);
152124 }
152125 template <class TARGET>
152126 const TARGET &Cast() const {
152127 DynamicCastCheck<TARGET>(this);
152128 return reinterpret_cast<const TARGET &>(*this);
152129 }
152130
152131 virtual idx_t MaxThreads(idx_t source_max_threads) {
152132 return source_max_threads;
152133 }
152134};
152135
152136class GlobalSinkState : public StateWithBlockableTasks {
152137public:
152139 }
152140 virtual ~GlobalSinkState() {
152141 }
152142
152144
152145 template <class TARGET>
152146 TARGET &Cast() {
152147 DynamicCastCheck<TARGET>(this);
152148 return reinterpret_cast<TARGET &>(*this);
152149 }
152150 template <class TARGET>
152151 const TARGET &Cast() const {
152152 DynamicCastCheck<TARGET>(this);
152153 return reinterpret_cast<const TARGET &>(*this);
152154 }
152155
152156 virtual idx_t MaxThreads(idx_t source_max_threads) {
152157 return source_max_threads;
152158 }
152159};
152160
152161class LocalSinkState {
152162public:
152163 virtual ~LocalSinkState() {
152164 }
152165
152167 SourcePartitionInfo partition_info;
152168
152169 template <class TARGET>
152170 TARGET &Cast() {
152171 DynamicCastCheck<TARGET>(this);
152172 return reinterpret_cast<TARGET &>(*this);
152173 }
152174 template <class TARGET>
152175 const TARGET &Cast() const {
152176 DynamicCastCheck<TARGET>(this);
152177 return reinterpret_cast<const TARGET &>(*this);
152178 }
152179};
152180
152181class GlobalSourceState : public StateWithBlockableTasks {
152182public:
152183 virtual ~GlobalSourceState() {
152184 }
152185
152186 virtual idx_t MaxThreads() {
152187 return 1;
152188 }
152189
152190 template <class TARGET>
152191 TARGET &Cast() {
152192 DynamicCastCheck<TARGET>(this);
152193 return reinterpret_cast<TARGET &>(*this);
152194 }
152195 template <class TARGET>
152196 const TARGET &Cast() const {
152197 DynamicCastCheck<TARGET>(this);
152198 return reinterpret_cast<const TARGET &>(*this);
152199 }
152200};
152201
152202class LocalSourceState {
152203public:
152204 virtual ~LocalSourceState() {
152205 }
152206
152207 template <class TARGET>
152208 TARGET &Cast() {
152209 DynamicCastCheck<TARGET>(this);
152210 return reinterpret_cast<TARGET &>(*this);
152211 }
152212 template <class TARGET>
152213 const TARGET &Cast() const {
152214 DynamicCastCheck<TARGET>(this);
152215 return reinterpret_cast<const TARGET &>(*this);
152216 }
152217};
152218
152219struct OperatorSinkInput {
152220 GlobalSinkState &global_state;
152221 LocalSinkState &local_state;
152222 InterruptState &interrupt_state;
152223};
152224
152225struct OperatorSourceInput {
152226 GlobalSourceState &global_state;
152227 LocalSourceState &local_state;
152228 InterruptState &interrupt_state;
152229};
152230
152231struct OperatorSinkCombineInput {
152232 GlobalSinkState &global_state;
152233 LocalSinkState &local_state;
152234 InterruptState &interrupt_state;
152235};
152236
152237struct OperatorSinkFinalizeInput {
152238 GlobalSinkState &global_state;
152239 InterruptState &interrupt_state;
152240};
152241
152242struct OperatorFinalizeInput {
152243 GlobalOperatorState &global_state;
152244 InterruptState &interrupt_state;
152245};
152246
152247struct OperatorSinkNextBatchInput {
152248 GlobalSinkState &global_state;
152249 LocalSinkState &local_state;
152250 InterruptState &interrupt_state;
152251};
152252
152253
152254
152255}
152256
152257
152258
152259
152260namespace duckdb {
152261
152263class Executor;
152264class PhysicalOperator;
152265class Pipeline;
152266class PipelineBuildState;
152267class MetaPipeline;
152268class PhysicalPlan;
152269
152270enum class OperatorCachingMode :
uint8_t { NONE, PARTITIONED, ORDERED, UNORDERED };
152271
152273class PhysicalOperator {
152274public:
152275 static constexpr const PhysicalOperatorType
TYPE = PhysicalOperatorType::INVALID;
152276
152277public:
152278 PhysicalOperator(PhysicalPlan &physical_plan, PhysicalOperatorType type, vector<LogicalType> types,
152279 idx_t estimated_cardinality);
152280 virtual ~PhysicalOperator() {
152281 }
152282
152284 PhysicalOperator(const PhysicalOperator &other) = delete;
152285 PhysicalOperator &
operator=(
const PhysicalOperator &) =
delete;
152286
152288 ArenaLinkedList<reference<PhysicalOperator>> children;
152290 PhysicalOperatorType type;
152292 vector<LogicalType> types;
152294 idx_t estimated_cardinality;
152295
152297 unique_ptr<GlobalSinkState> sink_state;
152299 unique_ptr<GlobalOperatorState> op_state;
152301 mutex lock;
152302
152303public:
152304 virtual string GetName() const;
152305 virtual InsertionOrderPreservingMap<string> ParamsToString() const {
152306 return InsertionOrderPreservingMap<string>();
152307 }
152308 static void SetEstimatedCardinality(InsertionOrderPreservingMap<string> &result, idx_t estimated_cardinality);
152309 virtual string ToString(ExplainFormat
format = ExplainFormat::DEFAULT)
const;
152310 void Print() const;
152311 virtual vector<const_reference<PhysicalOperator>> GetChildren() const;
152312
152314 const vector<LogicalType> &GetTypes() const {
152315 return types;
152316 }
152317
152318 virtual bool Equals(const PhysicalOperator &other) const {
152319 return false;
152320 }
152321
152323 idx_t EstimatedThreadCount()
const;
152324 bool CanSaturateThreads(ClientContext &context) const;
152325
152326 virtual void Verify();
152327
152328public:
152329
152330 virtual unique_ptr<OperatorState> GetOperatorState(ExecutionContext &context) const;
152331 virtual unique_ptr<GlobalOperatorState> GetGlobalOperatorState(ClientContext &context) const;
152332 virtual OperatorResultType Execute(ExecutionContext &context, DataChunk &input, DataChunk &chunk,
152333 GlobalOperatorState &gstate, OperatorState &state) const;
152335 GlobalOperatorState &gstate, OperatorState &state) const;
152337 OperatorFinalizeInput &input) const;
152338
152339 virtual bool ParallelOperator() const {
152340 return false;
152341 }
152342
152343 virtual bool RequiresFinalExecute() const {
152344 return false;
152345 }
152346
152347 virtual bool RequiresOperatorFinalize() const {
152348 return false;
152349 }
152350
152352 virtual OrderPreservationType OperatorOrder() const {
152353 return OrderPreservationType::INSERTION_ORDER;
152354 }
152355
152356public:
152357
152358 virtual unique_ptr<LocalSourceState> GetLocalSourceState(ExecutionContext &context,
152359 GlobalSourceState &gstate) const;
152360 virtual unique_ptr<GlobalSourceState> GetGlobalSourceState(ClientContext &context) const;
152361
152362protected:
152363 virtual SourceResultType GetDataInternal(ExecutionContext &context, DataChunk &chunk,
152364 OperatorSourceInput &input) const;
152365
152366public:
152367 SourceResultType GetData(ExecutionContext &context, DataChunk &chunk, OperatorSourceInput &input)
const;
152368
152369 virtual OperatorPartitionData GetPartitionData(ExecutionContext &context, DataChunk &chunk,
152370 GlobalSourceState &gstate, LocalSourceState &lstate,
152371 const OperatorPartitionInfo &partition_info) const;
152372
152373 virtual bool IsSource() const {
152374 return false;
152375 }
152376
152377 virtual bool ParallelSource() const {
152378 return false;
152379 }
152380
152381 virtual bool SupportsPartitioning(const OperatorPartitionInfo &partition_info) const {
152382 if (partition_info.AnyRequired()) {
152383 return false;
152384 }
152385 return true;
152386 }
152387
152389 virtual OrderPreservationType SourceOrder() const {
152390 return OrderPreservationType::INSERTION_ORDER;
152391 }
152392
152394 virtual ProgressData GetProgress(ClientContext &context, GlobalSourceState &gstate) const;
152395
152397 virtual ProgressData GetSinkProgress(ClientContext &context, GlobalSinkState &gstate,
152398 const ProgressData source_progress) const {
152399 return source_progress;
152400 }
152401
152402 virtual InsertionOrderPreservingMap<string> ExtraSourceParams(GlobalSourceState &gstate,
152403 LocalSourceState &lstate) const {
152404 return InsertionOrderPreservingMap<string>();
152405 }
152406
152407public:
152408
152409
152413 virtual SinkResultType Sink(ExecutionContext &context, DataChunk &chunk, OperatorSinkInput &input)
const;
152417 virtual SinkCombineResultType Combine(ExecutionContext &context, OperatorSinkCombineInput &input) const;
152420 virtual void PrepareFinalize(ClientContext &context, GlobalSinkState &sink_state) const;
152424 virtual SinkFinalizeType Finalize(Pipeline &pipeline, Event &event, ClientContext &context,
152425 OperatorSinkFinalizeInput &input) const;
152428 virtual SinkNextBatchType NextBatch(ExecutionContext &context, OperatorSinkNextBatchInput &input)
const;
152429
152430 virtual unique_ptr<LocalSinkState> GetLocalSinkState(ExecutionContext &context) const;
152431 virtual unique_ptr<GlobalSinkState> GetGlobalSinkState(ClientContext &context) const;
152432
152434 static idx_t GetMaxThreadMemory(ClientContext &context);
152435
152437 static OperatorCachingMode SelectOperatorCachingMode(ExecutionContext &context);
152438
152439 virtual bool IsSink() const {
152440 return false;
152441 }
152442
152443 virtual bool ParallelSink() const {
152444 return false;
152445 }
152446
152447 virtual OperatorPartitionInfo RequiredPartitionInfo() const {
152448 return OperatorPartitionInfo::NoPartitionInfo();
152449 }
152450
152453 virtual bool SinkOrderDependent() const {
152454 return false;
152455 }
152456
152457public:
152458
152459 virtual vector<const_reference<PhysicalOperator>> GetSources() const;
152460 bool AllSourcesSupportBatchIndex() const;
152461
152462 virtual void BuildPipelines(Pipeline ¤t, MetaPipeline &meta_pipeline);
152463
152464public:
152465 template <class TARGET>
152466 TARGET &Cast() {
152467 if (TARGET::TYPE != PhysicalOperatorType::INVALID && type != TARGET::TYPE) {
152468 throw InternalException("Failed to cast physical operator to type - physical operator type mismatch");
152469 }
152470 return reinterpret_cast<TARGET &>(*this);
152471 }
152472
152473 template <class TARGET>
152474 const TARGET &Cast() const {
152475 if (TARGET::TYPE != PhysicalOperatorType::INVALID && type != TARGET::TYPE) {
152476 throw InternalException("Failed to cast physical operator to type - physical operator type mismatch");
152477 }
152478 return reinterpret_cast<const TARGET &>(*this);
152479 }
152480};
152481
152483class CachingOperatorState : public OperatorState {
152484public:
152485 ~CachingOperatorState() override {
152486 }
152487
152488 void Finalize(const PhysicalOperator &op, ExecutionContext &context) override {
152489 }
152490
152491 unique_ptr<DataChunk> cached_chunk;
152492 bool initialized = false;
152494 OperatorCachingMode can_cache_chunk = OperatorCachingMode::NONE;
152495 bool must_return_continuation_chunk = false;
152497};
152498
152501class CachingPhysicalOperator : public PhysicalOperator {
152502public:
152503 static constexpr const idx_t CACHE_THRESHOLD = 64;
152504 CachingPhysicalOperator(PhysicalPlan &physical_plan, PhysicalOperatorType type, vector<LogicalType> types,
152505 idx_t estimated_cardinality);
152506
152507 bool caching_supported;
152508
152509public:
152512 OperatorResultType Execute(ExecutionContext &context, DataChunk &input, DataChunk &chunk,
152513 GlobalOperatorState &gstate, OperatorState &state) const final;
152517 OperatorState &state) const final;
152518
152519 bool RequiresFinalExecute() const final {
152520 return caching_supported;
152521 }
152522
152523protected:
152525 virtual OperatorResultType ExecuteInternal(ExecutionContext &context, DataChunk &input, DataChunk &chunk,
152526 GlobalOperatorState &gstate, OperatorState &state) const = 0;
152527
152528private:
152529 bool CanCacheType(const LogicalType &type);
152530};
152531
152532}
152533
152534
152535
152536
152537
152538
152539
152540
152541
152542
152543
152544
152545
152546
152547
152548
152549
152550
152551
152552
152553
152554
152555
152556
152557
152558
152559
152560
152561
152562
152563
152564
152565
152566
152567
152568
152569
152570
152571
152572
152573
152574
152575
152576
152577namespace duckdb {
152578
152581 NOT_PARTITIONED,
152582 SINGLE_VALUE_PARTITIONS,
152583 OVERLAPPING_PARTITIONS,
152584 DISJOINT_PARTITIONS
152585};
152586
152587enum class CountType { COUNT_EXACT, COUNT_APPROXIMATE };
152588
152589struct PartitionRowGroup {
152590 virtual ~PartitionRowGroup() = default;
152591 virtual unique_ptr<BaseStatistics> GetColumnStatistics(const StorageIndex &storage_index) = 0;
152592 virtual bool MinMaxIsExact(const BaseStatistics &stats, const StorageIndex &storage_index) = 0;
152593};
152594
152595struct PartitionStatistics {
152596 PartitionStatistics();
152597
152599 optional_idx row_start;
152603 CountType count_type;
152605 shared_ptr<PartitionRowGroup> partition_row_group;
152606};
152607
152608}
152609
152610
152611
152612
152613
152614
152615
152616
152617
152618
152619
152620
152621
152622
152623
152624
152625
152626
152627
152628
152629
152630
152631
152632
152633
152634
152635
152636
152637
152638
152639
152640
152641
152642
152643namespace duckdb {
152644
152645class IndexPointer {
152646public:
152648 static constexpr idx_t SHIFT_OFFSET = 32;
152649 static constexpr idx_t SHIFT_METADATA = 56;
152651 static constexpr idx_t AND_OFFSET = 0x0000000000FFFFFF;
152652 static constexpr idx_t AND_BUFFER_ID = 0x00000000FFFFFFFF;
152653 static constexpr idx_t AND_METADATA = 0xFF00000000000000;
152654
152655public:
152657 IndexPointer() : data(0) {};
152659 IndexPointer(const uint32_t buffer_id, const uint32_t offset) : data(0) {
152660 auto shifted_offset = UnsafeNumericCast<idx_t>(offset) << SHIFT_OFFSET;
152661 data += shifted_offset;
152662 data += buffer_id;
152663 };
152664
152665public:
152667 inline idx_t Get()
const {
152668 return data;
152669 }
152671 inline void Set(const idx_t data_p) {
152672 data = data_p;
152673 }
152674
152676 inline bool HasMetadata() const {
152677 return data & AND_METADATA;
152678 }
152680 inline uint8_t GetMetadata()
const {
152681 return data >> SHIFT_METADATA;
152682 }
152684 inline void SetMetadata(const uint8_t metadata) {
152685 data &= ~AND_METADATA;
152686 data |= UnsafeNumericCast<idx_t>(metadata) << SHIFT_METADATA;
152687 }
152688
152690 inline idx_t GetOffset()
const {
152691 auto offset = data >> SHIFT_OFFSET;
152692 return offset & AND_OFFSET;
152693 }
152695 inline idx_t GetBufferId()
const {
152696 return data & AND_BUFFER_ID;
152697 }
152698
152700 inline void Clear() {
152701 data = 0;
152702 }
152703
152705 inline void IncreaseBufferId(const idx_t summand) {
152706 data += summand;
152707 }
152708
152710 inline bool operator==(
const IndexPointer &ptr)
const {
152711 return data == ptr.data;
152712 }
152713
152714private:
152728};
152729
152730static_assert(
sizeof(IndexPointer) ==
sizeof(
idx_t),
"Invalid size for IndexPointer.");
152731
152732}
152733
152734
152735
152736
152737
152738
152739
152740
152741
152742
152743
152744
152745
152746
152747
152748
152749
152750
152751
152752
152753
152754
152755
152756
152757namespace duckdb {
152758class DuckTransaction;
152759class Transaction;
152760
152761struct TransactionData {
152762 TransactionData(DuckTransaction &transaction_p);
152763 TransactionData(transaction_t transaction_id_p, transaction_t start_time_p);
152764
152765 optional_ptr<DuckTransaction> transaction;
152768
152769 static TransactionData Committed() {
152770 return TransactionData(MAX_TRANSACTION_ID, 0);
152771 }
152772};
152773
152774}
152775
152776
152777namespace duckdb {
152778
152779enum class InsertedScanType {
152780
152781 STANDARD,
152782
152783 ALL_ROWS
152784};
152785
152788 STANDARD,
152793};
152794
152797 STANDARD,
152798
152799 DISALLOW_UPDATES
152800};
152801
152802struct ScanOptions {
152803 ScanOptions(TransactionData transaction);
152804
152805 TransactionData transaction;
152806 InsertedScanType insert_type = InsertedScanType::STANDARD;
152809};
152810
152819};
152820
152821}
152822
152823
152824namespace duckdb {
152825class RowGroup;
152826struct SelectionVector;
152827class Transaction;
152828struct TransactionData;
152829struct DeleteInfo;
152830class Serializer;
152831class Deserializer;
152832class FixedSizeAllocator;
152833
152834enum class ChunkInfoType :
uint8_t { CONSTANT_INFO, VECTOR_INFO, EMPTY_INFO };
152835
152836class ChunkInfo {
152837public:
152838 ChunkInfo(idx_t start, ChunkInfoType type) : start(start), type(type) {
152839 }
152840 virtual ~ChunkInfo() {
152841 }
152842
152846 ChunkInfoType type;
152847
152848public:
152851 virtual idx_t GetSelVector(ScanOptions options, optional_ptr<SelectionVector> sel_vector,
152852 idx_t max_count) const = 0;
152853 idx_t GetCheckpointRowCount(TransactionData transaction, idx_t max_count);
152855 virtual bool Fetch(TransactionData transaction, row_t row) = 0;
152856 virtual void CommitAppend(transaction_t commit_id, idx_t start, idx_t end) = 0;
152857 idx_t GetCommittedDeletedCount(idx_t max_count)
const;
152858 virtual bool Cleanup(transaction_t lowest_transaction) const;
152859 virtual string ToString(idx_t max_count) const = 0;
152860
152861 virtual bool HasDeletes(transaction_t transaction_id = MAX_TRANSACTION_ID) const = 0;
152862
152863 virtual void Write(WriteStream &writer, transaction_t transaction_id) const;
152864 static unique_ptr<ChunkInfo> Read(FixedSizeAllocator &allocator, ReadStream &reader);
152865
152866public:
152867 template <class TARGET>
152868 TARGET &Cast() {
152869 if (type != TARGET::TYPE) {
152870 throw InternalException("Failed to cast chunk info to type - query result type mismatch");
152871 }
152872 return reinterpret_cast<TARGET &>(*this);
152873 }
152874
152875 template <class TARGET>
152876 const TARGET &Cast() const {
152877 if (type != TARGET::TYPE) {
152878 throw InternalException("Failed to cast chunk info to type - query result type mismatch");
152879 }
152880 return reinterpret_cast<const TARGET &>(*this);
152881 }
152882};
152883
152884class ChunkConstantInfo : public ChunkInfo {
152885public:
152886 static constexpr const ChunkInfoType
TYPE = ChunkInfoType::CONSTANT_INFO;
152887
152888public:
152889 explicit ChunkConstantInfo(idx_t start);
152890
152893
152894public:
152895 idx_t GetSelVector(ScanOptions options, optional_ptr<SelectionVector> sel_vector, idx_t max_count)
const override;
152896 bool Fetch(TransactionData transaction, row_t row) override;
152897 void CommitAppend(transaction_t commit_id, idx_t start, idx_t end) override;
152898 bool Cleanup(transaction_t lowest_transaction) const override;
152899 string ToString(idx_t max_count) const override;
152900
152901 bool HasDeletes(transaction_t transaction_id = MAX_TRANSACTION_ID) const override;
152902
152903 void Write(WriteStream &writer, transaction_t transaction_id) const override;
152904 static unique_ptr<ChunkInfo> Read(ReadStream &reader);
152905
152906private:
152907 template <class INSERT_OP, class DELETE_OP>
152908 idx_t TemplatedGetSelVector(transaction_t start_time, transaction_t transaction_id, idx_t max_count)
const;
152909};
152910
152911class ChunkVectorInfo : public ChunkInfo {
152912public:
152913 static constexpr const ChunkInfoType
TYPE = ChunkInfoType::VECTOR_INFO;
152914
152915public:
152916 explicit ChunkVectorInfo(FixedSizeAllocator &allocator, idx_t start, transaction_t insert_id = 0);
152917 ~ChunkVectorInfo() override;
152918
152919public:
152920 idx_t GetSelVector(ScanOptions options, optional_ptr<SelectionVector> sel_vector, idx_t max_count)
const override;
152921 bool Fetch(TransactionData transaction, row_t row) override;
152922 void CommitAppend(transaction_t commit_id, idx_t start, idx_t end) override;
152923 bool Cleanup(transaction_t lowest_transaction) const override;
152924 string ToString(idx_t max_count) const override;
152925
152926 void Append(idx_t start, idx_t end, transaction_t commit_id);
152927
152933 idx_t Delete(transaction_t transaction_id, row_t
rows[], idx_t count);
152934 void CommitDelete(transaction_t commit_id, const DeleteInfo &info);
152935
152936 bool HasDeletes(transaction_t transaction_id = MAX_TRANSACTION_ID) const override;
152937 bool AnyDeleted() const;
152938 bool HasConstantInsertionId() const;
152940
152941 void Write(WriteStream &writer, transaction_t transaction_id) const override;
152942 static unique_ptr<ChunkInfo> Read(FixedSizeAllocator &allocator, ReadStream &reader);
152943
152944private:
152945 template <class INSERT_OP, class DELETE_OP>
152946 idx_t TemplatedGetSelVector(transaction_t start_time, transaction_t transaction_id,
152947 optional_ptr<SelectionVector> sel_vector, idx_t max_count) const;
152948
152949 IndexPointer GetInsertedPointer() const;
152950 IndexPointer GetDeletedPointer() const;
152951 IndexPointer GetInitializedInsertedPointer();
152952 IndexPointer GetInitializedDeletedPointer();
152953
152954private:
152955 FixedSizeAllocator &allocator;
152957 IndexPointer inserted_data;
152960
152962 IndexPointer deleted_data;
152963};
152964
152965}
152966
152967
152968
152969
152970
152971
152972
152973
152974
152975
152976
152977
152978
152979namespace duckdb {
152980
152981class SegmentStatistics {
152982public:
152983 explicit SegmentStatistics(LogicalType type);
152984 explicit SegmentStatistics(BaseStatistics statistics);
152985
152987 BaseStatistics statistics;
152988};
152989
152990}
152991
152992
152993
152994
152995
152996
152997
152998
152999
153000
153001
153002
153003
153004
153005
153006
153007namespace duckdb {
153008
153010class ColumnList {
153011public:
153012 class ColumnListIterator;
153013
153014public:
153015 DUCKDB_API explicit ColumnList(bool allow_duplicate_names = false);
153016 DUCKDB_API explicit ColumnList(vector<ColumnDefinition> columns, bool allow_duplicate_names = false);
153017
153018 DUCKDB_API void AddColumn(ColumnDefinition column);
153019 void Finalize();
153020
153021 DUCKDB_API const ColumnDefinition &GetColumn(LogicalIndex index) const;
153022 DUCKDB_API const ColumnDefinition &GetColumn(PhysicalIndex index) const;
153023 DUCKDB_API const ColumnDefinition &GetColumn(const string &name) const;
153024 DUCKDB_API ColumnDefinition &GetColumnMutable(LogicalIndex index);
153025 DUCKDB_API ColumnDefinition &GetColumnMutable(PhysicalIndex index);
153026 DUCKDB_API ColumnDefinition &GetColumnMutable(const string &name);
153027 DUCKDB_API vector<string> GetColumnNames() const;
153028 DUCKDB_API vector<LogicalType> GetColumnTypes() const;
153029
153030 DUCKDB_API bool ColumnExists(const string &name) const;
153031
153032 DUCKDB_API LogicalIndex GetColumnIndex(string &column_name) const;
153033 DUCKDB_API PhysicalIndex LogicalToPhysical(LogicalIndex index) const;
153034 DUCKDB_API LogicalIndex PhysicalToLogical(PhysicalIndex index) const;
153035
153036 idx_t LogicalColumnCount()
const {
153037 return columns.size();
153038 }
153039 idx_t PhysicalColumnCount()
const {
153040 return physical_columns.size();
153041 }
153042 bool empty() const {
153043 return columns.empty();
153044 }
153045
153046 ColumnList Copy() const;
153047 void Serialize(Serializer &serializer) const;
153048 static ColumnList Deserialize(Deserializer &deserializer);
153049
153050 DUCKDB_API ColumnListIterator Logical() const;
153051 DUCKDB_API ColumnListIterator Physical() const;
153052
153053 void SetAllowDuplicates(bool allow_duplicates) {
153054 allow_duplicate_names = allow_duplicates;
153055 }
153056
153057private:
153058 vector<ColumnDefinition> columns;
153060 case_insensitive_map_t<column_t> name_map;
153062 vector<idx_t> physical_columns;
153064 bool allow_duplicate_names;
153065
153066private:
153067 void AddToNameMap(ColumnDefinition &column);
153068
153069public:
153070
153071 class ColumnListIterator {
153072 public:
153073 ColumnListIterator(const ColumnList &list, bool physical) : list(list), physical(physical) {
153074 }
153075
153076 private:
153077 const ColumnList &list;
153078 bool physical;
153079
153080 private:
153081 class ColumnLogicalIteratorInternal {
153082 public:
153083 ColumnLogicalIteratorInternal(const ColumnList &list, bool physical, idx_t pos, idx_t end)
153084 : list(list), physical(physical), pos(pos), end(end) {
153085 }
153086
153087 const ColumnList &list;
153088 bool physical;
153091
153092 public:
153093 ColumnLogicalIteratorInternal &operator++() {
153094 pos++;
153095 return *this;
153096 }
153097 bool operator!=(
const ColumnLogicalIteratorInternal &other)
const {
153098 return pos != other.pos || end != other.end || &list != &other.list;
153099 }
153100 const ColumnDefinition &
operator*()
const {
153101 if (physical) {
153102 return list.GetColumn(PhysicalIndex(pos));
153103 } else {
153104 return list.GetColumn(LogicalIndex(pos));
153105 }
153106 }
153107 };
153108
153109 public:
153111 return physical ? list.PhysicalColumnCount() : list.LogicalColumnCount();
153112 }
153113
153114 ColumnLogicalIteratorInternal begin() {
153115 return ColumnLogicalIteratorInternal(list, physical, 0,
Size());
153116 }
153117 ColumnLogicalIteratorInternal end() {
153118 return ColumnLogicalIteratorInternal(list, physical,
Size(),
Size());
153119 }
153120 };
153121};
153122
153123}
153124
153125
153126
153127
153128
153129
153130
153131
153132
153133
153134
153135
153136
153137
153138namespace duckdb {
153139
153140template <class T>
153141class SegmentBase {
153142public:
153143 explicit SegmentBase(idx_t count) : count(count) {
153144 }
153145
153147 atomic<idx_t> count;
153148};
153149
153150}
153151
153152
153153
153154
153155
153156
153157
153158
153159
153160
153161
153162
153163
153164
153165namespace duckdb {
153166
153167class BlockAllocator;
153168class Serializer;
153169class Deserializer;
153170
153171class Block : public FileBuffer {
153172public:
153173 Block(BlockAllocator &allocator, const block_id_t id, const idx_t block_size, const idx_t block_header_size);
153174 Block(BlockAllocator &allocator, block_id_t id, uint32_t internal_size, idx_t block_header_size);
153175 Block(BlockAllocator &allocator, const block_id_t id, BlockManager &block_manager);
153176 Block(FileBuffer &source, block_id_t id, idx_t block_header_size);
153177
153178 block_id_t id;
153179};
153180
153181struct BlockPointer {
153182 BlockPointer(block_id_t block_id_p, uint32_t offset_p) : block_id(block_id_p), offset(offset_p) {
153183 }
153184 BlockPointer() : block_id(INVALID_BLOCK), offset(0) {
153185 }
153186
153187 block_id_t block_id;
153190
153191 bool IsValid() const {
153192 return block_id != INVALID_BLOCK;
153193 }
153194
153195 void Serialize(Serializer &serializer) const;
153196 static BlockPointer Deserialize(Deserializer &source);
153197};
153198
153199struct MetaBlockPointer {
153200 MetaBlockPointer(idx_t block_pointer, uint32_t offset_p) : block_pointer(block_pointer), offset(offset_p) {
153201 }
153202 MetaBlockPointer() : block_pointer(DConstants::INVALID_INDEX), offset(0) {
153203 }
153204
153205 idx_t block_pointer;
153208
153209 bool IsValid() const {
153210 return block_pointer != DConstants::INVALID_INDEX;
153211 }
153212 block_id_t GetBlockId() const;
153214
153215 bool operator==(
const MetaBlockPointer &rhs)
const {
153216 return block_pointer == rhs.block_pointer && offset == rhs.offset;
153217 }
153218
153219 friend std::ostream &
operator<<(std::ostream &os,
const MetaBlockPointer &obj) {
153220 return os << "{block_id: " << obj.GetBlockId() << " index: " << obj.GetBlockIndex() << " offset: " << obj.offset
153221 << "}";
153222 }
153223
153224 void Serialize(Serializer &serializer) const;
153225 static MetaBlockPointer Deserialize(Deserializer &source);
153226};
153227
153228}
153229
153230
153231
153232
153233
153234
153235
153236
153237
153238
153239
153240
153241
153242
153243
153244
153245
153246
153247
153248
153249
153250
153251
153252
153253namespace duckdb {
153254
153260};
153261
153267};
153268
153272 FULL_CHECKPOINT,
153278};
153279
153280}
153281
153282
153283
153284
153285namespace duckdb {
153286
153287struct CheckpointOptions {
153288 CheckpointOptions()
153290 type(
CheckpointType::FULL_CHECKPOINT), transaction_id(MAX_TRANSACTION_ID) {
153291 }
153292
153299 optional_ptr<lock_guard<mutex>> wal_lock;
153300};
153301
153302}
153303
153304
153305namespace duckdb {
153306class AttachedDatabase;
153307class BlockManager;
153308class ColumnData;
153309class DatabaseInstance;
153310class DataTable;
153311class PartialBlockManager;
153312struct DataTableInfo;
153313class ExpressionExecutor;
153314class RowGroupCollection;
153315class RowGroupWriter;
153316class UpdateSegment;
153317class TableStatistics;
153318struct ColumnSegmentInfo;
153319class Vector;
153320struct ColumnCheckpointState;
153321struct PartitionStatistics;
153322struct PersistentColumnData;
153323struct PersistentRowGroupData;
153324struct RowGroupPointer;
153325struct TransactionData;
153326class CollectionScanState;
153327class TableFilter;
153328class TableFilterSet;
153329struct ColumnFetchState;
153330struct RowGroupAppendState;
153331class MetadataManager;
153332class RowVersionManager;
153333class ScanFilterInfo;
153334class StorageCommitState;
153335template <class T>
153336struct SegmentNode;
153337enum class ColumnDataType;
153338
153339struct RowGroupWriteInfo {
153340 RowGroupWriteInfo(PartialBlockManager &manager, const vector<CompressionType> &compression_types,
153341 CheckpointOptions options = CheckpointOptions());
153342 RowGroupWriteInfo(PartialBlockManager &manager, const vector<CompressionType> &compression_types,
153343 vector<unique_ptr<PartialBlockManager>> &column_partial_block_managers_p);
153344
153345private:
153346 PartialBlockManager &manager;
153347
153348public:
153349 const vector<CompressionType> &compression_types;
153350 CheckpointOptions options;
153351
153352public:
153353 PartialBlockManager &GetPartialBlockManager(idx_t column_idx);
153354
153355private:
153356 optional_ptr<vector<unique_ptr<PartialBlockManager>>> column_partial_block_managers;
153357};
153358
153359struct RowGroupWriteData {
153360 shared_ptr<RowGroup> result_row_group;
153361 vector<unique_ptr<ColumnCheckpointState>> states;
153362 vector<BaseStatistics> statistics;
153363 bool reuse_existing_metadata_blocks = false;
153364 vector<idx_t> existing_extra_metadata_blocks;
153365 optional_idx write_count;
153366};
153367
153368class RowGroup : public SegmentBase<RowGroup> {
153369public:
153370 friend class ColumnData;
153371
153372public:
153373 RowGroup(RowGroupCollection &collection, idx_t count);
153374 RowGroup(RowGroupCollection &collection, RowGroupPointer pointer);
153375 RowGroup(RowGroupCollection &collection, PersistentRowGroupData &data);
153376 ~RowGroup();
153377
153378private:
153380 reference<RowGroupCollection> collection;
153382 atomic<optional_ptr<RowVersionManager>> version_info;
153384 shared_ptr<RowVersionManager> owned_version_info;
153386 mutable vector<shared_ptr<ColumnData>> columns;
153387
153388public:
153389 void MoveToCollection(RowGroupCollection &collection);
153390 RowGroupCollection &GetCollection() const {
153391 return collection.get();
153392 }
153394 vector<idx_t> GetOrComputeExtraMetadataBlocks(bool force_compute = false);
153395
153396 const vector<MetaBlockPointer> &GetColumnStartPointers() const;
153397
153398 BlockManager &GetBlockManager() const;
153399 DataTableInfo &GetTableInfo() const;
153400
153401 unique_ptr<RowGroup> AlterType(RowGroupCollection &collection, const LogicalType &target_type, idx_t changed_idx,
153402 ExpressionExecutor &executor, CollectionScanState &scan_state,
153403 SegmentNode<RowGroup> &node, DataChunk &scan_chunk);
153404 unique_ptr<RowGroup> AddColumn(RowGroupCollection &collection, ColumnDefinition &new_column,
153405 ExpressionExecutor &executor, Vector &intermediate);
153406 unique_ptr<RowGroup> RemoveColumn(RowGroupCollection &collection, idx_t removed_column);
153407
153408 void CommitDrop();
153409 void CommitDropColumn(const idx_t column_index);
153410
153411 void InitializeEmpty(const vector<LogicalType> &types, ColumnDataType data_type);
153412 bool HasChanges() const;
153413
153415 bool InitializeScan(CollectionScanState &state, SegmentNode<RowGroup> &node);
153416 bool InitializeScanWithOffset(CollectionScanState &state, SegmentNode<RowGroup> &node, idx_t vector_offset);
153419 bool CheckZonemap(ScanFilterInfo &filters);
153422 bool CheckZonemapSegments(CollectionScanState &state);
153423 void Scan(ScanOptions options, CollectionScanState &state, DataChunk &result);
153424 void Scan(CollectionScanState &state, DataChunk &result, TableScanType type);
153425
153426 idx_t GetSelVector(ScanOptions options, idx_t vector_idx, SelectionVector &sel_vector, idx_t max_count);
153427
153429 bool Fetch(TransactionData transaction, idx_t row);
153431 void FetchRow(TransactionData transaction, ColumnFetchState &state, const vector<StorageIndex> &column_ids,
153432 row_t row_id, DataChunk &result, idx_t result_idx);
153433
153435 void AppendVersionInfo(TransactionData transaction, idx_t count);
153437 void CommitAppend(transaction_t commit_id, idx_t start, idx_t count);
153439 void RevertAppend(idx_t new_count);
153441 void CleanupAppend(transaction_t lowest_transaction, idx_t start, idx_t count);
153442
153444 idx_t Delete(TransactionData transaction, DataTable &table, row_t *row_ids, idx_t count, idx_t row_group_start);
153445
153446 static vector<RowGroupWriteData> WriteToDisk(RowGroupWriteInfo &info,
153447 const vector<const_reference<RowGroup>> &row_groups);
153450 RowGroupWriteData WriteToDisk(RowGroupWriteInfo &info) const;
153452 idx_t GetCommittedRowCount();
153453 RowGroupWriteData WriteToDisk(RowGroupWriter &writer);
153454 RowGroupPointer Checkpoint(RowGroupWriteData write_data, RowGroupWriter &writer, TableStatistics &global_stats,
153455 idx_t row_group_start);
153456 bool IsPersistent() const;
153457 PersistentRowGroupData SerializeRowGroupInfo(idx_t row_group_start) const;
153458
153459 void InitializeAppend(RowGroupAppendState &append_state);
153460 void Append(RowGroupAppendState &append_state, DataChunk &chunk, idx_t append_count);
153461
153462 void Update(TransactionData transaction, DataTable &data_table, DataChunk &updates, row_t *ids, idx_t offset,
153463 idx_t count, const vector<PhysicalIndex> &column_ids, idx_t row_group_start);
153466 void UpdateColumn(TransactionData transaction, DataTable &data_table, DataChunk &updates, Vector &row_ids,
153467 idx_t offset, idx_t count, const vector<column_t> &column_path, idx_t row_group_start);
153468
153469 void MergeStatistics(idx_t column_idx, const BaseStatistics &other);
153470 void MergeIntoStatistics(idx_t column_idx, BaseStatistics &other);
153471 void MergeIntoStatistics(TableStatistics &other);
153472 unique_ptr<BaseStatistics> GetStatistics(idx_t column_idx) const;
153473 unique_ptr<BaseStatistics> GetStatistics(const StorageIndex &column_idx) const;
153474
153475 void GetColumnSegmentInfo(const QueryContext &context, idx_t row_group_index, vector<ColumnSegmentInfo> &result);
153476 static PartitionStatistics GetPartitionStats(SegmentNode<RowGroup> &row_group);
153477
153478 idx_t GetAllocationSize()
const {
153479 return allocation_size;
153480 }
153481
153482 void Verify();
153483
153484 void NextVector(CollectionScanState &state);
153485
153486 idx_t DeleteRows(idx_t vector_idx, transaction_t transaction_id, row_t
rows[], idx_t count);
153487 RowVersionManager &GetOrCreateVersionInfo();
153488
153489
153490 static void Serialize(RowGroupPointer &pointer, Serializer &serializer);
153491 static RowGroupPointer Deserialize(Deserializer &deserializer);
153492
153493 idx_t GetRowGroupSize()
const;
153494
153495 static FilterPropagateResult CheckRowIdFilter(const TableFilter &filter, idx_t beg_row, idx_t end_row);
153496 idx_t GetColumnCount()
const;
153497
153498 vector<MetaBlockPointer> CheckpointDeletes(RowGroupWriter &writer);
153499
153500private:
153501 optional_ptr<RowVersionManager> GetVersionInfo();
153502 optional_ptr<RowVersionManager> GetVersionInfoIfLoaded() const;
153503 shared_ptr<RowVersionManager> GetOrCreateVersionInfoPtr();
153504 shared_ptr<RowVersionManager> GetOrCreateVersionInfoInternal();
153505 void SetVersionInfo(shared_ptr<RowVersionManager> version);
153506
153507 ColumnData &GetColumn(storage_t c) const;
153508 void LoadColumn(storage_t c) const;
153509 ColumnData &GetColumn(const StorageIndex &c) const;
153510 vector<shared_ptr<ColumnData>> &GetColumns();
153511 void LoadRowIdColumnData() const;
153512 void SetCount(idx_t count);
153513
153514 bool HasUnloadedDeletes() const;
153515
153516private:
153517 mutable mutex row_group_lock;
153518 vector<MetaBlockPointer> column_pointers;
153520 mutable unique_ptr<atomic<bool>[]> is_loaded;
153521 vector<MetaBlockPointer> deletes_pointers;
153522 bool has_metadata_blocks = false;
153523 vector<idx_t> extra_metadata_blocks;
153524 atomic<bool> deletes_is_loaded;
153525 atomic<idx_t> allocation_size;
153527 mutable unique_ptr<ColumnData> row_id_column_data;
153529 mutable atomic<bool> row_id_is_loaded;
153530 atomic<bool> has_changes;
153531};
153532
153533}
153534
153535
153536
153537
153538
153539
153540
153541
153542
153543
153544
153545
153546
153547
153548
153549
153550
153551
153552
153553
153554
153555
153556
153557
153558
153559
153560
153561
153562
153563
153564
153565
153566
153567
153568
153569namespace duckdb {
153570struct StorageLockInternals;
153571
153572enum class StorageLockType { SHARED = 0, EXCLUSIVE = 1 };
153573
153574class StorageLockKey {
153575public:
153576 StorageLockKey(shared_ptr<StorageLockInternals> internals, StorageLockType type);
153577 ~StorageLockKey();
153578
153579 StorageLockType GetType() const {
153580 return type;
153581 }
153582
153583private:
153584 shared_ptr<StorageLockInternals> internals;
153585 StorageLockType type;
153586};
153587
153588class StorageLock {
153589public:
153590 StorageLock();
153591 ~StorageLock();
153592
153594 unique_ptr<StorageLockKey> GetExclusiveLock();
153596 unique_ptr<StorageLockKey> GetSharedLock();
153598 unique_ptr<StorageLockKey> TryGetExclusiveLock();
153603 unique_ptr<StorageLockKey> TryUpgradeCheckpointLock(StorageLockKey &lock);
153604
153605private:
153606 shared_ptr<StorageLockInternals> internals;
153607};
153608
153609}
153610
153611
153612
153613
153614
153615
153616
153617
153618
153619
153620
153621
153622
153623namespace duckdb {
153624
153625struct SegmentLock {
153626public:
153627 SegmentLock() {
153628 }
153629 explicit SegmentLock(mutex &lock) : lock(lock) {
153630 }
153631
153632 SegmentLock(const SegmentLock &other) = delete;
153633 SegmentLock &
operator=(
const SegmentLock &) =
delete;
153635 SegmentLock(SegmentLock &&other) noexcept {
153636 std::swap(lock, other.lock);
153637 }
153638 SegmentLock &
operator=(SegmentLock &&other)
noexcept {
153639 std::swap(lock, other.lock);
153640 return *this;
153641 }
153642
153643 void Release() {
153644 lock.unlock();
153645 }
153646
153647private:
153648 unique_lock<mutex> lock;
153649};
153650
153651}
153652
153653
153654
153655
153656
153657
153658namespace duckdb {
153659
153660template <class T>
153661struct SegmentNode {
153662 SegmentNode(idx_t row_start_p, shared_ptr<T> node_p, idx_t index_p)
153663 : row_start(row_start_p), node(std::move(node_p)), next(nullptr),
index(index_p) {
153664 }
153665
153666public:
153667 optional_ptr<SegmentNode<T>> Next() const {
153668#ifndef DUCKDB_R_BUILD
153669 return next.load();
153670#else
153671 return next;
153672#endif
153673 }
153674
153675 idx_t GetRowStart()
const {
153676 return row_start;
153677 }
153678 idx_t GetRowEnd()
const {
153679 return GetRowStart() + GetCount();
153680 }
153681 idx_t GetCount()
const {
153682 return GetNode().count;
153683 }
153684
153685 idx_t GetIndex()
const {
153687 }
153688
153689 T &GetNode() const {
153690 return *node;
153691 }
153692
153693 shared_ptr<T> MoveNode() {
153694 return std::move(node);
153695 }
153696 shared_ptr<T> &ReferenceNode() {
153697 return node;
153698 }
153699
153700 bool HasNode() const {
153701 return node.get();
153702 }
153703
153704 void SetNext(optional_ptr<SegmentNode<T>> next) {
153705 this->next = next.get();
153706 }
153707
153708 void SetNode(shared_ptr<T> new_node) {
153709 node = std::move(new_node);
153710 }
153711
153712private:
153714 shared_ptr<T> node;
153716#ifndef DUCKDB_R_BUILD
153717 atomic<SegmentNode<T> *> next;
153718#else
153719 SegmentNode<T> *next;
153720#endif
153723};
153724
153727
153728
153729
153730template <class T, bool SUPPORTS_LAZY_LOADING = false>
153731class SegmentTree {
153732private:
153733 class SegmentIterationHelper;
153734 class SegmentNodeIterationHelper;
153735
153736public:
153737 explicit SegmentTree(idx_t base_row_id = 0) : finished_loading(true), base_row_id(base_row_id) {
153738 }
153739 virtual ~SegmentTree() {
153740 }
153741
153744 SegmentLock Lock() const {
153745 return SegmentLock(node_lock);
153746 }
153747
153748 bool IsEmpty(SegmentLock &l) const {
153749 return GetRootSegment(l) == nullptr;
153750 }
153751
153753 optional_ptr<SegmentNode<T>> GetRootSegment() const {
153754 auto l = Lock();
153755 return GetRootSegment(l);
153756 }
153757
153758 optional_ptr<SegmentNode<T>> GetRootSegment(SegmentLock &l) const {
153759 if (nodes.empty()) {
153760 LoadNextSegment(l);
153761 }
153762 return GetRootSegmentInternal();
153763 }
153765 vector<unique_ptr<SegmentNode<T>>> MoveSegments(SegmentLock &l) {
153766 LoadAllSegments(l);
153767 return std::move(nodes);
153768 }
153769 vector<unique_ptr<SegmentNode<T>>> MoveSegments() {
153770 auto l = Lock();
153771 return MoveSegments(l);
153772 }
153773
153774 vector<unique_ptr<SegmentNode<T>>> &ReferenceLoadedSegmentsMutable(SegmentLock &l) {
153775 return nodes;
153776 }
153777
153778 idx_t GetSegmentCount()
const {
153779 auto l = Lock();
153780 return GetSegmentCount(l);
153781 }
153782 idx_t GetSegmentCount(SegmentLock &l)
const {
153783 LoadAllSegments(l);
153784 return nodes.size();
153785 }
153787 optional_ptr<SegmentNode<T>> GetSegmentByIndex(int64_t index) const {
153788 auto l = Lock();
153789 return GetSegmentByIndex(l, index);
153790 }
153791 optional_ptr<SegmentNode<T>> GetSegmentByIndex(SegmentLock &l, int64_t index) const {
153792 if (index < 0) {
153793
153794 LoadAllSegments(l);
153795 index += nodes.size();
153796 if (index < 0) {
153797 return nullptr;
153798 }
153799 return nodes[UnsafeNumericCast<idx_t>(index)].get();
153800 } else {
153801
153802 while (
idx_t(index) >= nodes.size() && LoadNextSegment(l)) {
153803 }
153804 if (
idx_t(index) >= nodes.size()) {
153805 return nullptr;
153806 }
153807 return nodes[UnsafeNumericCast<idx_t>(index)].get();
153808 }
153809 }
153811 optional_ptr<SegmentNode<T>> GetNextSegment(SegmentNode<T> &node) const {
153812 if (!SUPPORTS_LAZY_LOADING) {
153813 return node.Next();
153814 }
153815 if (finished_loading) {
153816 return node.Next();
153817 }
153818 auto l = Lock();
153819 return GetNextSegment(l, node);
153820 }
153821 optional_ptr<SegmentNode<T>> GetNextSegment(SegmentLock &l, SegmentNode<T> &node) const {
153822#ifdef DEBUG
153824#endif
153825 return GetSegmentByIndex(l, UnsafeNumericCast<int64_t>(node.GetIndex() + 1));
153826 }
153827
153829 optional_ptr<SegmentNode<T>> GetLastSegment(SegmentLock &l) const {
153830 LoadAllSegments(l);
153831 if (nodes.empty()) {
153832 return nullptr;
153833 }
153834 return nodes.back().get();
153835 }
153837 optional_ptr<SegmentNode<T>> GetSegment(idx_t row_number) const {
153838 auto l = Lock();
153839 return GetSegment(l, row_number);
153840 }
153841 optional_ptr<SegmentNode<T>> GetSegment(SegmentLock &l, idx_t row_number) const {
153842 return nodes[GetSegmentIndex(l, row_number)].get();
153843 }
153844
153845 void AppendSegment(shared_ptr<T> segment) {
153846 auto l = Lock();
153847 AppendSegment(l, std::move(segment));
153848 }
153849 void AppendSegment(SegmentLock &l, shared_ptr<T> segment) {
153850 LoadAllSegments(l);
153851 AppendSegmentInternal(l, std::move(segment));
153852 }
153853 void AppendSegment(SegmentLock &l, shared_ptr<T> segment, idx_t row_start) {
153854 LoadAllSegments(l);
153855 AppendSegmentInternal(l, std::move(segment), row_start);
153856 }
153858 bool HasSegment(SegmentNode<T> &segment) const {
153859 auto l = Lock();
153860 return HasSegment(l, segment);
153861 }
153862 bool HasSegment(SegmentLock &, SegmentNode<T> &segment) const {
153863 auto segment_idx = segment.GetIndex();
153864 return segment_idx < nodes.size() &&
RefersToSameObject(*nodes[segment_idx], segment);
153865 }
153866
153868 void EraseSegments(SegmentLock &l, idx_t segment_start) {
153869 LoadAllSegments(l);
153870 if (segment_start >= nodes.size()) {
153871 return;
153872 }
153873 nodes.erase(nodes.begin() + UnsafeNumericCast<int64_t>(segment_start), nodes.end());
153874 }
153875
153877 idx_t GetSegmentIndex(SegmentLock &l, idx_t row_number)
const {
153878 idx_t segment_index;
153879 if (TryGetSegmentIndex(l, row_number, segment_index)) {
153880 return segment_index;
153881 }
153882 string error;
153883 error =
StringUtil::Format(
"Attempting to find row number \"%lld\" in %lld nodes\n", row_number, nodes.size());
153884 for (idx_t i = 0; i < nodes.size(); i++) {
153885 error +=
StringUtil::Format(
"* Node %lld: Start %lld, Count %lld\n", i, nodes[i]->GetRowStart(),
153886 nodes[i]->GetCount());
153887 }
153888 throw InternalException("Could not find node in column segment tree!\n%s", error);
153889 }
153890
153891 bool TryGetSegmentIndex(SegmentLock &l, idx_t row_number, idx_t &result) const {
153892
153893 while (nodes.empty() || (row_number >= nodes.back()->GetRowEnd())) {
153894 if (!LoadNextSegment(l)) {
153895 break;
153896 }
153897 }
153898 if (nodes.empty()) {
153899 return false;
153900 }
153902 idx_t upper = nodes.size() - 1;
153903
153904 while (lower <= upper) {
153906 if (index >= nodes.size()) {
153907 string segments;
153908 for (auto &entry : nodes) {
153909 segments +=
StringUtil::Format(
"Start %d Count %d", entry->GetRowStart(), entry->GetCount());
153910 }
153911 throw InternalException("Segment tree index not found for row number %d\nSegments:%s", row_number,
153912 segments);
153913 }
153914 auto &entry = *nodes[
index];
153915 if (row_number < entry.GetRowStart()) {
153916 upper =
index - 1;
153917 } else if (row_number >= entry.GetRowEnd()) {
153918 lower =
index + 1;
153919 } else {
153921 return true;
153922 }
153923 }
153924 return false;
153925 }
153926
153927 void Verify(SegmentLock &) const {
153928#ifdef DEBUG
153929 idx_t base_start = nodes.empty() ? 0 : nodes[0]->GetRowStart();
153930 for (idx_t i = 0; i < nodes.size(); i++) {
153931 D_ASSERT(nodes[i]->GetRowStart() == base_start);
153932 base_start += nodes[i]->GetCount();
153933 }
153934#endif
153935 }
153936 void Verify() {
153937#ifdef DEBUG
153938 auto l = Lock();
153939 Verify(l);
153940#endif
153941 }
153942
153943 idx_t GetBaseRowId()
const {
153944 return base_row_id;
153945 }
153946
153947 SegmentIterationHelper Segments() const {
153948 return SegmentIterationHelper(*this);
153949 }
153950
153951 SegmentIterationHelper Segments(SegmentLock &l) const {
153952 return SegmentIterationHelper(*this, l);
153953 }
153954
153955 SegmentNodeIterationHelper SegmentNodes() const {
153956 return SegmentNodeIterationHelper(*this);
153957 }
153958
153959 SegmentNodeIterationHelper SegmentNodes(SegmentLock &l) const {
153960 return SegmentNodeIterationHelper(*this, l);
153961 }
153962
153963protected:
153964 mutable atomic<bool> finished_loading;
153965
153967 virtual shared_ptr<T> LoadSegment() const {
153968 return nullptr;
153969 }
153970
153971 optional_ptr<SegmentNode<T>> GetRootSegmentInternal() const {
153972 return nodes.empty() ? nullptr : nodes[0].get();
153973 }
153974
153975private:
153977 mutable vector<unique_ptr<SegmentNode<T>>> nodes;
153979 mutable mutex node_lock;
153981 idx_t base_row_id;
153982
153983private:
153984 class BaseSegmentIterator {
153985 public:
153986 BaseSegmentIterator(const SegmentTree &tree_p, optional_ptr<SegmentNode<T>> current_p,
153987 optional_ptr<SegmentLock> lock)
153988 : tree(tree_p), current(current_p), lock(lock) {
153989 }
153990
153991 const SegmentTree &tree;
153992 optional_ptr<SegmentNode<T>> current;
153993 optional_ptr<SegmentLock> lock;
153994
153995 public:
153996 void Next() {
153997 current = lock ? tree.GetNextSegment(*lock, *current) : tree.GetNextSegment(*current);
153998 }
153999
154000 BaseSegmentIterator &operator++() {
154001 Next();
154002 return *this;
154003 }
154004 bool operator!=(
const BaseSegmentIterator &other)
const {
154005 return current != other.current;
154006 }
154007 };
154008 class SegmentIterationHelper {
154009 public:
154010 explicit SegmentIterationHelper(const SegmentTree &tree) : tree(tree) {
154011 }
154012 SegmentIterationHelper(const SegmentTree &tree, SegmentLock &l) : tree(tree), lock(l) {
154013 }
154014
154015 private:
154016 const SegmentTree &tree;
154017 optional_ptr<SegmentLock> lock;
154018
154019 private:
154020 class SegmentIterator : public BaseSegmentIterator {
154021 public:
154022 SegmentIterator(const SegmentTree &tree_p, optional_ptr<SegmentNode<T>> current_p,
154023 optional_ptr<SegmentLock> lock)
154024 : BaseSegmentIterator(tree_p, current_p, lock) {
154025 }
154026
154028 return BaseSegmentIterator::current->GetNode();
154029 }
154030 };
154031
154032 public:
154033 SegmentIterator begin() {
154034 auto root = lock ? tree.GetRootSegment(*lock) : tree.GetRootSegment();
154035 return SegmentIterator(tree, root, lock);
154036 }
154037 SegmentIterator end() {
154038 return SegmentIterator(tree, nullptr, lock);
154039 }
154040 };
154041 class SegmentNodeIterationHelper {
154042 public:
154043 explicit SegmentNodeIterationHelper(const SegmentTree &tree) : tree(tree) {
154044 }
154045 SegmentNodeIterationHelper(const SegmentTree &tree, SegmentLock &l) : tree(tree), lock(l) {
154046 }
154047
154048 private:
154049 const SegmentTree &tree;
154050 optional_ptr<SegmentLock> lock;
154051
154052 private:
154053 class SegmentIterator : public BaseSegmentIterator {
154054 public:
154055 SegmentIterator(const SegmentTree &tree_p, optional_ptr<SegmentNode<T>> current_p,
154056 optional_ptr<SegmentLock> lock)
154057 : BaseSegmentIterator(tree_p, current_p, lock) {
154058 }
154059
154061 return *BaseSegmentIterator::current;
154062 }
154063 };
154064
154065 public:
154066 SegmentIterator begin() {
154067 auto root = lock ? tree.GetRootSegment(*lock) : tree.GetRootSegment();
154068 return SegmentIterator(tree, root, lock);
154069 }
154070 SegmentIterator end() {
154071 return SegmentIterator(tree, nullptr, lock);
154072 }
154073 };
154074
154076 bool LoadNextSegment(SegmentLock &l) const {
154077 if (!SUPPORTS_LAZY_LOADING) {
154078 return false;
154079 }
154080 if (finished_loading) {
154081 return false;
154082 }
154083 auto result = LoadSegment();
154084 if (result) {
154085 AppendSegmentInternal(l, std::move(result));
154086 return true;
154087 }
154088 return false;
154089 }
154090
154092 void LoadAllSegments(SegmentLock &l) const {
154093 if (!SUPPORTS_LAZY_LOADING) {
154094 return;
154095 }
154096 while (LoadNextSegment(l)) {
154097 }
154098 }
154099
154101 void AppendSegmentInternal(SegmentLock &l, shared_ptr<T> segment, idx_t row_start) const {
154102 D_ASSERT(segment);
154103
154104 auto node = make_uniq<SegmentNode<T>>(row_start, std::move(segment), nodes.size());
154105 if (!nodes.empty()) {
154106 nodes.back()->SetNext(*node);
154107 }
154108 nodes.push_back(std::move(node));
154109 }
154110 void AppendSegmentInternal(SegmentLock &l, shared_ptr<T> segment) const {
154112 if (nodes.empty()) {
154113 row_start = base_row_id;
154114 } else {
154115 auto &last_node = nodes.back();
154116 row_start = last_node->GetRowEnd();
154117 }
154118 AppendSegmentInternal(l, std::move(segment), row_start);
154119 }
154120};
154121
154122}
154123
154124
154125
154126namespace duckdb {
154127struct DataTableInfo;
154128class PersistentTableData;
154129class MetadataReader;
154130
154131class RowGroupSegmentTree : public SegmentTree<RowGroup, true> {
154132public:
154133 RowGroupSegmentTree(RowGroupCollection &collection, idx_t base_row_id);
154134 ~RowGroupSegmentTree() override;
154135
154136 void Initialize(PersistentTableData &data, optional_ptr<vector<MetaBlockPointer>> read_pointers = nullptr);
154137
154138 MetaBlockPointer GetRootPointer() const {
154139 return root_pointer;
154140 }
154141
154142protected:
154143 shared_ptr<RowGroup> LoadSegment() const override;
154144
154145 RowGroupCollection &collection;
154146 mutable idx_t current_row_group;
154147 mutable idx_t max_row_group;
154148 mutable unique_ptr<MetadataReader> reader;
154149 MetaBlockPointer root_pointer;
154150};
154151
154152}
154153
154154
154155
154156
154157namespace duckdb {
154158
154159enum class OrderByStatistics :
uint8_t { MIN, MAX };
154160enum class OrderByColumnType :
uint8_t { NUMERIC,
STRING };
154161
154162struct RowGroupOrderOptions {
154163 RowGroupOrderOptions(const StorageIndex &column_idx_p, OrderByStatistics order_by_p, OrderType order_type_p,
154164 OrderByNullType null_order_p, OrderByColumnType column_type_p,
154165 optional_idx row_limit_p = optional_idx(), idx_t row_group_offset_p = 0,
154166 idx_t leading_null_group_offset_p = 0)
154167 : column_idx(column_idx_p), order_by(order_by_p), order_type(order_type_p), null_order(null_order_p),
154168 column_type(column_type_p), row_limit(row_limit_p), row_group_offset(row_group_offset_p),
154169 leading_null_group_offset(leading_null_group_offset_p) {
154170 }
154171
154172 const StorageIndex column_idx;
154173 const OrderByStatistics order_by;
154174 const OrderType order_type;
154175 const OrderByNullType null_order;
154176 const OrderByColumnType column_type;
154177 const optional_idx row_limit;
154178 const idx_t row_group_offset;
154179 const idx_t leading_null_group_offset;
154180
154181 void Serialize(Serializer &serializer) const;
154182 static unique_ptr<RowGroupOrderOptions> Deserialize(Deserializer &deserializer);
154183};
154184
154185struct OffsetPruningResult {
154186 idx_t offset_remainder;
154187 idx_t pruned_row_group_count;
154188 idx_t leading_null_group_offset;
154189};
154190
154191class RowGroupReorderer {
154192public:
154193 explicit RowGroupReorderer(const RowGroupOrderOptions &options_p);
154194 optional_ptr<SegmentNode<RowGroup>> GetRootSegment(RowGroupSegmentTree &row_groups);
154195 optional_ptr<SegmentNode<RowGroup>> GetNextRowGroup(SegmentNode<RowGroup> &row_group);
154196
154197 static Value RetrieveStat(const BaseStatistics &stats, OrderByStatistics order_by, OrderByColumnType column_type);
154198 static OffsetPruningResult GetOffsetAfterPruning(OrderByStatistics order_by, OrderByColumnType column_type,
154199 OrderType order_type, OrderByNullType null_order,
154200 const StorageIndex &column_idx, idx_t row_offset,
154201 vector<PartitionStatistics> &stats);
154202
154203private:
154204 const RowGroupOrderOptions options;
154205
154207 bool initialized;
154208 vector<reference<SegmentNode<RowGroup>>> ordered_row_groups;
154209};
154210
154211}
154212
154213
154214
154215
154216
154217
154218
154219
154220
154221
154222
154223
154224
154225
154226
154227namespace duckdb {
154228
154229struct TableColumn {
154230 TableColumn() = default;
154231 TableColumn(string name_p, LogicalType type_p) : name(std::move(name_p)), type(std::move(type_p)) {
154232 }
154233
154234 string name;
154235 LogicalType type;
154236
154237 void Serialize(Serializer &serializer) const;
154238 static TableColumn Deserialize(Deserializer &deserializer);
154239};
154240
154241using virtual_column_map_t = unordered_map<column_t, TableColumn>;
154242
154243}
154244
154245
154246
154247
154248
154249
154250
154251
154252
154253
154254
154255
154256
154257
154258
154259
154260
154261
154262
154263
154264
154265
154266
154267
154268#include <stdint.h>
154269
154270
154271namespace duckdb {
154272
154273struct EnumUtil {
154274
154275 template <class T>
154276 static T FromString(const char *value) = delete;
154277
154278 template <class T>
154279 static T FromString(const string &value) { return FromString<T>(value.c_str()); }
154280
154281
154282 template <class T>
154283 static const char *ToChars(T value) = delete;
154284
154285 template <class T>
154286 static string ToString(T value) { return string(ToChars<T>(value)); }
154287};
154288
154289enum class ARTConflictType :
uint8_t;
154290
154291enum class ARTHandlingResult :
uint8_t;
154292
154293enum class ARTScanHandling :
uint8_t;
154294
154296
154297enum class AccessMode :
uint8_t;
154298
154300
154302
154303enum class AggregateHandling :
uint8_t;
154304
154306
154307enum class AggregateType :
uint8_t;
154308
154309enum class AllowParserOverride :
uint8_t;
154310
154311enum class AlterDatabaseType :
uint8_t;
154312
154313enum class AlterForeignKeyType :
uint8_t;
154314
154315enum class AlterScalarFunctionType :
uint8_t;
154316
154317enum class AlterTableFunctionType :
uint8_t;
154318
154319enum class AlterTableType :
uint8_t;
154320
154321enum class AlterType :
uint8_t;
154322
154323enum class AlterViewType :
uint8_t;
154324
154325enum class AppenderType :
uint8_t;
154326
154327enum class ArrowArrayPhysicalType :
uint8_t;
154328
154329enum class ArrowDateTimeType :
uint8_t;
154330
154332
154333enum class ArrowOffsetSize :
uint8_t;
154334
154335enum class ArrowTypeInfoType :
uint8_t;
154336
154337enum class ArrowVariableSizeType :
uint8_t;
154338
154340
154341enum class AsyncResultsExecutionMode :
uint8_t;
154342
154344
154345enum class BinderType :
uint8_t;
154346
154347enum class BindingMode :
uint8_t;
154348
154349enum class BitpackingMode :
uint8_t;
154350
154352
154353enum class BlockState :
uint8_t;
154354
154355enum class BufferedIndexReplay :
uint8_t;
154356
154357enum class CAPIResultSetType :
uint8_t;
154358
154360
154361enum class CTEMaterialize :
uint8_t;
154362
154363enum class CacheValidationMode :
uint8_t;
154364
154366
154368
154369enum class CatalogType :
uint8_t;
154370
154371enum class CheckpointAbort :
uint8_t;
154372
154373enum class ChunkInfoType :
uint8_t;
154374
154376
154378
154380
154381enum class ColumnSegmentType :
uint8_t;
154382
154384
154385enum class CompressionType :
uint8_t;
154386
154387enum class CompressionValidity :
uint8_t;
154388
154389enum class ConflictManagerMode :
uint8_t;
154390
154391enum class ConstraintType :
uint8_t;
154392
154394
154395enum class CopyFunctionReturnType :
uint8_t;
154396
154397enum class CopyOverwriteMode :
uint8_t;
154398
154399enum class CopyToType :
uint8_t;
154400
154401enum class DataFileType :
uint8_t;
154402
154403enum class DateCastResult :
uint8_t;
154404
154405enum class DatePartSpecifier :
uint8_t;
154406
154407enum class DebugInitialize :
uint8_t;
154408
154409enum class DebugVectorVerification :
uint8_t;
154410
154411enum class DecimalBitWidth :
uint8_t;
154412
154413enum class DefaultOrderByNullType :
uint8_t;
154414
154416
154417enum class DeprecatedIndexType :
uint8_t;
154418
154419enum class DeprecatedUsingKeySyntax :
uint8_t;
154420
154422
154423enum class DistinctType :
uint8_t;
154424
154426
154427enum class ExceptionFormatValueType :
uint8_t;
154428
154429enum class ExceptionType :
uint8_t;
154430
154431enum class ExplainFormat :
uint8_t;
154432
154433enum class ExplainOutputType :
uint8_t;
154434
154435enum class ExplainType :
uint8_t;
154436
154437enum class ExponentType :
uint8_t;
154438
154439enum class ExpressionClass :
uint8_t;
154440
154441enum class ExpressionType :
uint8_t;
154442
154444
154446
154447enum class ExtensionLoadResult :
uint8_t;
154448
154449enum class ExtensionUpdateResultTag :
uint8_t;
154450
154451enum class ExtraDropInfoType :
uint8_t;
154452
154453enum class ExtraPersistentColumnDataType :
uint8_t;
154454
154456
154457enum class FileBufferType :
uint8_t;
154458
154459enum class FileCompressionType :
uint8_t;
154460
154461enum class FileExpandResult :
uint8_t;
154462
154463enum class FileGlobOptions :
uint8_t;
154464
154465enum class FileLockType :
uint8_t;
154466
154467enum class FileNameSegmentType :
uint8_t;
154468
154469enum class FilterPropagateResult :
uint8_t;
154470
154471enum class ForeignKeyType :
uint8_t;
154472
154474
154476
154478
154480
154481enum class GateStatus :
uint8_t;
154482
154483enum class GeometryStorageType :
uint8_t;
154484
154485enum class GeometryType :
uint8_t;
154486
154488
154489enum class HTTPStatusCode :
uint16_t;
154490
154491enum class IndexAppendMode :
uint8_t;
154492
154494
154495enum class IndexConstraintType :
uint8_t;
154496
154497enum class InsertColumnOrder :
uint8_t;
154498
154500
154501enum class JoinRefType :
uint8_t;
154502
154503enum class JoinType :
uint8_t;
154504
154505enum class KeywordCategory :
uint8_t;
154506
154507enum class LambdaSyntax :
uint8_t;
154508
154509enum class LambdaSyntaxType :
uint8_t;
154510
154511enum class LimitNodeType :
uint8_t;
154512
154513enum class LoadType :
uint8_t;
154514
154515enum class LogContextScope :
uint8_t;
154516
154518
154519enum class LogMode :
uint8_t;
154520
154522
154523enum class LogicalOperatorType :
uint8_t;
154524
154526
154527enum class LookupResultType :
uint8_t;
154528
154529enum class MacroType :
uint8_t;
154530
154531enum class MapInvalidReason :
uint8_t;
154532
154533enum class MemoryTag :
uint8_t;
154534
154535enum class MergeActionCondition :
uint8_t;
154536
154537enum class MergeActionType :
uint8_t;
154538
154540
154541enum class MetricGroup :
uint8_t;
154542
154543enum class MetricType :
uint8_t;
154544
154545enum class MultiFileColumnMappingMode :
uint8_t;
154546
154547enum class MultiFileFileState :
uint8_t;
154548
154550
154551enum class NewLineIdentifier :
uint8_t;
154552
154553enum class OnConflictAction :
uint8_t;
154554
154555enum class OnCreateConflict :
uint8_t;
154556
154557enum class OnEntryNotFound :
uint8_t;
154558
154559enum class OperatorCachingMode :
uint8_t;
154560
154562
154564
154566
154567enum class OptimizerType :
uint32_t;
154568
154569enum class OrderByColumnType :
uint8_t;
154570
154571enum class OrderByNullType :
uint8_t;
154572
154573enum class OrderByStatistics :
uint8_t;
154574
154575enum class OrderPreservationType :
uint8_t;
154576
154577enum class OrderType :
uint8_t;
154578
154579enum class OrdinalityType :
uint8_t;
154580
154581enum class OutputStream :
uint8_t;
154582
154583enum class ParseInfoType :
uint8_t;
154584
154585enum class ParserExtensionResultType :
uint8_t;
154586
154588
154590
154591enum class PendingExecutionResult :
uint8_t;
154592
154593enum class PhysicalOperatorType :
uint8_t;
154594
154595enum class PhysicalTableScanExecutionStrategy :
uint8_t;
154596
154598
154599enum class PragmaType :
uint8_t;
154600
154601enum class PreparedParamType :
uint8_t;
154602
154603enum class PreparedStatementMode :
uint8_t;
154604
154605enum class PreserveOrderType :
uint8_t;
154606
154607enum class ProfilerPrintFormat :
uint8_t;
154608
154609enum class ProfilingCoverage :
uint8_t;
154610
154611enum class ProfilingParameterNames :
uint8_t;
154612
154613enum class PushdownExtractSupport :
uint8_t;
154614
154615enum class QuantileSerializationType :
uint8_t;
154616
154617enum class QueryNodeType :
uint8_t;
154618
154619enum class QueryResultMemoryType :
uint8_t;
154620
154621enum class QueryResultOutputType :
uint8_t;
154622
154623enum class QueryResultType :
uint8_t;
154624
154626
154627enum class RelationType :
uint8_t;
154628
154629enum class RenderMode :
uint8_t;
154630
154631enum class RequestType :
uint8_t;
154632
154633enum class ResultModifierType :
uint8_t;
154634
154635enum class SampleMethod :
uint8_t;
154636
154637enum class SampleType :
uint8_t;
154638
154639enum class SamplingState :
uint8_t;
154640
154641enum class ScanType :
uint8_t;
154642
154644
154646
154648
154649enum class SequenceInfo :
uint8_t;
154650
154651enum class SetOperationType :
uint8_t;
154652
154653enum class SetScope :
uint8_t;
154654
154655enum class SetType :
uint8_t;
154656
154658
154659enum class ShowType :
uint8_t;
154660
154662
154663enum class SinkCombineResultType :
uint8_t;
154664
154666
154668
154670
154672
154674
154675enum class StarExpressionType :
uint8_t;
154676
154677enum class StatementReturnType :
uint8_t;
154678
154679enum class StatementType :
uint8_t;
154680
154681enum class StatisticsType :
uint8_t;
154682
154683enum class StatsInfo :
uint8_t;
154684
154685enum class StorageBlockPrefetch :
uint8_t;
154686
154687enum class StorageIndexType :
uint8_t;
154688
154689enum class StrTimeSpecifier :
uint8_t;
154690
154691enum class StreamExecutionResult :
uint8_t;
154692
154693enum class SubqueryType :
uint8_t;
154694
154695enum class TableColumnType :
uint8_t;
154696
154697enum class TableFilterType :
uint8_t;
154698
154700
154701enum class TableReferenceType :
uint8_t;
154702
154703enum class TaskExecutionMode :
uint8_t;
154704
154705enum class TaskExecutionResult :
uint8_t;
154706
154707enum class TemporaryBufferSize :
uint64_t;
154708
154709enum class TemporaryCompressionLevel : int;
154710
154711enum class ThreadPinMode :
uint8_t;
154712
154713enum class TimestampCastResult :
uint8_t;
154714
154715enum class TransactionInvalidationPolicy :
uint8_t;
154716
154717enum class TransactionModifierType :
uint8_t;
154718
154719enum class TransactionType :
uint8_t;
154720
154721enum class TupleDataNestednessType :
uint8_t;
154722
154724
154725enum class TupleDataValidityType :
uint8_t;
154726
154728
154729enum class UnionInvalidReason :
uint8_t;
154730
154731enum class VariantChildLookupMode :
uint8_t;
154732
154733enum class VariantLogicalType :
uint8_t;
154734
154736
154737enum class VariantValueType :
uint8_t;
154738
154739enum class VectorAuxiliaryDataType :
uint8_t;
154740
154741enum class VectorBufferType :
uint8_t;
154742
154743enum class VectorType :
uint8_t;
154744
154745enum class VerificationType :
uint8_t;
154746
154747enum class VerifyExistenceType :
uint8_t;
154748
154749enum class VertexType :
uint8_t;
154750
154751enum class WALType :
uint8_t;
154752
154754
154755enum class WindowBoundary :
uint8_t;
154756
154758
154759enum class WindowMergeSortStage :
uint8_t;
154760
154761
154762template<>
154763const char* EnumUtil::ToChars<ARTConflictType>(ARTConflictType value);
154764
154765template<>
154766const char* EnumUtil::ToChars<ARTHandlingResult>(ARTHandlingResult value);
154767
154768template<>
154769const char* EnumUtil::ToChars<ARTScanHandling>(ARTScanHandling value);
154770
154771template<>
154772const char* EnumUtil::ToChars<ARTScanResult>(ARTScanResult value);
154773
154774template<>
154775const char* EnumUtil::ToChars<AccessMode>(AccessMode value);
154776
154777template<>
154778const char* EnumUtil::ToChars<AggregateCombineType>(AggregateCombineType value);
154779
154780template<>
154781const char* EnumUtil::ToChars<AggregateDistinctDependent>(AggregateDistinctDependent value);
154782
154783template<>
154784const char* EnumUtil::ToChars<AggregateHandling>(AggregateHandling value);
154785
154786template<>
154787const char* EnumUtil::ToChars<AggregateOrderDependent>(AggregateOrderDependent value);
154788
154789template<>
154790const char* EnumUtil::ToChars<AggregateType>(AggregateType value);
154791
154792template<>
154793const char* EnumUtil::ToChars<AllowParserOverride>(AllowParserOverride value);
154794
154795template<>
154796const char* EnumUtil::ToChars<AlterDatabaseType>(AlterDatabaseType value);
154797
154798template<>
154799const char* EnumUtil::ToChars<AlterForeignKeyType>(AlterForeignKeyType value);
154800
154801template<>
154802const char* EnumUtil::ToChars<AlterScalarFunctionType>(AlterScalarFunctionType value);
154803
154804template<>
154805const char* EnumUtil::ToChars<AlterTableFunctionType>(AlterTableFunctionType value);
154806
154807template<>
154808const char* EnumUtil::ToChars<AlterTableType>(AlterTableType value);
154809
154810template<>
154811const char* EnumUtil::ToChars<AlterType>(AlterType value);
154812
154813template<>
154814const char* EnumUtil::ToChars<AlterViewType>(AlterViewType value);
154815
154816template<>
154817const char* EnumUtil::ToChars<AppenderType>(AppenderType value);
154818
154819template<>
154820const char* EnumUtil::ToChars<ArrowArrayPhysicalType>(ArrowArrayPhysicalType value);
154821
154822template<>
154823const char* EnumUtil::ToChars<ArrowDateTimeType>(ArrowDateTimeType value);
154824
154825template<>
154826const char* EnumUtil::ToChars<ArrowFormatVersion>(ArrowFormatVersion value);
154827
154828template<>
154829const char* EnumUtil::ToChars<ArrowOffsetSize>(ArrowOffsetSize value);
154830
154831template<>
154832const char* EnumUtil::ToChars<ArrowTypeInfoType>(ArrowTypeInfoType value);
154833
154834template<>
154835const char* EnumUtil::ToChars<ArrowVariableSizeType>(ArrowVariableSizeType value);
154836
154837template<>
154838const char* EnumUtil::ToChars<AsyncResultType>(AsyncResultType value);
154839
154840template<>
154841const char* EnumUtil::ToChars<AsyncResultsExecutionMode>(AsyncResultsExecutionMode value);
154842
154843template<>
154844const char* EnumUtil::ToChars<BaseColumnPrunerMode>(BaseColumnPrunerMode value);
154845
154846template<>
154847const char* EnumUtil::ToChars<BinderType>(BinderType value);
154848
154849template<>
154850const char* EnumUtil::ToChars<BindingMode>(BindingMode value);
154851
154852template<>
154853const char* EnumUtil::ToChars<BitpackingMode>(BitpackingMode value);
154854
154855template<>
154856const char* EnumUtil::ToChars<BlockIteratorStateType>(BlockIteratorStateType value);
154857
154858template<>
154859const char* EnumUtil::ToChars<BlockState>(BlockState value);
154860
154861template<>
154862const char* EnumUtil::ToChars<BufferedIndexReplay>(BufferedIndexReplay value);
154863
154864template<>
154865const char* EnumUtil::ToChars<CAPIResultSetType>(CAPIResultSetType value);
154866
154867template<>
154868const char* EnumUtil::ToChars<CSVState>(CSVState value);
154869
154870template<>
154871const char* EnumUtil::ToChars<CTEMaterialize>(CTEMaterialize value);
154872
154873template<>
154874const char* EnumUtil::ToChars<CacheValidationMode>(CacheValidationMode value);
154875
154876template<>
154877const char* EnumUtil::ToChars<CachingMode>(CachingMode value);
154878
154879template<>
154880const char* EnumUtil::ToChars<CatalogLookupBehavior>(CatalogLookupBehavior value);
154881
154882template<>
154883const char* EnumUtil::ToChars<CatalogType>(CatalogType value);
154884
154885template<>
154886const char* EnumUtil::ToChars<CheckpointAbort>(CheckpointAbort value);
154887
154888template<>
154889const char* EnumUtil::ToChars<ChunkInfoType>(ChunkInfoType value);
154890
154891template<>
154892const char* EnumUtil::ToChars<ColumnDataAllocatorType>(ColumnDataAllocatorType value);
154893
154894template<>
154895const char* EnumUtil::ToChars<ColumnDataScanProperties>(ColumnDataScanProperties value);
154896
154897template<>
154898const char* EnumUtil::ToChars<ColumnIndexType>(ColumnIndexType value);
154899
154900template<>
154901const char* EnumUtil::ToChars<ColumnSegmentType>(ColumnSegmentType value);
154902
154903template<>
154904const char* EnumUtil::ToChars<CompressedMaterializationDirection>(CompressedMaterializationDirection value);
154905
154906template<>
154907const char* EnumUtil::ToChars<CompressionType>(CompressionType value);
154908
154909template<>
154910const char* EnumUtil::ToChars<CompressionValidity>(CompressionValidity value);
154911
154912template<>
154913const char* EnumUtil::ToChars<ConflictManagerMode>(ConflictManagerMode value);
154914
154915template<>
154916const char* EnumUtil::ToChars<ConstraintType>(ConstraintType value);
154917
154918template<>
154919const char* EnumUtil::ToChars<CoordinateReferenceSystemType>(CoordinateReferenceSystemType value);
154920
154921template<>
154922const char* EnumUtil::ToChars<CopyFunctionReturnType>(CopyFunctionReturnType value);
154923
154924template<>
154925const char* EnumUtil::ToChars<CopyOverwriteMode>(CopyOverwriteMode value);
154926
154927template<>
154928const char* EnumUtil::ToChars<CopyToType>(CopyToType value);
154929
154930template<>
154931const char* EnumUtil::ToChars<DataFileType>(DataFileType value);
154932
154933template<>
154934const char* EnumUtil::ToChars<DateCastResult>(DateCastResult value);
154935
154936template<>
154937const char* EnumUtil::ToChars<DatePartSpecifier>(DatePartSpecifier value);
154938
154939template<>
154940const char* EnumUtil::ToChars<DebugInitialize>(DebugInitialize value);
154941
154942template<>
154943const char* EnumUtil::ToChars<DebugVectorVerification>(DebugVectorVerification value);
154944
154945template<>
154946const char* EnumUtil::ToChars<DecimalBitWidth>(DecimalBitWidth value);
154947
154948template<>
154949const char* EnumUtil::ToChars<DefaultOrderByNullType>(DefaultOrderByNullType value);
154950
154951template<>
154952const char* EnumUtil::ToChars<DependencyEntryType>(DependencyEntryType value);
154953
154954template<>
154955const char* EnumUtil::ToChars<DeprecatedIndexType>(DeprecatedIndexType value);
154956
154957template<>
154958const char* EnumUtil::ToChars<DeprecatedUsingKeySyntax>(DeprecatedUsingKeySyntax value);
154959
154960template<>
154961const char* EnumUtil::ToChars<DestroyBufferUpon>(DestroyBufferUpon value);
154962
154963template<>
154964const char* EnumUtil::ToChars<DistinctType>(DistinctType value);
154965
154966template<>
154967const char* EnumUtil::ToChars<ErrorType>(ErrorType value);
154968
154969template<>
154970const char* EnumUtil::ToChars<ExceptionFormatValueType>(ExceptionFormatValueType value);
154971
154972template<>
154973const char* EnumUtil::ToChars<ExceptionType>(ExceptionType value);
154974
154975template<>
154976const char* EnumUtil::ToChars<ExplainFormat>(ExplainFormat value);
154977
154978template<>
154979const char* EnumUtil::ToChars<ExplainOutputType>(ExplainOutputType value);
154980
154981template<>
154982const char* EnumUtil::ToChars<ExplainType>(ExplainType value);
154983
154984template<>
154985const char* EnumUtil::ToChars<ExponentType>(ExponentType value);
154986
154987template<>
154988const char* EnumUtil::ToChars<ExpressionClass>(ExpressionClass value);
154989
154990template<>
154991const char* EnumUtil::ToChars<ExpressionType>(ExpressionType value);
154992
154993template<>
154994const char* EnumUtil::ToChars<ExtensionABIType>(ExtensionABIType value);
154995
154996template<>
154997const char* EnumUtil::ToChars<ExtensionInstallMode>(ExtensionInstallMode value);
154998
154999template<>
155000const char* EnumUtil::ToChars<ExtensionLoadResult>(ExtensionLoadResult value);
155001
155002template<>
155003const char* EnumUtil::ToChars<ExtensionUpdateResultTag>(ExtensionUpdateResultTag value);
155004
155005template<>
155006const char* EnumUtil::ToChars<ExtraDropInfoType>(ExtraDropInfoType value);
155007
155008template<>
155009const char* EnumUtil::ToChars<ExtraPersistentColumnDataType>(ExtraPersistentColumnDataType value);
155010
155011template<>
155012const char* EnumUtil::ToChars<ExtraTypeInfoType>(ExtraTypeInfoType value);
155013
155014template<>
155015const char* EnumUtil::ToChars<FileBufferType>(FileBufferType value);
155016
155017template<>
155018const char* EnumUtil::ToChars<FileCompressionType>(FileCompressionType value);
155019
155020template<>
155021const char* EnumUtil::ToChars<FileExpandResult>(FileExpandResult value);
155022
155023template<>
155024const char* EnumUtil::ToChars<FileGlobOptions>(FileGlobOptions value);
155025
155026template<>
155027const char* EnumUtil::ToChars<FileLockType>(FileLockType value);
155028
155029template<>
155030const char* EnumUtil::ToChars<FileNameSegmentType>(FileNameSegmentType value);
155031
155032template<>
155033const char* EnumUtil::ToChars<FilterPropagateResult>(FilterPropagateResult value);
155034
155035template<>
155036const char* EnumUtil::ToChars<ForeignKeyType>(ForeignKeyType value);
155037
155038template<>
155039const char* EnumUtil::ToChars<FunctionCollationHandling>(FunctionCollationHandling value);
155040
155041template<>
155042const char* EnumUtil::ToChars<FunctionErrors>(FunctionErrors value);
155043
155044template<>
155045const char* EnumUtil::ToChars<FunctionNullHandling>(FunctionNullHandling value);
155046
155047template<>
155048const char* EnumUtil::ToChars<FunctionStability>(FunctionStability value);
155049
155050template<>
155051const char* EnumUtil::ToChars<GateStatus>(GateStatus value);
155052
155053template<>
155054const char* EnumUtil::ToChars<GeometryStorageType>(GeometryStorageType value);
155055
155056template<>
155057const char* EnumUtil::ToChars<GeometryType>(GeometryType value);
155058
155059template<>
155060const char* EnumUtil::ToChars<HLLStorageType>(HLLStorageType value);
155061
155062template<>
155063const char* EnumUtil::ToChars<HTTPStatusCode>(HTTPStatusCode value);
155064
155065template<>
155066const char* EnumUtil::ToChars<IndexAppendMode>(IndexAppendMode value);
155067
155068template<>
155069const char* EnumUtil::ToChars<IndexBindState>(IndexBindState value);
155070
155071template<>
155072const char* EnumUtil::ToChars<IndexConstraintType>(IndexConstraintType value);
155073
155074template<>
155075const char* EnumUtil::ToChars<InsertColumnOrder>(InsertColumnOrder value);
155076
155077template<>
155078const char* EnumUtil::ToChars<InterruptMode>(InterruptMode value);
155079
155080template<>
155081const char* EnumUtil::ToChars<JoinRefType>(JoinRefType value);
155082
155083template<>
155084const char* EnumUtil::ToChars<JoinType>(JoinType value);
155085
155086template<>
155087const char* EnumUtil::ToChars<KeywordCategory>(KeywordCategory value);
155088
155089template<>
155090const char* EnumUtil::ToChars<LambdaSyntax>(LambdaSyntax value);
155091
155092template<>
155093const char* EnumUtil::ToChars<LambdaSyntaxType>(LambdaSyntaxType value);
155094
155095template<>
155096const char* EnumUtil::ToChars<LimitNodeType>(LimitNodeType value);
155097
155098template<>
155099const char* EnumUtil::ToChars<LoadType>(LoadType value);
155100
155101template<>
155102const char* EnumUtil::ToChars<LogContextScope>(LogContextScope value);
155103
155104template<>
155105const char* EnumUtil::ToChars<LogLevel>(LogLevel value);
155106
155107template<>
155108const char* EnumUtil::ToChars<LogMode>(LogMode value);
155109
155110template<>
155111const char* EnumUtil::ToChars<LoggingTargetTable>(LoggingTargetTable value);
155112
155113template<>
155114const char* EnumUtil::ToChars<LogicalOperatorType>(LogicalOperatorType value);
155115
155116template<>
155117const char* EnumUtil::ToChars<LogicalTypeId>(LogicalTypeId value);
155118
155119template<>
155120const char* EnumUtil::ToChars<LookupResultType>(LookupResultType value);
155121
155122template<>
155123const char* EnumUtil::ToChars<MacroType>(MacroType value);
155124
155125template<>
155126const char* EnumUtil::ToChars<MapInvalidReason>(MapInvalidReason value);
155127
155128template<>
155129const char* EnumUtil::ToChars<MemoryTag>(MemoryTag value);
155130
155131template<>
155132const char* EnumUtil::ToChars<MergeActionCondition>(MergeActionCondition value);
155133
155134template<>
155135const char* EnumUtil::ToChars<MergeActionType>(MergeActionType value);
155136
155137template<>
155138const char* EnumUtil::ToChars<MetaPipelineType>(MetaPipelineType value);
155139
155140template<>
155141const char* EnumUtil::ToChars<MetricGroup>(MetricGroup value);
155142
155143template<>
155144const char* EnumUtil::ToChars<MetricType>(MetricType value);
155145
155146template<>
155147const char* EnumUtil::ToChars<MultiFileColumnMappingMode>(MultiFileColumnMappingMode value);
155148
155149template<>
155150const char* EnumUtil::ToChars<MultiFileFileState>(MultiFileFileState value);
155151
155152template<>
155153const char* EnumUtil::ToChars<NType>(NType value);
155154
155155template<>
155156const char* EnumUtil::ToChars<NewLineIdentifier>(NewLineIdentifier value);
155157
155158template<>
155159const char* EnumUtil::ToChars<OnConflictAction>(OnConflictAction value);
155160
155161template<>
155162const char* EnumUtil::ToChars<OnCreateConflict>(OnCreateConflict value);
155163
155164template<>
155165const char* EnumUtil::ToChars<OnEntryNotFound>(OnEntryNotFound value);
155166
155167template<>
155168const char* EnumUtil::ToChars<OperatorCachingMode>(OperatorCachingMode value);
155169
155170template<>
155171const char* EnumUtil::ToChars<OperatorFinalResultType>(OperatorFinalResultType value);
155172
155173template<>
155174const char* EnumUtil::ToChars<OperatorFinalizeResultType>(OperatorFinalizeResultType value);
155175
155176template<>
155177const char* EnumUtil::ToChars<OperatorResultType>(OperatorResultType value);
155178
155179template<>
155180const char* EnumUtil::ToChars<OptimizerType>(OptimizerType value);
155181
155182template<>
155183const char* EnumUtil::ToChars<OrderByColumnType>(OrderByColumnType value);
155184
155185template<>
155186const char* EnumUtil::ToChars<OrderByNullType>(OrderByNullType value);
155187
155188template<>
155189const char* EnumUtil::ToChars<OrderByStatistics>(OrderByStatistics value);
155190
155191template<>
155192const char* EnumUtil::ToChars<OrderPreservationType>(OrderPreservationType value);
155193
155194template<>
155195const char* EnumUtil::ToChars<OrderType>(OrderType value);
155196
155197template<>
155198const char* EnumUtil::ToChars<OrdinalityType>(OrdinalityType value);
155199
155200template<>
155201const char* EnumUtil::ToChars<OutputStream>(OutputStream value);
155202
155203template<>
155204const char* EnumUtil::ToChars<ParseInfoType>(ParseInfoType value);
155205
155206template<>
155207const char* EnumUtil::ToChars<ParserExtensionResultType>(ParserExtensionResultType value);
155208
155209template<>
155210const char* EnumUtil::ToChars<PartitionedColumnDataType>(PartitionedColumnDataType value);
155211
155212template<>
155213const char* EnumUtil::ToChars<PartitionedTupleDataType>(PartitionedTupleDataType value);
155214
155215template<>
155216const char* EnumUtil::ToChars<PendingExecutionResult>(PendingExecutionResult value);
155217
155218template<>
155219const char* EnumUtil::ToChars<PhysicalOperatorType>(PhysicalOperatorType value);
155220
155221template<>
155222const char* EnumUtil::ToChars<PhysicalTableScanExecutionStrategy>(PhysicalTableScanExecutionStrategy value);
155223
155224template<>
155225const char* EnumUtil::ToChars<PhysicalType>(PhysicalType value);
155226
155227template<>
155228const char* EnumUtil::ToChars<PragmaType>(PragmaType value);
155229
155230template<>
155231const char* EnumUtil::ToChars<PreparedParamType>(PreparedParamType value);
155232
155233template<>
155234const char* EnumUtil::ToChars<PreparedStatementMode>(PreparedStatementMode value);
155235
155236template<>
155237const char* EnumUtil::ToChars<PreserveOrderType>(PreserveOrderType value);
155238
155239template<>
155240const char* EnumUtil::ToChars<ProfilerPrintFormat>(ProfilerPrintFormat value);
155241
155242template<>
155243const char* EnumUtil::ToChars<ProfilingCoverage>(ProfilingCoverage value);
155244
155245template<>
155246const char* EnumUtil::ToChars<ProfilingParameterNames>(ProfilingParameterNames value);
155247
155248template<>
155249const char* EnumUtil::ToChars<PushdownExtractSupport>(PushdownExtractSupport value);
155250
155251template<>
155252const char* EnumUtil::ToChars<QuantileSerializationType>(QuantileSerializationType value);
155253
155254template<>
155255const char* EnumUtil::ToChars<QueryNodeType>(QueryNodeType value);
155256
155257template<>
155258const char* EnumUtil::ToChars<QueryResultMemoryType>(QueryResultMemoryType value);
155259
155260template<>
155261const char* EnumUtil::ToChars<QueryResultOutputType>(QueryResultOutputType value);
155262
155263template<>
155264const char* EnumUtil::ToChars<QueryResultType>(QueryResultType value);
155265
155266template<>
155267const char* EnumUtil::ToChars<RecoveryMode>(RecoveryMode value);
155268
155269template<>
155270const char* EnumUtil::ToChars<RelationType>(RelationType value);
155271
155272template<>
155273const char* EnumUtil::ToChars<RenderMode>(RenderMode value);
155274
155275template<>
155276const char* EnumUtil::ToChars<RequestType>(RequestType value);
155277
155278template<>
155279const char* EnumUtil::ToChars<ResultModifierType>(ResultModifierType value);
155280
155281template<>
155282const char* EnumUtil::ToChars<SampleMethod>(SampleMethod value);
155283
155284template<>
155285const char* EnumUtil::ToChars<SampleType>(SampleType value);
155286
155287template<>
155288const char* EnumUtil::ToChars<SamplingState>(SamplingState value);
155289
155290template<>
155291const char* EnumUtil::ToChars<ScanType>(ScanType value);
155292
155293template<>
155294const char* EnumUtil::ToChars<SecretDisplayType>(SecretDisplayType value);
155295
155296template<>
155297const char* EnumUtil::ToChars<SecretPersistType>(SecretPersistType value);
155298
155299template<>
155300const char* EnumUtil::ToChars<SecretSerializationType>(SecretSerializationType value);
155301
155302template<>
155303const char* EnumUtil::ToChars<SequenceInfo>(SequenceInfo value);
155304
155305template<>
155306const char* EnumUtil::ToChars<SetOperationType>(SetOperationType value);
155307
155308template<>
155309const char* EnumUtil::ToChars<SetScope>(SetScope value);
155310
155311template<>
155312const char* EnumUtil::ToChars<SetType>(SetType value);
155313
155314template<>
155315const char* EnumUtil::ToChars<SettingScope>(SettingScope value);
155316
155317template<>
155318const char* EnumUtil::ToChars<ShowType>(ShowType value);
155319
155320template<>
155321const char* EnumUtil::ToChars<SimplifiedTokenType>(SimplifiedTokenType value);
155322
155323template<>
155324const char* EnumUtil::ToChars<SinkCombineResultType>(SinkCombineResultType value);
155325
155326template<>
155327const char* EnumUtil::ToChars<SinkFinalizeType>(SinkFinalizeType value);
155328
155329template<>
155330const char* EnumUtil::ToChars<SinkNextBatchType>(SinkNextBatchType value);
155331
155332template<>
155333const char* EnumUtil::ToChars<SinkResultType>(SinkResultType value);
155334
155335template<>
155336const char* EnumUtil::ToChars<SortKeyType>(SortKeyType value);
155337
155338template<>
155339const char* EnumUtil::ToChars<SourceResultType>(SourceResultType value);
155340
155341template<>
155342const char* EnumUtil::ToChars<StarExpressionType>(StarExpressionType value);
155343
155344template<>
155345const char* EnumUtil::ToChars<StatementReturnType>(StatementReturnType value);
155346
155347template<>
155348const char* EnumUtil::ToChars<StatementType>(StatementType value);
155349
155350template<>
155351const char* EnumUtil::ToChars<StatisticsType>(StatisticsType value);
155352
155353template<>
155354const char* EnumUtil::ToChars<StatsInfo>(StatsInfo value);
155355
155356template<>
155357const char* EnumUtil::ToChars<StorageBlockPrefetch>(StorageBlockPrefetch value);
155358
155359template<>
155360const char* EnumUtil::ToChars<StorageIndexType>(StorageIndexType value);
155361
155362template<>
155363const char* EnumUtil::ToChars<StrTimeSpecifier>(StrTimeSpecifier value);
155364
155365template<>
155366const char* EnumUtil::ToChars<StreamExecutionResult>(StreamExecutionResult value);
155367
155368template<>
155369const char* EnumUtil::ToChars<SubqueryType>(SubqueryType value);
155370
155371template<>
155372const char* EnumUtil::ToChars<TableColumnType>(TableColumnType value);
155373
155374template<>
155375const char* EnumUtil::ToChars<TableFilterType>(TableFilterType value);
155376
155377template<>
155378const char* EnumUtil::ToChars<TablePartitionInfo>(TablePartitionInfo value);
155379
155380template<>
155381const char* EnumUtil::ToChars<TableReferenceType>(TableReferenceType value);
155382
155383template<>
155384const char* EnumUtil::ToChars<TaskExecutionMode>(TaskExecutionMode value);
155385
155386template<>
155387const char* EnumUtil::ToChars<TaskExecutionResult>(TaskExecutionResult value);
155388
155389template<>
155390const char* EnumUtil::ToChars<TemporaryBufferSize>(TemporaryBufferSize value);
155391
155392template<>
155393const char* EnumUtil::ToChars<TemporaryCompressionLevel>(TemporaryCompressionLevel value);
155394
155395template<>
155396const char* EnumUtil::ToChars<ThreadPinMode>(ThreadPinMode value);
155397
155398template<>
155399const char* EnumUtil::ToChars<TimestampCastResult>(TimestampCastResult value);
155400
155401template<>
155402const char* EnumUtil::ToChars<TransactionInvalidationPolicy>(TransactionInvalidationPolicy value);
155403
155404template<>
155405const char* EnumUtil::ToChars<TransactionModifierType>(TransactionModifierType value);
155406
155407template<>
155408const char* EnumUtil::ToChars<TransactionType>(TransactionType value);
155409
155410template<>
155411const char* EnumUtil::ToChars<TupleDataNestednessType>(TupleDataNestednessType value);
155412
155413template<>
155414const char* EnumUtil::ToChars<TupleDataPinProperties>(TupleDataPinProperties value);
155415
155416template<>
155417const char* EnumUtil::ToChars<TupleDataValidityType>(TupleDataValidityType value);
155418
155419template<>
155420const char* EnumUtil::ToChars<UndoFlags>(UndoFlags value);
155421
155422template<>
155423const char* EnumUtil::ToChars<UnionInvalidReason>(UnionInvalidReason value);
155424
155425template<>
155426const char* EnumUtil::ToChars<VariantChildLookupMode>(VariantChildLookupMode value);
155427
155428template<>
155429const char* EnumUtil::ToChars<VariantLogicalType>(VariantLogicalType value);
155430
155431template<>
155432const char* EnumUtil::ToChars<VariantStatsShreddingState>(VariantStatsShreddingState value);
155433
155434template<>
155435const char* EnumUtil::ToChars<VariantValueType>(VariantValueType value);
155436
155437template<>
155438const char* EnumUtil::ToChars<VectorAuxiliaryDataType>(VectorAuxiliaryDataType value);
155439
155440template<>
155441const char* EnumUtil::ToChars<VectorBufferType>(VectorBufferType value);
155442
155443template<>
155444const char* EnumUtil::ToChars<VectorType>(VectorType value);
155445
155446template<>
155447const char* EnumUtil::ToChars<VerificationType>(VerificationType value);
155448
155449template<>
155450const char* EnumUtil::ToChars<VerifyExistenceType>(VerifyExistenceType value);
155451
155452template<>
155453const char* EnumUtil::ToChars<VertexType>(VertexType value);
155454
155455template<>
155456const char* EnumUtil::ToChars<WALType>(WALType value);
155457
155458template<>
155459const char* EnumUtil::ToChars<WindowAggregationMode>(WindowAggregationMode value);
155460
155461template<>
155462const char* EnumUtil::ToChars<WindowBoundary>(WindowBoundary value);
155463
155464template<>
155465const char* EnumUtil::ToChars<WindowExcludeMode>(WindowExcludeMode value);
155466
155467template<>
155468const char* EnumUtil::ToChars<WindowMergeSortStage>(WindowMergeSortStage value);
155469
155470
155471template<>
155472ARTConflictType EnumUtil::FromString<ARTConflictType>(const char *value);
155473
155474template<>
155475ARTHandlingResult EnumUtil::FromString<ARTHandlingResult>(const char *value);
155476
155477template<>
155478ARTScanHandling EnumUtil::FromString<ARTScanHandling>(const char *value);
155479
155480template<>
155481ARTScanResult EnumUtil::FromString<ARTScanResult>(
const char *value);
155482
155483template<>
155484AccessMode EnumUtil::FromString<AccessMode>(const char *value);
155485
155486template<>
155488
155489template<>
155491
155492template<>
155493AggregateHandling EnumUtil::FromString<AggregateHandling>(const char *value);
155494
155495template<>
155497
155498template<>
155499AggregateType EnumUtil::FromString<AggregateType>(const char *value);
155500
155501template<>
155502AllowParserOverride EnumUtil::FromString<AllowParserOverride>(const char *value);
155503
155504template<>
155505AlterDatabaseType EnumUtil::FromString<AlterDatabaseType>(const char *value);
155506
155507template<>
155508AlterForeignKeyType EnumUtil::FromString<AlterForeignKeyType>(const char *value);
155509
155510template<>
155511AlterScalarFunctionType EnumUtil::FromString<AlterScalarFunctionType>(const char *value);
155512
155513template<>
155514AlterTableFunctionType EnumUtil::FromString<AlterTableFunctionType>(const char *value);
155515
155516template<>
155517AlterTableType EnumUtil::FromString<AlterTableType>(const char *value);
155518
155519template<>
155520AlterType EnumUtil::FromString<AlterType>(const char *value);
155521
155522template<>
155523AlterViewType EnumUtil::FromString<AlterViewType>(const char *value);
155524
155525template<>
155526AppenderType EnumUtil::FromString<AppenderType>(const char *value);
155527
155528template<>
155529ArrowArrayPhysicalType EnumUtil::FromString<ArrowArrayPhysicalType>(const char *value);
155530
155531template<>
155532ArrowDateTimeType EnumUtil::FromString<ArrowDateTimeType>(const char *value);
155533
155534template<>
155536
155537template<>
155538ArrowOffsetSize EnumUtil::FromString<ArrowOffsetSize>(const char *value);
155539
155540template<>
155541ArrowTypeInfoType EnumUtil::FromString<ArrowTypeInfoType>(const char *value);
155542
155543template<>
155544ArrowVariableSizeType EnumUtil::FromString<ArrowVariableSizeType>(const char *value);
155545
155546template<>
155547AsyncResultType EnumUtil::FromString<AsyncResultType>(
const char *value);
155548
155549template<>
155550AsyncResultsExecutionMode EnumUtil::FromString<AsyncResultsExecutionMode>(const char *value);
155551
155552template<>
155554
155555template<>
155556BinderType EnumUtil::FromString<BinderType>(const char *value);
155557
155558template<>
155559BindingMode EnumUtil::FromString<BindingMode>(const char *value);
155560
155561template<>
155562BitpackingMode EnumUtil::FromString<BitpackingMode>(const char *value);
155563
155564template<>
155566
155567template<>
155568BlockState EnumUtil::FromString<BlockState>(const char *value);
155569
155570template<>
155571BufferedIndexReplay EnumUtil::FromString<BufferedIndexReplay>(const char *value);
155572
155573template<>
155574CAPIResultSetType EnumUtil::FromString<CAPIResultSetType>(const char *value);
155575
155576template<>
155577CSVState EnumUtil::FromString<CSVState>(
const char *value);
155578
155579template<>
155580CTEMaterialize EnumUtil::FromString<CTEMaterialize>(const char *value);
155581
155582template<>
155583CacheValidationMode EnumUtil::FromString<CacheValidationMode>(const char *value);
155584
155585template<>
155586CachingMode EnumUtil::FromString<CachingMode>(
const char *value);
155587
155588template<>
155590
155591template<>
155592CatalogType EnumUtil::FromString<CatalogType>(const char *value);
155593
155594template<>
155595CheckpointAbort EnumUtil::FromString<CheckpointAbort>(const char *value);
155596
155597template<>
155598ChunkInfoType EnumUtil::FromString<ChunkInfoType>(const char *value);
155599
155600template<>
155602
155603template<>
155605
155606template<>
155607ColumnIndexType EnumUtil::FromString<ColumnIndexType>(
const char *value);
155608
155609template<>
155610ColumnSegmentType EnumUtil::FromString<ColumnSegmentType>(const char *value);
155611
155612template<>
155614
155615template<>
155616CompressionType EnumUtil::FromString<CompressionType>(const char *value);
155617
155618template<>
155619CompressionValidity EnumUtil::FromString<CompressionValidity>(const char *value);
155620
155621template<>
155622ConflictManagerMode EnumUtil::FromString<ConflictManagerMode>(const char *value);
155623
155624template<>
155625ConstraintType EnumUtil::FromString<ConstraintType>(const char *value);
155626
155627template<>
155629
155630template<>
155631CopyFunctionReturnType EnumUtil::FromString<CopyFunctionReturnType>(const char *value);
155632
155633template<>
155634CopyOverwriteMode EnumUtil::FromString<CopyOverwriteMode>(const char *value);
155635
155636template<>
155637CopyToType EnumUtil::FromString<CopyToType>(const char *value);
155638
155639template<>
155640DataFileType EnumUtil::FromString<DataFileType>(const char *value);
155641
155642template<>
155643DateCastResult EnumUtil::FromString<DateCastResult>(const char *value);
155644
155645template<>
155646DatePartSpecifier EnumUtil::FromString<DatePartSpecifier>(const char *value);
155647
155648template<>
155649DebugInitialize EnumUtil::FromString<DebugInitialize>(const char *value);
155650
155651template<>
155652DebugVectorVerification EnumUtil::FromString<DebugVectorVerification>(const char *value);
155653
155654template<>
155655DecimalBitWidth EnumUtil::FromString<DecimalBitWidth>(const char *value);
155656
155657template<>
155658DefaultOrderByNullType EnumUtil::FromString<DefaultOrderByNullType>(const char *value);
155659
155660template<>
155662
155663template<>
155664DeprecatedIndexType EnumUtil::FromString<DeprecatedIndexType>(const char *value);
155665
155666template<>
155667DeprecatedUsingKeySyntax EnumUtil::FromString<DeprecatedUsingKeySyntax>(const char *value);
155668
155669template<>
155671
155672template<>
155673DistinctType EnumUtil::FromString<DistinctType>(const char *value);
155674
155675template<>
155676ErrorType EnumUtil::FromString<ErrorType>(const char *value);
155677
155678template<>
155679ExceptionFormatValueType EnumUtil::FromString<ExceptionFormatValueType>(const char *value);
155680
155681template<>
155682ExceptionType EnumUtil::FromString<ExceptionType>(const char *value);
155683
155684template<>
155685ExplainFormat EnumUtil::FromString<ExplainFormat>(const char *value);
155686
155687template<>
155688ExplainOutputType EnumUtil::FromString<ExplainOutputType>(const char *value);
155689
155690template<>
155691ExplainType EnumUtil::FromString<ExplainType>(const char *value);
155692
155693template<>
155694ExponentType EnumUtil::FromString<ExponentType>(const char *value);
155695
155696template<>
155697ExpressionClass EnumUtil::FromString<ExpressionClass>(const char *value);
155698
155699template<>
155700ExpressionType EnumUtil::FromString<ExpressionType>(const char *value);
155701
155702template<>
155703ExtensionABIType EnumUtil::FromString<ExtensionABIType>(
const char *value);
155704
155705template<>
155707
155708template<>
155709ExtensionLoadResult EnumUtil::FromString<ExtensionLoadResult>(const char *value);
155710
155711template<>
155712ExtensionUpdateResultTag EnumUtil::FromString<ExtensionUpdateResultTag>(const char *value);
155713
155714template<>
155715ExtraDropInfoType EnumUtil::FromString<ExtraDropInfoType>(const char *value);
155716
155717template<>
155718ExtraPersistentColumnDataType EnumUtil::FromString<ExtraPersistentColumnDataType>(const char *value);
155719
155720template<>
155722
155723template<>
155724FileBufferType EnumUtil::FromString<FileBufferType>(const char *value);
155725
155726template<>
155727FileCompressionType EnumUtil::FromString<FileCompressionType>(const char *value);
155728
155729template<>
155730FileExpandResult EnumUtil::FromString<FileExpandResult>(const char *value);
155731
155732template<>
155733FileGlobOptions EnumUtil::FromString<FileGlobOptions>(const char *value);
155734
155735template<>
155736FileLockType EnumUtil::FromString<FileLockType>(const char *value);
155737
155738template<>
155739FileNameSegmentType EnumUtil::FromString<FileNameSegmentType>(const char *value);
155740
155741template<>
155742FilterPropagateResult EnumUtil::FromString<FilterPropagateResult>(const char *value);
155743
155744template<>
155745ForeignKeyType EnumUtil::FromString<ForeignKeyType>(const char *value);
155746
155747template<>
155749
155750template<>
155751FunctionErrors EnumUtil::FromString<FunctionErrors>(
const char *value);
155752
155753template<>
155755
155756template<>
155758
155759template<>
155760GateStatus EnumUtil::FromString<GateStatus>(const char *value);
155761
155762template<>
155763GeometryStorageType EnumUtil::FromString<GeometryStorageType>(const char *value);
155764
155765template<>
155766GeometryType EnumUtil::FromString<GeometryType>(const char *value);
155767
155768template<>
155769HLLStorageType EnumUtil::FromString<HLLStorageType>(
const char *value);
155770
155771template<>
155772HTTPStatusCode EnumUtil::FromString<HTTPStatusCode>(const char *value);
155773
155774template<>
155775IndexAppendMode EnumUtil::FromString<IndexAppendMode>(const char *value);
155776
155777template<>
155778IndexBindState EnumUtil::FromString<IndexBindState>(
const char *value);
155779
155780template<>
155781IndexConstraintType EnumUtil::FromString<IndexConstraintType>(const char *value);
155782
155783template<>
155784InsertColumnOrder EnumUtil::FromString<InsertColumnOrder>(const char *value);
155785
155786template<>
155787InterruptMode EnumUtil::FromString<InterruptMode>(
const char *value);
155788
155789template<>
155790JoinRefType EnumUtil::FromString<JoinRefType>(const char *value);
155791
155792template<>
155793JoinType EnumUtil::FromString<JoinType>(const char *value);
155794
155795template<>
155796KeywordCategory EnumUtil::FromString<KeywordCategory>(const char *value);
155797
155798template<>
155799LambdaSyntax EnumUtil::FromString<LambdaSyntax>(const char *value);
155800
155801template<>
155802LambdaSyntaxType EnumUtil::FromString<LambdaSyntaxType>(const char *value);
155803
155804template<>
155805LimitNodeType EnumUtil::FromString<LimitNodeType>(const char *value);
155806
155807template<>
155808LoadType EnumUtil::FromString<LoadType>(const char *value);
155809
155810template<>
155811LogContextScope EnumUtil::FromString<LogContextScope>(const char *value);
155812
155813template<>
155814LogLevel EnumUtil::FromString<LogLevel>(
const char *value);
155815
155816template<>
155817LogMode EnumUtil::FromString<LogMode>(const char *value);
155818
155819template<>
155821
155822template<>
155823LogicalOperatorType EnumUtil::FromString<LogicalOperatorType>(const char *value);
155824
155825template<>
155826LogicalTypeId EnumUtil::FromString<LogicalTypeId>(
const char *value);
155827
155828template<>
155829LookupResultType EnumUtil::FromString<LookupResultType>(const char *value);
155830
155831template<>
155832MacroType EnumUtil::FromString<MacroType>(const char *value);
155833
155834template<>
155835MapInvalidReason EnumUtil::FromString<MapInvalidReason>(const char *value);
155836
155837template<>
155838MemoryTag EnumUtil::FromString<MemoryTag>(const char *value);
155839
155840template<>
155841MergeActionCondition EnumUtil::FromString<MergeActionCondition>(const char *value);
155842
155843template<>
155844MergeActionType EnumUtil::FromString<MergeActionType>(const char *value);
155845
155846template<>
155847MetaPipelineType EnumUtil::FromString<MetaPipelineType>(
const char *value);
155848
155849template<>
155850MetricGroup EnumUtil::FromString<MetricGroup>(const char *value);
155851
155852template<>
155853MetricType EnumUtil::FromString<MetricType>(const char *value);
155854
155855template<>
155856MultiFileColumnMappingMode EnumUtil::FromString<MultiFileColumnMappingMode>(const char *value);
155857
155858template<>
155859MultiFileFileState EnumUtil::FromString<MultiFileFileState>(const char *value);
155860
155861template<>
155862NType EnumUtil::FromString<NType>(const char *value);
155863
155864template<>
155865NewLineIdentifier EnumUtil::FromString<NewLineIdentifier>(const char *value);
155866
155867template<>
155868OnConflictAction EnumUtil::FromString<OnConflictAction>(const char *value);
155869
155870template<>
155871OnCreateConflict EnumUtil::FromString<OnCreateConflict>(const char *value);
155872
155873template<>
155874OnEntryNotFound EnumUtil::FromString<OnEntryNotFound>(const char *value);
155875
155876template<>
155877OperatorCachingMode EnumUtil::FromString<OperatorCachingMode>(const char *value);
155878
155879template<>
155881
155882template<>
155884
155885template<>
155887
155888template<>
155889OptimizerType EnumUtil::FromString<OptimizerType>(const char *value);
155890
155891template<>
155892OrderByColumnType EnumUtil::FromString<OrderByColumnType>(const char *value);
155893
155894template<>
155895OrderByNullType EnumUtil::FromString<OrderByNullType>(const char *value);
155896
155897template<>
155898OrderByStatistics EnumUtil::FromString<OrderByStatistics>(const char *value);
155899
155900template<>
155901OrderPreservationType EnumUtil::FromString<OrderPreservationType>(const char *value);
155902
155903template<>
155904OrderType EnumUtil::FromString<OrderType>(const char *value);
155905
155906template<>
155907OrdinalityType EnumUtil::FromString<OrdinalityType>(const char *value);
155908
155909template<>
155910OutputStream EnumUtil::FromString<OutputStream>(const char *value);
155911
155912template<>
155913ParseInfoType EnumUtil::FromString<ParseInfoType>(const char *value);
155914
155915template<>
155916ParserExtensionResultType EnumUtil::FromString<ParserExtensionResultType>(const char *value);
155917
155918template<>
155920
155921template<>
155923
155924template<>
155925PendingExecutionResult EnumUtil::FromString<PendingExecutionResult>(const char *value);
155926
155927template<>
155928PhysicalOperatorType EnumUtil::FromString<PhysicalOperatorType>(const char *value);
155929
155930template<>
155931PhysicalTableScanExecutionStrategy EnumUtil::FromString<PhysicalTableScanExecutionStrategy>(const char *value);
155932
155933template<>
155934PhysicalType EnumUtil::FromString<PhysicalType>(
const char *value);
155935
155936template<>
155937PragmaType EnumUtil::FromString<PragmaType>(const char *value);
155938
155939template<>
155940PreparedParamType EnumUtil::FromString<PreparedParamType>(const char *value);
155941
155942template<>
155943PreparedStatementMode EnumUtil::FromString<PreparedStatementMode>(const char *value);
155944
155945template<>
155946PreserveOrderType EnumUtil::FromString<PreserveOrderType>(const char *value);
155947
155948template<>
155949ProfilerPrintFormat EnumUtil::FromString<ProfilerPrintFormat>(const char *value);
155950
155951template<>
155952ProfilingCoverage EnumUtil::FromString<ProfilingCoverage>(const char *value);
155953
155954template<>
155955ProfilingParameterNames EnumUtil::FromString<ProfilingParameterNames>(const char *value);
155956
155957template<>
155958PushdownExtractSupport EnumUtil::FromString<PushdownExtractSupport>(const char *value);
155959
155960template<>
155961QuantileSerializationType EnumUtil::FromString<QuantileSerializationType>(const char *value);
155962
155963template<>
155964QueryNodeType EnumUtil::FromString<QueryNodeType>(const char *value);
155965
155966template<>
155967QueryResultMemoryType EnumUtil::FromString<QueryResultMemoryType>(const char *value);
155968
155969template<>
155970QueryResultOutputType EnumUtil::FromString<QueryResultOutputType>(const char *value);
155971
155972template<>
155973QueryResultType EnumUtil::FromString<QueryResultType>(const char *value);
155974
155975template<>
155976RecoveryMode EnumUtil::FromString<RecoveryMode>(
const char *value);
155977
155978template<>
155979RelationType EnumUtil::FromString<RelationType>(const char *value);
155980
155981template<>
155982RenderMode EnumUtil::FromString<RenderMode>(const char *value);
155983
155984template<>
155985RequestType EnumUtil::FromString<RequestType>(const char *value);
155986
155987template<>
155988ResultModifierType EnumUtil::FromString<ResultModifierType>(const char *value);
155989
155990template<>
155991SampleMethod EnumUtil::FromString<SampleMethod>(const char *value);
155992
155993template<>
155994SampleType EnumUtil::FromString<SampleType>(const char *value);
155995
155996template<>
155997SamplingState EnumUtil::FromString<SamplingState>(const char *value);
155998
155999template<>
156000ScanType EnumUtil::FromString<ScanType>(const char *value);
156001
156002template<>
156004
156005template<>
156007
156008template<>
156010
156011template<>
156012SequenceInfo EnumUtil::FromString<SequenceInfo>(const char *value);
156013
156014template<>
156015SetOperationType EnumUtil::FromString<SetOperationType>(const char *value);
156016
156017template<>
156018SetScope EnumUtil::FromString<SetScope>(const char *value);
156019
156020template<>
156021SetType EnumUtil::FromString<SetType>(const char *value);
156022
156023template<>
156024SettingScope EnumUtil::FromString<SettingScope>(
const char *value);
156025
156026template<>
156027ShowType EnumUtil::FromString<ShowType>(const char *value);
156028
156029template<>
156031
156032template<>
156033SinkCombineResultType EnumUtil::FromString<SinkCombineResultType>(const char *value);
156034
156035template<>
156036SinkFinalizeType EnumUtil::FromString<SinkFinalizeType>(
const char *value);
156037
156038template<>
156040
156041template<>
156042SinkResultType EnumUtil::FromString<SinkResultType>(
const char *value);
156043
156044template<>
156045SortKeyType EnumUtil::FromString<SortKeyType>(
const char *value);
156046
156047template<>
156048SourceResultType EnumUtil::FromString<SourceResultType>(
const char *value);
156049
156050template<>
156051StarExpressionType EnumUtil::FromString<StarExpressionType>(const char *value);
156052
156053template<>
156054StatementReturnType EnumUtil::FromString<StatementReturnType>(const char *value);
156055
156056template<>
156057StatementType EnumUtil::FromString<StatementType>(const char *value);
156058
156059template<>
156060StatisticsType EnumUtil::FromString<StatisticsType>(const char *value);
156061
156062template<>
156063StatsInfo EnumUtil::FromString<StatsInfo>(const char *value);
156064
156065template<>
156066StorageBlockPrefetch EnumUtil::FromString<StorageBlockPrefetch>(const char *value);
156067
156068template<>
156069StorageIndexType EnumUtil::FromString<StorageIndexType>(const char *value);
156070
156071template<>
156072StrTimeSpecifier EnumUtil::FromString<StrTimeSpecifier>(const char *value);
156073
156074template<>
156075StreamExecutionResult EnumUtil::FromString<StreamExecutionResult>(const char *value);
156076
156077template<>
156078SubqueryType EnumUtil::FromString<SubqueryType>(const char *value);
156079
156080template<>
156081TableColumnType EnumUtil::FromString<TableColumnType>(const char *value);
156082
156083template<>
156084TableFilterType EnumUtil::FromString<TableFilterType>(const char *value);
156085
156086template<>
156088
156089template<>
156090TableReferenceType EnumUtil::FromString<TableReferenceType>(const char *value);
156091
156092template<>
156093TaskExecutionMode EnumUtil::FromString<TaskExecutionMode>(const char *value);
156094
156095template<>
156096TaskExecutionResult EnumUtil::FromString<TaskExecutionResult>(const char *value);
156097
156098template<>
156099TemporaryBufferSize EnumUtil::FromString<TemporaryBufferSize>(const char *value);
156100
156101template<>
156102TemporaryCompressionLevel EnumUtil::FromString<TemporaryCompressionLevel>(const char *value);
156103
156104template<>
156105ThreadPinMode EnumUtil::FromString<ThreadPinMode>(const char *value);
156106
156107template<>
156108TimestampCastResult EnumUtil::FromString<TimestampCastResult>(const char *value);
156109
156110template<>
156111TransactionInvalidationPolicy EnumUtil::FromString<TransactionInvalidationPolicy>(const char *value);
156112
156113template<>
156114TransactionModifierType EnumUtil::FromString<TransactionModifierType>(const char *value);
156115
156116template<>
156117TransactionType EnumUtil::FromString<TransactionType>(const char *value);
156118
156119template<>
156120TupleDataNestednessType EnumUtil::FromString<TupleDataNestednessType>(const char *value);
156121
156122template<>
156124
156125template<>
156126TupleDataValidityType EnumUtil::FromString<TupleDataValidityType>(const char *value);
156127
156128template<>
156129UndoFlags EnumUtil::FromString<UndoFlags>(const char *value);
156130
156131template<>
156132UnionInvalidReason EnumUtil::FromString<UnionInvalidReason>(const char *value);
156133
156134template<>
156135VariantChildLookupMode EnumUtil::FromString<VariantChildLookupMode>(const char *value);
156136
156137template<>
156138VariantLogicalType EnumUtil::FromString<VariantLogicalType>(const char *value);
156139
156140template<>
156142
156143template<>
156144VariantValueType EnumUtil::FromString<VariantValueType>(const char *value);
156145
156146template<>
156147VectorAuxiliaryDataType EnumUtil::FromString<VectorAuxiliaryDataType>(const char *value);
156148
156149template<>
156150VectorBufferType EnumUtil::FromString<VectorBufferType>(const char *value);
156151
156152template<>
156153VectorType EnumUtil::FromString<VectorType>(const char *value);
156154
156155template<>
156156VerificationType EnumUtil::FromString<VerificationType>(const char *value);
156157
156158template<>
156159VerifyExistenceType EnumUtil::FromString<VerifyExistenceType>(const char *value);
156160
156161template<>
156162VertexType EnumUtil::FromString<VertexType>(const char *value);
156163
156164template<>
156165WALType EnumUtil::FromString<WALType>(const char *value);
156166
156167template<>
156169
156170template<>
156171WindowBoundary EnumUtil::FromString<WindowBoundary>(const char *value);
156172
156173template<>
156175
156176template<>
156177WindowMergeSortStage EnumUtil::FromString<WindowMergeSortStage>(const char *value);
156178
156179
156180}
156181
156182
156183
156184
156185
156186namespace duckdb {
156187
156188class InterruptState;
156189class TaskExecutor;
156190class Executor;
156191
156192enum class AsyncResultsExecutionMode :
uint8_t {
156193 SYNCHRONOUS,
156194 TASK_EXECUTOR
156195};
156196
156197class AsyncTask {
156198public:
156199 virtual ~AsyncTask() {};
156200 virtual void Execute() = 0;
156201};
156202
156203class AsyncResult {
156204 explicit AsyncResult(AsyncResultType t);
156205
156206public:
156207 AsyncResult() = default;
156208 AsyncResult(AsyncResult &&) = default;
156209 AsyncResult(SourceResultType t);
156210 explicit AsyncResult(vector<unique_ptr<AsyncTask>> &&task);
156211 AsyncResult &
operator=(SourceResultType t);
156212 AsyncResult &
operator=(AsyncResultType t);
156213 AsyncResult &
operator=(AsyncResult &&) noexcept;
156214
156215
156216
156217 void ScheduleTasks(InterruptState &interrupt_state, Executor &executor);
156218
156219
156220
156221 void ExecuteTasksSynchronously();
156222
156223 static AsyncResultType GetAsyncResultType(SourceResultType s);
156224
156225
156226 bool HasTasks() const;
156227 AsyncResultType GetResultType() const;
156228
156229 vector<unique_ptr<AsyncTask>> &&ExtractAsyncTasks();
156230
156231#ifdef DUCKDB_DEBUG_ASYNC_SINK_SOURCE
156232 static vector<unique_ptr<AsyncTask>> GenerateTestTasks();
156233#endif
156234
156235 static AsyncResultsExecutionMode
156236 ConvertToAsyncResultExecutionMode(const PhysicalTableScanExecutionStrategy &execution_mode);
156237
156238private:
156240 vector<unique_ptr<AsyncTask>> async_tasks {};
156241};
156242}
156243
156244
156245
156246
156247
156248
156249
156250
156251
156252
156253
156254
156255
156256
156257
156258
156259namespace duckdb {
156260
156261class BinderException : public Exception {
156262public:
156263 DUCKDB_API explicit BinderException(const string &msg);
156264
156265 DUCKDB_API explicit BinderException(const unordered_map<string, string> &extra_info, const string &msg);
156266
156267 template <typename... ARGS>
156268 explicit BinderException(const string &msg, ARGS &&...params)
156269 : BinderException(ConstructMessage(msg, std::forward<ARGS>(
params)...)) {
156270 }
156271
156272 template <typename... ARGS>
156273 explicit BinderException(const TableRef &ref, const string &msg, ARGS &&...params)
156274 : BinderException(Exception::InitializeExtraInfo(ref), ConstructMessage(msg, std::forward<ARGS>(
params)...)) {
156275 }
156276 template <typename... ARGS>
156277 explicit BinderException(const ParsedExpression &expr, const string &msg, ARGS &&...params)
156278 : BinderException(Exception::InitializeExtraInfo(expr), ConstructMessage(msg, std::forward<ARGS>(
params)...)) {
156279 }
156280
156281 template <typename... ARGS>
156282 explicit BinderException(const Expression &expr, const string &msg, ARGS &&...params)
156283 : BinderException(Exception::InitializeExtraInfo(expr), ConstructMessage(msg, std::forward<ARGS>(
params)...)) {
156284 }
156285
156286 template <typename... ARGS>
156287 explicit BinderException(QueryErrorContext error_context, const string &msg, ARGS &&...params)
156288 : BinderException(Exception::InitializeExtraInfo(error_context),
156289 ConstructMessage(msg, std::forward<ARGS>(
params)...)) {
156290 }
156291
156292 template <typename... ARGS>
156293 explicit BinderException(optional_idx error_location, const string &msg, ARGS &&...params)
156294 : BinderException(Exception::InitializeExtraInfo(error_location),
156295 ConstructMessage(msg, std::forward<ARGS>(
params)...)) {
156296 }
156297
156298 static BinderException ColumnNotFound(const string &name, const vector<string> &similar_bindings,
156299 QueryErrorContext context = QueryErrorContext());
156300 static BinderException NoMatchingFunction(const string &catalog_name, const string &schema_name, const string &name,
156301 const vector<LogicalType> &arguments, const vector<string> &candidates);
156302 static BinderException Unsupported(ParsedExpression &expr, const string &message);
156303};
156304
156305}
156306
156307
156308
156309namespace duckdb {
156310
156311class BaseStatistics;
156312class LogicalDependencyList;
156313class LogicalGet;
156314class TableFunction;
156315class TableFilterSet;
156316class TableFunctionRef;
156317class TableCatalogEntry;
156318class SampleOptions;
156319struct MultiFileReader;
156320struct OperatorPartitionData;
156321struct OperatorPartitionInfo;
156322enum class OrderByColumnType :
uint8_t;
156323enum class OrderType :
uint8_t;
156324enum class OrderByStatistics :
uint8_t;
156325
156326struct TableFunctionInfo {
156327 DUCKDB_API virtual ~TableFunctionInfo();
156328
156329 template <class TARGET>
156330 TARGET &Cast() {
156331 DynamicCastCheck<TARGET>(this);
156332 return reinterpret_cast<TARGET &>(*this);
156333 }
156334 template <class TARGET>
156335 const TARGET &Cast() const {
156336 DynamicCastCheck<TARGET>(this);
156337 return reinterpret_cast<const TARGET &>(*this);
156338 }
156339};
156340
156341struct GlobalTableFunctionState {
156342public:
156343
156344 constexpr static const int64_t MAX_THREADS = 999999999;
156345
156346public:
156347 DUCKDB_API virtual ~GlobalTableFunctionState();
156348
156349 virtual idx_t MaxThreads()
const {
156350 return 1;
156351 }
156352
156353 template <class TARGET>
156354 TARGET &Cast() {
156355 DynamicCastCheck<TARGET>(this);
156356 return reinterpret_cast<TARGET &>(*this);
156357 }
156358 template <class TARGET>
156359 const TARGET &Cast() const {
156360 DynamicCastCheck<TARGET>(this);
156361 return reinterpret_cast<const TARGET &>(*this);
156362 }
156363};
156364
156365struct LocalTableFunctionState {
156366 DUCKDB_API virtual ~LocalTableFunctionState();
156367
156368 template <class TARGET>
156369 TARGET &Cast() {
156370 DynamicCastCheck<TARGET>(this);
156371 return reinterpret_cast<TARGET &>(*this);
156372 }
156373 template <class TARGET>
156374 const TARGET &Cast() const {
156375 DynamicCastCheck<TARGET>(this);
156376 return reinterpret_cast<const TARGET &>(*this);
156377 }
156378};
156379
156380struct TableFunctionBindInput {
156381 TableFunctionBindInput(vector<Value> &inputs, named_parameter_map_t &named_parameters,
156382 vector<LogicalType> &input_table_types, vector<string> &input_table_names,
156383 optional_ptr<TableFunctionInfo> info, optional_ptr<Binder> binder,
156384 TableFunction &table_function, const TableFunctionRef &ref)
156385 : inputs(inputs), named_parameters(named_parameters), input_table_types(input_table_types),
156386 input_table_names(input_table_names), info(info), binder(binder), table_function(table_function), ref(ref) {
156387 }
156388
156389 vector<Value> &inputs;
156390 named_parameter_map_t &named_parameters;
156391 vector<LogicalType> &input_table_types;
156392 vector<string> &input_table_names;
156393 optional_ptr<TableFunctionInfo> info;
156394 optional_ptr<Binder> binder;
156395 TableFunction &table_function;
156396 const TableFunctionRef &ref;
156397};
156398
156399struct TableFunctionInitInput {
156400 TableFunctionInitInput(optional_ptr<const FunctionData> bind_data_p, vector<column_t> column_ids_p,
156401 const vector<idx_t> &projection_ids_p, optional_ptr<TableFilterSet> filters_p,
156402 optional_ptr<SampleOptions> sample_options_p = nullptr,
156403 optional_ptr<const PhysicalOperator> op_p = nullptr)
156404 : bind_data(bind_data_p), column_ids(std::move(column_ids_p)), projection_ids(projection_ids_p),
156405 filters(filters_p), sample_options(sample_options_p), op(op_p) {
156406 for (auto &col_id : column_ids) {
156407 column_indexes.emplace_back(col_id);
156408 }
156409 }
156410
156411 TableFunctionInitInput(optional_ptr<const FunctionData> bind_data_p, vector<ColumnIndex> column_indexes_p,
156412 const vector<idx_t> &projection_ids_p, optional_ptr<TableFilterSet> filters_p,
156413 optional_ptr<SampleOptions> sample_options_p = nullptr,
156414 optional_ptr<const PhysicalOperator> op_p = nullptr)
156415 : bind_data(bind_data_p), column_indexes(std::move(column_indexes_p)), projection_ids(projection_ids_p),
156416 filters(filters_p), sample_options(sample_options_p), op(op_p) {
156417 for (auto &col_id : column_indexes) {
156418 column_ids.emplace_back(col_id.GetPrimaryIndex());
156419 }
156420 }
156421
156422 optional_ptr<const FunctionData> bind_data;
156423 vector<column_t> column_ids;
156424 vector<ColumnIndex> column_indexes;
156425 const vector<idx_t> projection_ids;
156426 optional_ptr<TableFilterSet> filters;
156427 optional_ptr<SampleOptions> sample_options;
156428 optional_ptr<const PhysicalOperator> op;
156429
156430 bool CanRemoveFilterColumns() const {
156431 if (projection_ids.empty()) {
156432
156433 return false;
156434 }
156435 if (projection_ids.size() == column_ids.size()) {
156436
156437 return false;
156438 }
156439
156440 return true;
156441 }
156442};
156443
156444struct TableFunctionInput {
156445public:
156446 TableFunctionInput(optional_ptr<const FunctionData> bind_data_p,
156447 optional_ptr<LocalTableFunctionState> local_state_p,
156448 optional_ptr<GlobalTableFunctionState> global_state_p)
156449 : bind_data(bind_data_p), local_state(local_state_p), global_state(global_state_p), async_result() {
156450 }
156451
156452public:
156453 optional_ptr<const FunctionData> bind_data;
156454 optional_ptr<LocalTableFunctionState> local_state;
156455 optional_ptr<GlobalTableFunctionState> global_state;
156456 AsyncResult async_result {};
156457 AsyncResultsExecutionMode results_execution_mode {AsyncResultsExecutionMode::SYNCHRONOUS};
156458};
156459
156460struct TableFunctionPartitionInput {
156461 TableFunctionPartitionInput(optional_ptr<const FunctionData> bind_data_p, const vector<column_t> &partition_ids)
156462 : bind_data(bind_data_p), partition_ids(partition_ids) {
156463 }
156464
156465 optional_ptr<const FunctionData> bind_data;
156466 const vector<column_t> &partition_ids;
156467};
156468
156469struct TableFunctionToStringInput {
156470 TableFunctionToStringInput(const TableFunction &table_function_p, optional_ptr<const FunctionData> bind_data_p)
156471 : table_function(table_function_p), bind_data(bind_data_p) {
156472 }
156473 const TableFunction &table_function;
156474 optional_ptr<const FunctionData> bind_data;
156475};
156476
156477struct TableFunctionDynamicToStringInput {
156478 TableFunctionDynamicToStringInput(const TableFunction &table_function_p,
156479 optional_ptr<const FunctionData> bind_data_p,
156480 optional_ptr<LocalTableFunctionState> local_state_p,
156481 optional_ptr<GlobalTableFunctionState> global_state_p)
156482 : table_function(table_function_p), bind_data(bind_data_p), local_state(local_state_p),
156483 global_state(global_state_p) {
156484 }
156485 const TableFunction &table_function;
156486 optional_ptr<const FunctionData> bind_data;
156487 optional_ptr<LocalTableFunctionState> local_state;
156488 optional_ptr<GlobalTableFunctionState> global_state;
156489};
156490
156491struct TableFunctionGetPartitionInput {
156492public:
156493 TableFunctionGetPartitionInput(optional_ptr<const FunctionData> bind_data_p,
156494 optional_ptr<LocalTableFunctionState> local_state_p,
156495 optional_ptr<GlobalTableFunctionState> global_state_p,
156496 const OperatorPartitionInfo &partition_info_p)
156497 : bind_data(bind_data_p), local_state(local_state_p), global_state(global_state_p),
156498 partition_info(partition_info_p) {
156499 }
156500
156501public:
156502 optional_ptr<const FunctionData> bind_data;
156503 optional_ptr<LocalTableFunctionState> local_state;
156504 optional_ptr<GlobalTableFunctionState> global_state;
156505 const OperatorPartitionInfo &partition_info;
156506};
156507
156508struct TableFunctionGetStatisticsInput {
156509public:
156510 TableFunctionGetStatisticsInput(const FunctionData *bind_data, const ColumnIndex &column_index)
156511 : bind_data(bind_data), column_index(column_index) {
156512 }
156513
156514public:
156515 optional_ptr<const FunctionData> bind_data;
156516 ColumnIndex column_index;
156517};
156518
156519struct GetPartitionStatsInput {
156520 GetPartitionStatsInput(const TableFunction &table_function_p, optional_ptr<const FunctionData> bind_data_p)
156521 : table_function(table_function_p), bind_data(bind_data_p) {
156522 }
156523
156524 const TableFunction &table_function;
156525 optional_ptr<const FunctionData> bind_data;
156526};
156527
156528enum class ScanType :
uint8_t { TABLE, PARQUET, EXTERNAL };
156529
156530struct BindInfo {
156531public:
156532 explicit BindInfo(ScanType type_p) : type(type_p) {};
156533 explicit BindInfo(TableCatalogEntry &table) : type(ScanType::TABLE), table(&table) {};
156534
156535 unordered_map<string, Value> options;
156536 ScanType type;
156537 optional_ptr<TableCatalogEntry> table;
156538
156539 void InsertOption(const string &name, Value value) {
156540 if (options.find(name) != options.end()) {
156541 throw InternalException("This option already exists");
156542 }
156543 options.emplace(name, std::move(value));
156544 }
156545 template <class T>
156546 T GetOption(const string &name) {
156547 if (options.find(name) == options.end()) {
156548 throw InternalException("This option does not exist");
156549 }
156550 return options[name].GetValue<T>();
156551 }
156552 template <class T>
156553 vector<T> GetOptionList(const string &name) {
156554 if (options.find(name) == options.end()) {
156555 throw InternalException("This option does not exist");
156556 }
156557 auto option = options[name];
156558 if (option.type().id() != LogicalTypeId::LIST) {
156559 throw InternalException("This option is not a list");
156560 }
156561 vector<T> result;
156562 auto list_children = ListValue::GetChildren(option);
156563 for (auto &child : list_children) {
156564 result.emplace_back(child.GetValue<T>());
156565 }
156566 return result;
156567 }
156568};
156569
156570typedef unique_ptr<FunctionData> (*table_function_bind_t)(ClientContext &context, TableFunctionBindInput &input,
156571 vector<LogicalType> &return_types, vector<string> &names);
156572typedef unique_ptr<TableRef> (*table_function_bind_replace_t)(ClientContext &context, TableFunctionBindInput &input);
156573typedef unique_ptr<LogicalOperator> (*table_function_bind_operator_t)(ClientContext &context,
156574 TableFunctionBindInput &input,
idx_t bind_index,
156575 vector<string> &return_names);
156576typedef unique_ptr<GlobalTableFunctionState> (*table_function_init_global_t)(ClientContext &context,
156577 TableFunctionInitInput &input);
156578typedef unique_ptr<LocalTableFunctionState> (*table_function_init_local_t)(ExecutionContext &context,
156579 TableFunctionInitInput &input,
156580 GlobalTableFunctionState *global_state);
156581typedef unique_ptr<BaseStatistics> (*table_statistics_t)(ClientContext &context, const FunctionData *bind_data,
156583typedef unique_ptr<BaseStatistics> (*table_statistics_extended_t)(ClientContext &context,
156584 TableFunctionGetStatisticsInput &input);
156585typedef void (*table_function_t)(ClientContext &context, TableFunctionInput &data, DataChunk &output);
156586typedef OperatorResultType (*table_in_out_function_t)(ExecutionContext &context, TableFunctionInput &data,
156587 DataChunk &input, DataChunk &output);
156589 DataChunk &output);
156590typedef OperatorPartitionData (*table_function_get_partition_data_t)(ClientContext &context,
156591 TableFunctionGetPartitionInput &input);
156592
156593typedef BindInfo (*table_function_get_bind_info_t)(const optional_ptr<FunctionData> bind_data);
156594
156595typedef unique_ptr<MultiFileReader> (*table_function_get_multi_file_reader_t)(const TableFunction &);
156596
156597typedef bool (*table_function_supports_pushdown_type_t)(
const FunctionData &bind_data,
idx_t col_idx);
156598
156599typedef bool (*table_function_supports_pushdown_extract_t)(const FunctionData &bind_data, const LogicalIndex &col_idx);
156600
156601typedef double (*table_function_progress_t)(ClientContext &context, const FunctionData *bind_data,
156602 const GlobalTableFunctionState *global_state);
156603typedef void (*table_function_dependency_t)(LogicalDependencyList &dependencies, const FunctionData *bind_data);
156604typedef unique_ptr<NodeStatistics> (*table_function_cardinality_t)(ClientContext &context,
156605 const FunctionData *bind_data);
156606typedef idx_t (*table_function_rows_scanned_t)(GlobalTableFunctionState &global_state,
156607 LocalTableFunctionState &local_state);
156608typedef void (*table_function_pushdown_complex_filter_t)(ClientContext &context, LogicalGet &
get,
156609 FunctionData *bind_data,
156610 vector<unique_ptr<Expression>> &filters);
156611typedef bool (*table_function_pushdown_expression_t)(ClientContext &context,
const LogicalGet &
get, Expression &expr);
156612typedef InsertionOrderPreservingMap<string> (*table_function_to_string_t)(TableFunctionToStringInput &input);
156613typedef InsertionOrderPreservingMap<string> (*table_function_dynamic_to_string_t)(
156614 TableFunctionDynamicToStringInput &input);
156615
156616typedef void (*table_function_serialize_t)(Serializer &serializer, const optional_ptr<FunctionData> bind_data,
156617 const TableFunction &function);
156618typedef unique_ptr<FunctionData> (*table_function_deserialize_t)(Deserializer &deserializer, TableFunction &function);
156619
156620typedef void (*table_function_type_pushdown_t)(ClientContext &context, optional_ptr<FunctionData> bind_data,
156621 const unordered_map<idx_t, LogicalType> &new_column_types);
156622typedef TablePartitionInfo (*table_function_get_partition_info_t)(ClientContext &context,
156623 TableFunctionPartitionInput &input);
156624
156625typedef vector<PartitionStatistics> (*table_function_get_partition_stats_t)(ClientContext &context,
156626 GetPartitionStatsInput &input);
156627
156628typedef virtual_column_map_t (*table_function_get_virtual_columns_t)(ClientContext &context,
156629 optional_ptr<FunctionData> bind_data);
156630
156631typedef vector<column_t> (*table_function_get_row_id_columns)(ClientContext &context,
156632 optional_ptr<FunctionData> bind_data);
156633
156634typedef void (*table_function_set_scan_order)(unique_ptr<RowGroupOrderOptions> order_options,
156635 optional_ptr<FunctionData> bind_data);
156636
156639
156640class TableFunction : public SimpleNamedParameterFunction {
156641public:
156642 DUCKDB_API TableFunction();
156643
156644 DUCKDB_API
156645 TableFunction(string name, const vector<LogicalType> &arguments, table_function_t function,
156646 table_function_bind_t bind = nullptr, table_function_init_global_t init_global = nullptr,
156647 table_function_init_local_t init_local = nullptr);
156648 DUCKDB_API
156649 TableFunction(const vector<LogicalType> &arguments, table_function_t function, table_function_bind_t bind = nullptr,
156650 table_function_init_global_t init_global = nullptr, table_function_init_local_t init_local = nullptr);
156651
156652 DUCKDB_API
156653 TableFunction(string name, const vector<LogicalType> &arguments, std::nullptr_t function,
156654 table_function_bind_t bind = nullptr, table_function_init_global_t init_global = nullptr,
156655 table_function_init_local_t init_local = nullptr);
156656 DUCKDB_API
156657 TableFunction(const vector<LogicalType> &arguments, std::nullptr_t function, table_function_bind_t bind = nullptr,
156658 table_function_init_global_t init_global = nullptr, table_function_init_local_t init_local = nullptr);
156659
156660 bool HasBindCallback() const {
156661 return bind !=
nullptr;
156662 }
156663 table_function_bind_t GetBindCallback() const {
156665 }
156666 bool HasSerializationCallbacks() const {
156668 }
156669 void SetSerializeCallback(table_function_serialize_t callback) {
156671 }
156672 void SetDeserializeCallback(table_function_deserialize_t callback) {
156674 }
156675 table_function_serialize_t GetSerializeCallback() const {
156677 }
156678 table_function_deserialize_t GetDeserializeCallback() const {
156680 }
156681
156685 table_function_bind_t
bind;
156690 table_function_bind_replace_t bind_replace;
156694 table_function_bind_operator_t bind_operator;
156699 table_function_init_global_t init_global;
156703 table_function_init_local_t init_local;
156705 table_function_t function;
156707 table_in_out_function_t in_out_function;
156709 table_in_out_function_final_t in_out_function_final;
156712 table_statistics_t statistics;
156715 table_statistics_extended_t statistics_extended;
156718 table_function_dependency_t dependency;
156721 table_function_cardinality_t cardinality;
156723 table_function_rows_scanned_t rows_scanned;
156726 table_function_pushdown_complex_filter_t pushdown_complex_filter;
156728 table_function_pushdown_expression_t pushdown_expression;
156732 table_function_dynamic_to_string_t dynamic_to_string;
156734 table_function_progress_t table_scan_progress;
156736 table_function_get_partition_data_t get_partition_data;
156738 table_function_get_bind_info_t get_bind_info;
156740 table_function_type_pushdown_t type_pushdown;
156742 table_function_get_multi_file_reader_t get_multi_file_reader;
156744 table_function_supports_pushdown_type_t supports_pushdown_type;
156746 table_function_supports_pushdown_extract_t supports_pushdown_extract;
156748 table_function_get_partition_info_t get_partition_info;
156750 table_function_get_partition_stats_t get_partition_stats;
156752 table_function_get_virtual_columns_t get_virtual_columns;
156754 table_function_get_row_id_columns get_row_id_columns;
156756 table_function_set_scan_order set_scan_order;
156757
156760 bool verify_serialization = true;
156761
156764 bool projection_pushdown;
156767 bool filter_pushdown;
156770 bool filter_prune;
156773 bool sampling_pushdown;
156775 bool late_materialization;
156777 shared_ptr<TableFunctionInfo> function_info;
156779 OrderPreservationType order_preservation_type = OrderPreservationType::INSERTION_ORDER;
156780
156785
156786 DUCKDB_API bool Equal(const TableFunction &rhs) const;
156787 DUCKDB_API
bool operator==(
const TableFunction &rhs)
const;
156788 DUCKDB_API
bool operator!=(
const TableFunction &rhs)
const;
156789};
156790
156791}
156792
156793
156794
156795
156796
156797
156798
156799
156800
156801
156802
156803
156804
156805
156806
156807
156808
156809namespace duckdb {
156810
156811struct ConcurrentQueue;
156812struct QueueProducerToken;
156813class ClientContext;
156814class DatabaseInstance;
156815class TaskScheduler;
156816
156817struct SchedulerThread;
156818
156819struct ProducerToken {
156820 ProducerToken(TaskScheduler &scheduler, unique_ptr<QueueProducerToken> token);
156821 ~ProducerToken();
156822
156823 TaskScheduler &scheduler;
156824 unique_ptr<QueueProducerToken> token;
156825 mutex producer_lock;
156826};
156827
156829class TaskScheduler {
156830
156831 constexpr static int64_t TASK_TIMEOUT_USECS = 5000;
156832
156833public:
156834 explicit TaskScheduler(DatabaseInstance &db);
156835 ~TaskScheduler();
156836
156837 DUCKDB_API static TaskScheduler &GetScheduler(ClientContext &context);
156838 DUCKDB_API static TaskScheduler &GetScheduler(DatabaseInstance &db);
156839
156840 unique_ptr<ProducerToken> CreateProducer();
156842 void ScheduleTask(ProducerToken &producer, shared_ptr<Task> task);
156843 void ScheduleTasks(ProducerToken &producer, vector<shared_ptr<Task>> &tasks);
156845 bool GetTaskFromProducer(ProducerToken &token, shared_ptr<Task> &task);
156847 void ExecuteForever(atomic<bool> *marker);
156850 idx_t ExecuteTasks(atomic<bool> *marker, idx_t max_tasks);
156852 void ExecuteTasks(idx_t max_tasks);
156853
156857 void SetThreads(idx_t total_threads, idx_t external_threads);
156858
156859 void RelaunchThreads();
156860
156862 DUCKDB_API
int32_t NumberOfThreads();
156863
156864 idx_t GetNumberOfTasks()
const;
156865 idx_t GetProducerCount()
const;
156866 idx_t GetTaskCountForProducer(ProducerToken &token)
const;
156867
156869 void Signal(idx_t n);
156870
156872 static void YieldThread();
156873
156875 void SetAllocatorFlushTreshold(idx_t threshold);
156877 void SetAllocatorBackgroundThreads(bool enable);
156878
156882 static idx_t GetEstimatedCPUId();
156883
156884private:
156885 void RelaunchThreadsInternal(int32_t n, bool destroy);
156886
156887private:
156888 DatabaseInstance &
db;
156890 unique_ptr<ConcurrentQueue> queue;
156892 mutex thread_lock;
156894 vector<unique_ptr<SchedulerThread>> threads;
156896 vector<unique_ptr<atomic<bool>>> markers;
156898 atomic<idx_t> allocator_flush_threshold;
156900 atomic<bool> allocator_background_threads;
156902 atomic<int32_t> requested_thread_count;
156904 atomic<int32_t> current_thread_count;
156905};
156906
156907}
156908
156909
156910
156911
156912
156913
156914
156915
156916
156917
156918
156919
156920
156921
156922
156923namespace duckdb {
156925class PhysicalOperator;
156926class ThreadContext;
156927
156930class ExecutorTask : public Task {
156931public:
156932 ExecutorTask(Executor &executor, shared_ptr<Event> event);
156933 ExecutorTask(ClientContext &context, shared_ptr<Event> event, const PhysicalOperator &op);
156934 ~ExecutorTask() override;
156935
156936public:
156937 void Deschedule() override;
156938 void Reschedule() override;
156939
156940public:
156941 Executor &executor;
156942 shared_ptr<Event> event;
156943 unique_ptr<ThreadContext> thread_context;
156944 optional_ptr<const PhysicalOperator> op;
156945
156946private:
156947 ClientContext &context;
156948
156949public:
156950 virtual TaskExecutionResult ExecuteTask(TaskExecutionMode mode) = 0;
156951 TaskExecutionResult Execute(TaskExecutionMode mode) override;
156952};
156953
156954}
156955
156956
156957namespace duckdb {
156958
156959class Executor;
156960class MetaPipeline;
156961class PipelineExecutor;
156962class Pipeline;
156963
156964class PipelineTask : public ExecutorTask {
156965 static constexpr const idx_t PARTIAL_CHUNK_COUNT = 50;
156966
156967public:
156968 explicit PipelineTask(Pipeline &pipeline_p, shared_ptr<Event> event_p);
156969
156970 Pipeline &pipeline;
156971 unique_ptr<PipelineExecutor> pipeline_executor;
156972
156973 string TaskType() const override {
156974 return "PipelineTask";
156975 }
156976
156977public:
156978 const PipelineExecutor &GetPipelineExecutor() const;
156979 bool TaskBlockedOnResult() const override;
156980
156981public:
156982 TaskExecutionResult ExecuteTask(TaskExecutionMode mode) override;
156983};
156984
156985class PipelineBuildState {
156986public:
156988 constexpr static idx_t BATCH_INCREMENT = 10000000000000;
156989
156990public:
156992 reference_map_t<const PhysicalOperator, reference<Pipeline>> delim_join_dependencies;
156994 reference_map_t<const PhysicalOperator, reference<Pipeline>> cte_dependencies;
156995
156996public:
156997 void SetPipelineSource(Pipeline &pipeline, PhysicalOperator &op);
156998 void SetPipelineSink(Pipeline &pipeline, optional_ptr<PhysicalOperator> op, idx_t sink_pipeline_count);
156999 void SetPipelineOperators(Pipeline &pipeline, vector<reference<PhysicalOperator>> operators);
157000 void AddPipelineOperator(Pipeline &pipeline, PhysicalOperator &op);
157001 shared_ptr<Pipeline> CreateChildPipeline(Executor &executor, Pipeline &pipeline, PhysicalOperator &op);
157002
157003 optional_ptr<PhysicalOperator> GetPipelineSource(Pipeline &pipeline);
157004 optional_ptr<PhysicalOperator> GetPipelineSink(Pipeline &pipeline);
157005 vector<reference<PhysicalOperator>> GetPipelineOperators(Pipeline &pipeline);
157006};
157007
157009class Pipeline : public enable_shared_from_this<Pipeline> {
157010 friend class Executor;
157011 friend class PipelineExecutor;
157012 friend class PipelineEvent;
157013 friend class PipelineFinishEvent;
157014 friend class PipelineBuildState;
157015 friend class MetaPipeline;
157016
157017public:
157018 explicit Pipeline(Executor &execution_context);
157019
157020 Executor &executor;
157021
157022public:
157023 ClientContext &GetClientContext();
157024
157025 void AddDependency(shared_ptr<Pipeline> &pipeline);
157026 vector<weak_ptr<Pipeline>> GetDependencies() const;
157027
157028 void Ready();
157029 void Reset();
157030 void ResetSink();
157031 void ResetSource(bool force);
157032 void ClearSource();
157033 void Schedule(shared_ptr<Event> &event);
157034 void PrepareFinalize();
157035
157036 string ToString() const;
157037 void Print() const;
157038 void PrintDependencies() const;
157039
157041 bool GetProgress(ProgressData &progress_data);
157042
157044 vector<reference<PhysicalOperator>> GetOperators();
157045 vector<const_reference<PhysicalOperator>> GetOperators() const;
157046 const vector<reference<PhysicalOperator>> &GetIntermediateOperators() const;
157047
157048 optional_ptr<PhysicalOperator> GetSink() {
157049 return sink;
157050 }
157051
157052 optional_ptr<PhysicalOperator> GetSource() {
157053 return source;
157054 }
157055
157057 bool IsOrderDependent() const;
157058
157060 idx_t RegisterNewBatchIndex();
157061
157063 idx_t UpdateBatchIndex(idx_t old_index, idx_t new_index);
157064
157065private:
157067 bool ready;
157069 atomic<bool> initialized;
157071 optional_ptr<PhysicalOperator> source;
157073 vector<reference<PhysicalOperator>> operators;
157075 optional_ptr<PhysicalOperator> sink;
157076
157078 unique_ptr<GlobalSourceState> source_state;
157079
157081 vector<weak_ptr<Pipeline>> parents;
157083 vector<weak_ptr<Pipeline>> dependencies;
157084
157086 idx_t base_batch_index = 0;
157088 mutex batch_lock;
157093 multiset<idx_t> batch_indexes;
157094
157095private:
157096 void ScheduleSequentialTask(shared_ptr<Event> &event);
157097 bool LaunchScanTasks(shared_ptr<Event> &event, idx_t max_threads);
157098
157099 bool ScheduleParallel(shared_ptr<Event> &event);
157100};
157101
157102}
157103
157104
157105#include <condition_variable>
157106
157107namespace duckdb {
157108class ClientContext;
157109class DataChunk;
157110class PhysicalOperator;
157111class PipelineExecutor;
157112class OperatorState;
157113class QueryProfiler;
157114class ThreadContext;
157115class Task;
157116
157117struct PipelineEventStack;
157118struct ProducerToken;
157119struct ScheduleEventData;
157120
157121class Executor {
157122 friend class Pipeline;
157123 friend class PipelineTask;
157124 friend class PipelineBuildState;
157125
157126public:
157127 static constexpr idx_t WAIT_TIME = 20;
157128
157129public:
157130 explicit Executor(ClientContext &context);
157131 ~Executor();
157132
157133 ClientContext &context;
157134
157135public:
157136 static Executor &Get(ClientContext &context);
157137
157138 void Initialize(PhysicalOperator &physical_plan);
157139 void Initialize(unique_ptr<PhysicalOperator> physical_plan);
157140
157141 void CancelTasks();
157142 PendingExecutionResult ExecuteTask(bool dry_run = false);
157143 void WaitForTask();
157144 void SignalTaskRescheduled(lock_guard<mutex> &);
157145
157146 void Reset();
157147
157148 vector<LogicalType> GetTypes();
157149
157151 void PushError(ErrorData exception);
157152
157153 ErrorData GetError();
157154
157156 bool HasError();
157159 void ThrowException();
157160
157162 void WorkOnTasks();
157163
157165 void Flush(ThreadContext &context);
157166
157168 void RescheduleTask(shared_ptr<Task> &task);
157169
157171 void AddToBeRescheduled(shared_ptr<Task> &task);
157172
157174 idx_t GetPipelinesProgress(ProgressData &progress);
157175
157176 void CompletePipeline() {
157177 completed_pipelines++;
157178 }
157179 ProducerToken &GetToken() {
157180 return *producer;
157181 }
157182 void AddEvent(shared_ptr<Event> event);
157183
157184 void AddRecursiveCTE(PhysicalOperator &rec_cte);
157185 void ReschedulePipelines(const vector<shared_ptr<MetaPipeline>> &pipelines, vector<shared_ptr<Event>> &events);
157186
157188 bool HasResultCollector();
157190 bool HasStreamingResultCollector();
157192 unique_ptr<QueryResult> GetResult();
157193
157195 bool ExecutionIsFinished();
157196
157197 void RegisterTask() {
157198 executor_tasks++;
157199 }
157200 void UnregisterTask() {
157201 executor_tasks--;
157202 }
157203
157204 idx_t GetTotalPipelines()
const {
157205 return total_pipelines;
157206 }
157207
157208 idx_t GetCompletedPipelines()
const {
157209 return completed_pipelines.load();
157210 }
157211
157212private:
157214 bool ResultCollectorIsBlocked();
157215 void InitializeInternal(PhysicalOperator &physical_plan);
157216
157217 void ScheduleEvents(const vector<shared_ptr<MetaPipeline>> &meta_pipelines);
157218 void ScheduleEventsInternal(ScheduleEventData &event_data);
157219
157220 static void VerifyScheduledEvents(const ScheduleEventData &event_data);
157221 static void VerifyScheduledEventsInternal(const idx_t i, const vector<reference<Event>> &vertices,
157222 vector<bool> &visited, vector<bool> &recursion_stack);
157223
157224 void SchedulePipeline(const shared_ptr<MetaPipeline> &pipeline, ScheduleEventData &event_data);
157225
157226 bool NextExecutor();
157227
157228 shared_ptr<Pipeline> CreateChildPipeline(Pipeline ¤t, PhysicalOperator &op);
157229
157230 void VerifyPipeline(Pipeline &pipeline);
157231 void VerifyPipelines();
157232
157233private:
157234 optional_ptr<PhysicalOperator> physical_plan;
157235 unique_ptr<PhysicalOperator> owned_plan;
157236
157237 mutex executor_lock;
157239 vector<shared_ptr<Pipeline>> pipelines;
157241 vector<shared_ptr<Pipeline>> root_pipelines;
157243 vector<reference<PhysicalOperator>> recursive_ctes;
157245 unique_ptr<PipelineExecutor> root_executor;
157247 idx_t root_pipeline_idx;
157249 unique_ptr<ProducerToken> producer;
157251 vector<shared_ptr<Event>> events;
157253 shared_ptr<QueryProfiler> profiler;
157255 TaskErrorManager error_manager;
157256
157258 atomic<idx_t> completed_pipelines;
157260 idx_t total_pipelines;
157262 bool cancelled;
157263
157265 PendingExecutionResult execution_result;
157267 shared_ptr<Task> task;
157268
157270 unordered_map<Task *, shared_ptr<Task>> to_be_rescheduled_tasks;
157272 std::condition_variable task_reschedule;
157273
157275 atomic<idx_t> executor_tasks;
157276
157278 atomic<idx_t> blocked_thread_time;
157279};
157280}
157281
157282
157283namespace duckdb {
157284class ClientContext;
157285class ClientContextLock;
157286class PreparedStatementData;
157287
157288class PendingQueryResult : public BaseQueryResult {
157289 friend class ClientContext;
157290
157291public:
157292 static constexpr const QueryResultType
TYPE = QueryResultType::PENDING_RESULT;
157293
157294public:
157295 DUCKDB_API PendingQueryResult(shared_ptr<ClientContext> context, PreparedStatementData &statement,
157296 vector<LogicalType> types, bool allow_stream_result);
157297 DUCKDB_API explicit PendingQueryResult(ErrorData error_message);
157298 DUCKDB_API ~PendingQueryResult() override;
157299 DUCKDB_API bool AllowStreamResult() const;
157300 PendingQueryResult(const PendingQueryResult &) = delete;
157301 PendingQueryResult &
operator=(
const PendingQueryResult &) =
delete;
157302
157303public:
157311 DUCKDB_API PendingExecutionResult ExecuteTask();
157312 DUCKDB_API PendingExecutionResult CheckPulse();
157314 void WaitForTask();
157315
157318 DUCKDB_API unique_ptr<QueryResult> Execute();
157319
157320 DUCKDB_API void Close();
157321
157323 DUCKDB_API static bool IsResultReady(PendingExecutionResult result);
157324 DUCKDB_API static bool IsExecutionFinished(PendingExecutionResult result);
157325
157326private:
157327 shared_ptr<ClientContext> context;
157328 bool allow_stream_result;
157329
157330private:
157331 void CheckExecutableInternal(ClientContextLock &lock);
157332
157333 PendingExecutionResult ExecuteTaskInternal(ClientContextLock &lock);
157334 unique_ptr<QueryResult> ExecuteInternal(ClientContextLock &lock);
157335 unique_ptr<ClientContextLock> LockContext();
157336};
157337
157338}
157339
157340
157341
157342
157343
157344
157345
157346
157347
157348
157349
157350
157351
157352
157353
157354
157355
157356
157357
157358
157359
157360
157361
157362
157363
157364
157365
157366
157367
157368namespace duckdb {
157369
157370struct BoundParameterData {
157371public:
157372 BoundParameterData() {
157373 }
157374 explicit BoundParameterData(Value val) : value(std::move(val)), return_type(GetDefaultType(value.type())) {
157375 }
157376 BoundParameterData(Value val, LogicalType type_p) : value(std::move(val)), return_type(std::move(type_p)) {
157377 }
157378
157379private:
157380 Value value;
157381
157382public:
157383 LogicalType return_type;
157384
157385public:
157386 void SetValue(Value val) {
157387 value = std::move(val);
157388 }
157389
157390 const Value &GetValue() const {
157391 return value;
157392 }
157393
157394 void Serialize(Serializer &serializer) const;
157395 static shared_ptr<BoundParameterData> Deserialize(Deserializer &deserializer);
157396
157397private:
157398 LogicalType GetDefaultType(const LogicalType &type) {
157399 if (value.type().id() == LogicalTypeId::VARCHAR && StringType::GetCollation(type).empty()) {
157400 return LogicalTypeId::STRING_LITERAL;
157401 }
157402 return value.type();
157403 }
157404};
157405
157406}
157407
157408
157409namespace duckdb {
157410class ClientContext;
157411class PreparedStatementData;
157412
157414class PreparedStatement {
157415public:
157417 DUCKDB_API PreparedStatement(shared_ptr<ClientContext> context, shared_ptr<PreparedStatementData> data,
157418 string query, case_insensitive_map_t<idx_t> named_param_map);
157420 DUCKDB_API explicit PreparedStatement(ErrorData error);
157421
157422 DUCKDB_API ~PreparedStatement();
157423
157424public:
157426 shared_ptr<ClientContext> context;
157428 shared_ptr<PreparedStatementData> data;
157430 string query;
157432 bool success;
157434 ErrorData error;
157436 case_insensitive_map_t<idx_t> named_param_map;
157437
157438public:
157440 DUCKDB_API const string &GetError();
157442 DUCKDB_API ErrorData &GetErrorObject();
157444 DUCKDB_API bool HasError() const;
157446 DUCKDB_API
idx_t ColumnCount();
157448 DUCKDB_API StatementType GetStatementType();
157450 DUCKDB_API StatementProperties GetStatementProperties();
157452 DUCKDB_API const vector<LogicalType> &GetTypes();
157454 DUCKDB_API const vector<string> &GetNames();
157456 DUCKDB_API case_insensitive_map_t<LogicalType> GetExpectedParameterTypes() const;
157457
157459 template <typename... ARGS>
157460 unique_ptr<PendingQueryResult> PendingQuery(ARGS... args) {
157461 vector<Value> values;
157462 return PendingQueryRecursive(values, args...);
157463 }
157464
157466 DUCKDB_API unique_ptr<PendingQueryResult> PendingQuery(vector<Value> &values, bool allow_stream_result = true);
157467
157469 DUCKDB_API unique_ptr<PendingQueryResult> PendingQuery(case_insensitive_map_t<BoundParameterData> &named_values,
157470 bool allow_stream_result = true);
157471
157473 DUCKDB_API unique_ptr<QueryResult> Execute(vector<Value> &values, bool allow_stream_result = true);
157474
157476 DUCKDB_API unique_ptr<QueryResult> Execute(case_insensitive_map_t<BoundParameterData> &named_values,
157477 bool allow_stream_result = true);
157478
157480 template <typename... ARGS>
157481 unique_ptr<QueryResult> Execute(ARGS... args) {
157482 vector<Value> values;
157483 return ExecuteRecursive(values, args...);
157484 }
157485
157486 template <class PAYLOAD>
157487 static string ExcessValuesException(const case_insensitive_map_t<idx_t> ¶meters,
157488 const case_insensitive_map_t<PAYLOAD> &values) {
157489
157490 set<string> excess_set;
157491 for (auto &pair : values) {
157492 auto &name = pair.first;
157493 if (!parameters.count(name)) {
157494 excess_set.insert(name);
157495 }
157496 }
157497 vector<string> excess_values;
157498 for (auto &val : excess_set) {
157499 excess_values.push_back(val);
157500 }
157501 return StringUtil::Format(
"Parameter argument/count mismatch, identifiers of the excess parameters: %s",
157503 }
157504
157505 template <class PAYLOAD>
157506 static string MissingValuesException(const case_insensitive_map_t<idx_t> ¶meters,
157507 const case_insensitive_map_t<PAYLOAD> &values) {
157508
157509 set<string> missing_set;
157510 for (auto &pair : parameters) {
157511 auto &name = pair.first;
157512 if (!values.count(name)) {
157513 missing_set.insert(name);
157514 }
157515 }
157516 vector<string> missing_values;
157517 for (auto &val : missing_set) {
157518 missing_values.push_back(val);
157519 }
157520 return StringUtil::Format(
"Values were not provided for the following prepared statement parameters: %s",
157522 }
157523
157524 template <class PAYLOAD>
157525 static void VerifyParameters(const case_insensitive_map_t<PAYLOAD> &provided,
157526 const case_insensitive_map_t<idx_t> &expected) {
157527 if (expected.size() == provided.size()) {
157528
157529 for (auto &pair : expected) {
157530 auto &identifier = pair.first;
157531 if (!provided.count(identifier)) {
157532 throw InvalidInputException(MissingValuesException(expected, provided));
157533 }
157534 }
157535 return;
157536 }
157537
157538 if (expected.size() > provided.size()) {
157539 throw InvalidInputException(MissingValuesException(expected, provided));
157540 } else {
157541 D_ASSERT(provided.size() > expected.size());
157542 throw InvalidInputException(ExcessValuesException(expected, provided));
157543 }
157544 }
157545
157547 static bool CanCachePlan(const LogicalOperator &op);
157548
157549private:
157550 unique_ptr<PendingQueryResult> PendingQueryRecursive(vector<Value> &values) {
157551 return PendingQuery(values);
157552 }
157553
157554 template <typename T, typename... ARGS>
157555 unique_ptr<PendingQueryResult> PendingQueryRecursive(vector<Value> &values, T value, ARGS... args) {
157556 values.push_back(Value::CreateValue<T>(value));
157557 return PendingQueryRecursive(values, args...);
157558 }
157559
157560 unique_ptr<QueryResult> ExecuteRecursive(vector<Value> &values) {
157561 return Execute(values);
157562 }
157563
157564 template <typename T, typename... ARGS>
157565 unique_ptr<QueryResult> ExecuteRecursive(vector<Value> &values, T value, ARGS... args) {
157566 values.push_back(Value::CreateValue<T>(value));
157567 return ExecuteRecursive(values, args...);
157568 }
157569};
157570
157571}
157572
157573
157574
157575
157576
157577
157578
157579
157580
157581
157582
157583
157584
157585
157586
157587
157588
157589
157590
157591
157592
157593
157594
157595
157596
157597namespace duckdb {
157598
157599
157600
157601
157602enum class JoinType :
uint8_t {
157603 INVALID = 0,
157604 LEFT = 1,
157605 RIGHT = 2,
157606 INNER = 3,
157607 OUTER = 4,
157608 SEMI = 5,
157609 ANTI = 6,
157610 MARK = 7,
157611
157612 SINGLE = 8,
157613
157614 RIGHT_SEMI = 9,
157615
157616 RIGHT_ANTI = 10
157617
157618};
157619
157622
157625
157628
157631
157634
157635
157636string JoinTypeToString(JoinType type);
157637
157638}
157639
157640
157641
157642
157643
157644
157645
157646
157647
157648
157649
157650
157651
157652namespace duckdb {
157653
157654
157655
157656
157657enum class RelationType :
uint8_t {
157658 INVALID_RELATION,
157659 TABLE_RELATION,
157660 PROJECTION_RELATION,
157661 FILTER_RELATION,
157662 EXPLAIN_RELATION,
157663 CROSS_PRODUCT_RELATION,
157664 JOIN_RELATION,
157665 AGGREGATE_RELATION,
157666 SET_OPERATION_RELATION,
157667 DISTINCT_RELATION,
157668 LIMIT_RELATION,
157669 ORDER_RELATION,
157670 CREATE_VIEW_RELATION,
157671 CREATE_TABLE_RELATION,
157672 INSERT_RELATION,
157673 VALUE_LIST_RELATION,
157674 MATERIALIZED_RELATION,
157675 DELETE_RELATION,
157676 UPDATE_RELATION,
157677 WRITE_CSV_RELATION,
157678 WRITE_PARQUET_RELATION,
157679 READ_CSV_RELATION,
157680 SUBQUERY_RELATION,
157681 TABLE_FUNCTION_RELATION,
157682 VIEW_RELATION,
157683 QUERY_RELATION,
157684 DELIM_JOIN_RELATION,
157685 DELIM_GET_RELATION,
157686 EXTENSION_RELATION = 255
157687};
157688
157689string RelationTypeToString(RelationType type);
157690
157691}
157692
157693
157694
157695
157696
157697
157698
157699
157700
157701
157702
157703
157704
157705
157706namespace duckdb {
157707
157708
157709
157710
157711enum class JoinRefType :
uint8_t {
157712 REGULAR,
157713 NATURAL,
157714 CROSS,
157715 POSITIONAL,
157716 ASOF,
157717 DEPENDENT,
157718};
157719
157720const char *ToString(JoinRefType value);
157721
157722}
157723
157724
157725
157726
157727
157728
157729
157730
157731
157732
157733
157734
157735
157736
157737
157738
157739
157740
157741
157742
157743
157744
157745
157746
157747
157748
157749
157750
157751
157752
157753
157754
157755
157756
157757
157758
157759
157760
157761
157762
157763
157764
157765
157766
157767
157768
157769
157770
157771
157772namespace duckdb {
157773class ClientContext;
157774
157775class DefaultGenerator {
157776public:
157777 explicit DefaultGenerator(Catalog &catalog);
157778 virtual ~DefaultGenerator();
157779
157780 Catalog &catalog;
157781 atomic<bool> created_all_entries;
157782
157783public:
157785 virtual unique_ptr<CatalogEntry> CreateDefaultEntry(ClientContext &context, const string &entry_name);
157786 virtual unique_ptr<CatalogEntry> CreateDefaultEntry(CatalogTransaction transaction, const string &entry_name);
157788 virtual vector<string> GetDefaultEntries() = 0;
157792 virtual bool LockDuringCreate() const {
157793 return false;
157794 }
157795};
157796
157797}
157798
157799
157800
157801
157802
157803
157804
157805
157806
157807
157808
157809
157810
157811
157812
157813
157814
157815
157816
157817
157818
157819
157820
157821
157822
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
157860namespace duckdb {
157861class CatalogEntry;
157862
157863struct CatalogEntryHashFunction {
157865 std::hash<void *> hash_func;
157866 return hash_func((void *)&a.get());
157867 }
157868};
157869
157870struct CatalogEntryEquality {
157871 bool operator()(
const reference<CatalogEntry> &a,
const reference<CatalogEntry> &b)
const {
157873 }
157874};
157875
157876using catalog_entry_set_t = unordered_set<reference<CatalogEntry>, CatalogEntryHashFunction, CatalogEntryEquality>;
157877
157878template <typename T>
157879using catalog_entry_map_t = unordered_map<reference<CatalogEntry>, T, CatalogEntryHashFunction, CatalogEntryEquality>;
157880
157881using catalog_entry_vector_t = vector<reference<CatalogEntry>>;
157882
157883}
157884
157885
157886
157887
157888
157889
157890
157891
157892
157893
157894
157895
157896
157897
157898
157899
157900
157901namespace duckdb {
157902class CatalogEntry;
157903
157904struct DependencyFlags {
157905public:
157906 DependencyFlags() : value(0) {
157907 }
157908 DependencyFlags(const DependencyFlags &other) : value(other.value) {
157909 }
157910 virtual ~DependencyFlags() = default;
157911 DependencyFlags &
operator=(
const DependencyFlags &other) {
157912 value = other.value;
157913 return *this;
157914 }
157915 bool operator==(
const DependencyFlags &other)
const {
157916 return other.value == value;
157917 }
157918 bool operator!=(
const DependencyFlags &other)
const {
157919 return !(*this == other);
157920 }
157921
157922public:
157923 virtual string ToString() const = 0;
157924
157925protected:
157926 template <uint8_t BIT>
157927 bool IsSet() const {
157928 static const uint8_t FLAG = (1 << BIT);
157929 return (value & FLAG) == FLAG;
157930 }
157931 template <uint8_t BIT>
157932 void Set() {
157933 static const uint8_t FLAG = (1 << BIT);
157934 value |= FLAG;
157935 }
157936 void Merge(uint8_t other) {
157937 value |= other;
157938 }
157940 return value;
157941 }
157942
157943private:
157945};
157946
157947struct DependencySubjectFlags : public DependencyFlags {
157948private:
157949 static constexpr uint8_t OWNERSHIP = 0;
157950
157951public:
157952 DependencySubjectFlags &Apply(DependencySubjectFlags other) {
157953 Merge(other.Value());
157954 return *this;
157955 }
157956
157957public:
157958 bool IsOwnership() const {
157959 return IsSet<OWNERSHIP>();
157960 }
157961
157962public:
157963 DependencySubjectFlags &SetOwnership() {
157964 Set<OWNERSHIP>();
157965 return *this;
157966 }
157967
157968public:
157969 string ToString() const override {
157970 string result;
157971 if (IsOwnership()) {
157972 result += "OWNS";
157973 }
157974 return result;
157975 }
157976};
157977
157978struct DependencyDependentFlags : public DependencyFlags {
157979private:
157980 static constexpr uint8_t BLOCKING = 0;
157981 static constexpr uint8_t OWNED_BY = 1;
157982
157983public:
157984 DependencyDependentFlags &Apply(DependencyDependentFlags other) {
157985 Merge(other.Value());
157986 return *this;
157987 }
157988
157989public:
157990 bool IsBlocking() const {
157991 return IsSet<BLOCKING>();
157992 }
157993 bool IsOwnedBy() const {
157994 return IsSet<OWNED_BY>();
157995 }
157996
157997public:
157998 DependencyDependentFlags &SetBlocking() {
157999 Set<BLOCKING>();
158000 return *this;
158001 }
158002 DependencyDependentFlags &SetOwnedBy() {
158003 Set<OWNED_BY>();
158004 return *this;
158005 }
158006
158007public:
158008 string ToString() const override {
158009 string result;
158010 if (IsBlocking()) {
158011 result += "REGULAR";
158012 } else {
158013 result += "AUTOMATIC";
158014 }
158015 result += " | ";
158016 if (IsOwnedBy()) {
158017 result += "OWNED BY";
158018 }
158019 return result;
158020 }
158021};
158022
158023struct CatalogEntryInfo {
158024public:
158025 CatalogType type;
158026 string schema;
158027 string name;
158028
158029public:
158030 bool operator==(
const CatalogEntryInfo &other)
const {
158031 if (other.type != type) {
158032 return false;
158033 }
158035 return false;
158036 }
158038 return false;
158039 }
158040 return true;
158041 }
158042
158043public:
158044 void Serialize(Serializer &serializer) const;
158045 static CatalogEntryInfo Deserialize(Deserializer &deserializer);
158046};
158047
158048struct Dependency {
158049 Dependency(CatalogEntry &entry,
158050 DependencyDependentFlags flags = DependencyDependentFlags().SetBlocking())
158051 : entry(entry), flags(std::move(flags)) {
158052 }
158053
158055 reference<CatalogEntry> entry;
158057 DependencyDependentFlags flags;
158058};
158059
158060struct DependencyHashFunction {
158062 std::hash<void *> hash_func;
158063 return hash_func((void *)&a.entry.get());
158064 }
158065};
158066
158067struct DependencyEquality {
158068 bool operator()(
const Dependency &a,
const Dependency &b)
const {
158070 }
158071};
158072using dependency_set_t = unordered_set<Dependency, DependencyHashFunction, DependencyEquality>;
158073
158074}
158075
158076
158077namespace duckdb {
158078class Catalog;
158079class CatalogEntry;
158080struct CreateInfo;
158081class SchemaCatalogEntry;
158082struct CatalogTransaction;
158083class LogicalDependencyList;
158084
158087struct LogicalDependency {
158088public:
158089 CatalogEntryInfo entry;
158090 string catalog;
158091
158092public:
158093 explicit LogicalDependency(CatalogEntry &entry);
158094 LogicalDependency();
158095 LogicalDependency(optional_ptr<Catalog> catalog, CatalogEntryInfo entry, string catalog_str);
158096 bool operator==(
const LogicalDependency &other)
const;
158097
158098public:
158099 void Serialize(Serializer &serializer) const;
158100 static LogicalDependency Deserialize(Deserializer &deserializer);
158101};
158102
158103struct LogicalDependencyHashFunction {
158105};
158106
158107struct LogicalDependencyEquality {
158108 bool operator()(
const LogicalDependency &a,
const LogicalDependency &b)
const;
158109};
158110
158112class LogicalDependencyList {
158113 using create_info_set_t =
158114 unordered_set<LogicalDependency, LogicalDependencyHashFunction, LogicalDependencyEquality>;
158115
158116public:
158117 DUCKDB_API void AddDependency(CatalogEntry &entry);
158118 DUCKDB_API void AddDependency(const LogicalDependency &entry);
158119 DUCKDB_API bool Contains(CatalogEntry &entry);
158120
158121public:
158122 DUCKDB_API void VerifyDependencies(Catalog &catalog, const string &name);
158123 void Serialize(Serializer &serializer) const;
158124 static LogicalDependencyList Deserialize(Deserializer &deserializer);
158125 bool operator==(
const LogicalDependencyList &other)
const;
158126 const create_info_set_t &Set() const;
158127
158128private:
158129 create_info_set_t set;
158130};
158131
158132}
158133
158134
158135namespace duckdb {
158136class SchemaCatalogEntry;
158137
158139class StandardEntry : public InCatalogEntry {
158140public:
158141 StandardEntry(CatalogType type, SchemaCatalogEntry &schema, Catalog &catalog, string name)
158142 : InCatalogEntry(type, catalog, std::move(name)), schema(schema) {
158143 }
158144 ~StandardEntry() override {
158145 }
158146
158148 SchemaCatalogEntry &schema;
158150 LogicalDependencyList dependencies;
158151
158152public:
158153 SchemaCatalogEntry &ParentSchema() override {
158154 return schema;
158155 }
158156 const SchemaCatalogEntry &ParentSchema() const override {
158157 return schema;
158158 }
158159};
158160
158161}
158162
158163
158164
158165
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
158194
158195
158196
158197
158198namespace duckdb {
158199
158200enum class CatalogType :
uint8_t;
158201
158202enum class ParseInfoType :
uint8_t {
158203 ALTER_INFO,
158204 ATTACH_INFO,
158205 COPY_INFO,
158206 CREATE_INFO,
158207 CREATE_SECRET_INFO,
158208 DETACH_INFO,
158209 DROP_INFO,
158210 BOUND_EXPORT_DATA,
158211 LOAD_INFO,
158212 PRAGMA_INFO,
158213 SHOW_SELECT_INFO,
158214 TRANSACTION_INFO,
158215 VACUUM_INFO,
158216 COMMENT_ON_INFO,
158217 COMMENT_ON_COLUMN_INFO,
158218 COPY_DATABASE_INFO,
158219 UPDATE_EXTENSIONS_INFO
158220};
158221
158222struct ParseInfo {
158223 explicit ParseInfo(ParseInfoType info_type) : info_type(info_type) {
158224 }
158225 virtual ~ParseInfo() {
158226 }
158227
158228 ParseInfoType info_type;
158229
158230public:
158231 template <class TARGET>
158232 TARGET &Cast() {
158233 DynamicCastCheck<TARGET>(this);
158234 return reinterpret_cast<TARGET &>(*this);
158235 }
158236
158237 template <class TARGET>
158238 const TARGET &Cast() const {
158239 DynamicCastCheck<TARGET>(this);
158240 return reinterpret_cast<const TARGET &>(*this);
158241 }
158242
158243 virtual void Serialize(Serializer &serializer) const;
158244 static unique_ptr<ParseInfo> Deserialize(Deserializer &deserializer);
158245 static string QualifierToString(const string &catalog, const string &schema, const string &name);
158246 static string TypeToString(CatalogType type);
158247};
158248
158249}
158250
158251
158252
158253
158254
158255
158256
158257
158258
158259
158260
158261
158262
158263
158264namespace duckdb {
158265
158266enum class OnCreateConflict :
uint8_t {
158267
158268 ERROR_ON_CONFLICT,
158269
158270 IGNORE_ON_CONFLICT,
158271
158272 REPLACE_ON_CONFLICT,
158273
158274 ALTER_ON_CONFLICT
158275};
158276
158277}
158278
158279
158280
158281
158282namespace duckdb {
158283struct AlterInfo;
158284
158285struct CreateInfo : public ParseInfo {
158286public:
158287 static constexpr const ParseInfoType
TYPE = ParseInfoType::CREATE_INFO;
158288
158289public:
158290 explicit CreateInfo(CatalogType type, string schema = DEFAULT_SCHEMA, string catalog_p = INVALID_CATALOG)
158291 : ParseInfo(
TYPE), type(type), catalog(std::move(catalog_p)), schema(std::move(schema)),
158292 on_conflict(OnCreateConflict::ERROR_ON_CONFLICT), temporary(false), internal(false) {
158293 }
158294 ~CreateInfo() override {
158295 }
158296
158298 CatalogType type;
158300 string catalog;
158302 string schema;
158304 OnCreateConflict on_conflict;
158306 bool temporary;
158308 bool internal;
158310 string sql;
158312 LogicalDependencyList dependencies;
158314 Value comment;
158316 InsertionOrderPreservingMap<string> tags;
158317
158318public:
158319 void Serialize(Serializer &serializer) const override;
158320 static unique_ptr<CreateInfo> Deserialize(Deserializer &deserializer);
158321
158322 virtual unique_ptr<CreateInfo> Copy() const = 0;
158323
158324 DUCKDB_API void CopyProperties(CreateInfo &other) const;
158326 DUCKDB_API virtual unique_ptr<AlterInfo> GetAlterInfo() const;
158328 DUCKDB_API string GetCreatePrefix(const string &entry) const;
158329
158330 virtual string ToString() const {
158331 throw NotImplementedException("ToString not supported for this type of CreateInfo: '%s'",
158332 EnumUtil::ToString(info_type));
158333 }
158334};
158335
158336}
158337
158338
158339namespace duckdb {
158340
158341enum class SequenceInfo :
uint8_t {
158342
158343 SEQ_START,
158344
158345 SEQ_INC,
158346
158347 SEQ_MIN,
158348
158349 SEQ_MAX,
158350
158351 SEQ_CYCLE,
158352
158353 SEQ_OWN
158354};
158355
158356struct CreateSequenceInfo : public CreateInfo {
158357 CreateSequenceInfo();
158358
158360 string name;
158372 bool cycle;
158373
158374public:
158375 unique_ptr<CreateInfo> Copy() const override;
158376
158377public:
158378 DUCKDB_API void Serialize(Serializer &serializer) const override;
158379 DUCKDB_API static unique_ptr<CreateInfo> Deserialize(Deserializer &deserializer);
158380
158381 string ToString() const override;
158382};
158383
158384}
158385
158386
158387
158388
158389
158390
158391
158392
158393
158394
158395
158396
158397
158398
158399
158400
158401
158402
158403
158404
158405
158406
158407
158408
158409
158410
158411namespace duckdb {
158412
158413enum class AlterType :
uint8_t {
158414 INVALID = 0,
158415 ALTER_TABLE = 1,
158416 ALTER_VIEW = 2,
158417 ALTER_SEQUENCE = 3,
158418 CHANGE_OWNERSHIP = 4,
158419 ALTER_SCALAR_FUNCTION = 5,
158420 ALTER_TABLE_FUNCTION = 6,
158421 SET_COMMENT = 7,
158422 SET_COLUMN_COMMENT = 8,
158423 ALTER_DATABASE = 9
158424};
158425
158426struct AlterEntryData {
158427 AlterEntryData() {
158428 }
158429 AlterEntryData(string catalog_p, string schema_p, string name_p, OnEntryNotFound if_not_found)
158430 : catalog(std::move(catalog_p)), schema(std::move(schema_p)), name(std::move(name_p)),
158431 if_not_found(if_not_found) {
158432 }
158433
158434 string catalog;
158435 string schema;
158436 string name;
158437 OnEntryNotFound if_not_found;
158438};
158439
158440struct AlterInfo : public ParseInfo {
158441public:
158442 static constexpr const ParseInfoType
TYPE = ParseInfoType::ALTER_INFO;
158443
158444public:
158445 AlterInfo(AlterType type, string catalog, string schema, string name, OnEntryNotFound if_not_found);
158446 ~AlterInfo() override;
158447
158448 AlterType type;
158450 OnEntryNotFound if_not_found;
158452 string catalog;
158454 string schema;
158456 string name;
158458 bool allow_internal;
158460 unique_ptr<LogicalDependencyList> new_dependencies;
158461
158462public:
158463 virtual CatalogType GetCatalogType() const = 0;
158464 virtual unique_ptr<AlterInfo> Copy() const = 0;
158465 virtual string ToString() const = 0;
158466
158467 void Serialize(Serializer &serializer) const override;
158468 static unique_ptr<ParseInfo> Deserialize(Deserializer &deserializer);
158469
158470 virtual string GetColumnName() const {
158471 return "";
158472 };
158473
158474 AlterEntryData GetAlterEntryData() const;
158475 bool IsAddPrimaryKey() const;
158476
158477protected:
158478 explicit AlterInfo(AlterType type);
158479};
158480
158481}
158482
158483
158484
158485
158486
158487
158488
158489
158490
158491
158492
158493
158494
158495
158496
158497
158498namespace duckdb {
158499
158500class Serializer;
158501class Deserializer;
158502
158503
158504
158505
158506enum class ConstraintType :
uint8_t {
158507 INVALID = 0,
158508 NOT_NULL = 1,
158509 CHECK = 2,
158510 UNIQUE = 3,
158511 FOREIGN_KEY = 4,
158512};
158513
158514enum class ForeignKeyType :
uint8_t {
158515 FK_TYPE_PRIMARY_KEY_TABLE = 0,
158516 FK_TYPE_FOREIGN_KEY_TABLE = 1,
158517 FK_TYPE_SELF_REFERENCE_TABLE = 2
158518};
158519
158520struct ForeignKeyInfo {
158521 ForeignKeyType type;
158522 string schema;
158525 string table;
158527 vector<PhysicalIndex> pk_keys;
158529 vector<PhysicalIndex> fk_keys;
158530
158531 bool IsDeleteConstraint() const {
158532 return type == ForeignKeyType::FK_TYPE_PRIMARY_KEY_TABLE ||
158533 type == ForeignKeyType::FK_TYPE_SELF_REFERENCE_TABLE;
158534 }
158535 bool IsAppendConstraint() const {
158536 return type == ForeignKeyType::FK_TYPE_FOREIGN_KEY_TABLE ||
158537 type == ForeignKeyType::FK_TYPE_SELF_REFERENCE_TABLE;
158538 }
158539};
158540
158542class Constraint {
158543public:
158544 DUCKDB_API explicit Constraint(ConstraintType type);
158545 DUCKDB_API virtual ~Constraint();
158546
158547 ConstraintType type;
158548
158549public:
158550 DUCKDB_API virtual string ToString() const = 0;
158551 DUCKDB_API void Print() const;
158552
158553 DUCKDB_API virtual unique_ptr<Constraint> Copy() const = 0;
158554
158555 DUCKDB_API virtual void Serialize(Serializer &serializer) const;
158556 DUCKDB_API static unique_ptr<Constraint> Deserialize(Deserializer &deserializer);
158557
158558public:
158559 template <class TARGET>
158560 TARGET &Cast() {
158561 if (type != TARGET::TYPE) {
158562 throw InternalException("Failed to cast constraint to type - constraint type mismatch");
158563 }
158564 return reinterpret_cast<TARGET &>(*this);
158565 }
158566
158567 template <class TARGET>
158568 const TARGET &Cast() const {
158569 if (type != TARGET::TYPE) {
158570 throw InternalException("Failed to cast constraint to type - constraint type mismatch");
158571 }
158572 return reinterpret_cast<const TARGET &>(*this);
158573 }
158574};
158575}
158576
158577
158578
158579namespace duckdb {
158580
158581enum class AlterForeignKeyType :
uint8_t { AFT_ADD = 0, AFT_DELETE = 1 };
158582
158583
158584
158585
158586struct ChangeOwnershipInfo : public AlterInfo {
158587 ChangeOwnershipInfo(CatalogType entry_catalog_type, string entry_catalog, string entry_schema, string entry_name,
158588 string owner_schema, string owner_name, OnEntryNotFound if_not_found);
158589
158590
158591
158592
158593 CatalogType entry_catalog_type;
158594
158595 string owner_schema;
158596 string owner_name;
158597
158598public:
158599 CatalogType GetCatalogType() const override;
158600 unique_ptr<AlterInfo> Copy() const override;
158601 string ToString() const override;
158602
158603 void Serialize(Serializer &serializer) const override;
158604 static unique_ptr<AlterInfo> Deserialize(Deserializer &deserializer);
158605
158606 explicit ChangeOwnershipInfo();
158607};
158608
158609
158610
158611
158612struct SetCommentInfo : public AlterInfo {
158613 SetCommentInfo(CatalogType entry_catalog_type, string entry_catalog, string entry_schema, string entry_name,
158614 Value new_comment_value_p, OnEntryNotFound if_not_found);
158615
158616 CatalogType entry_catalog_type;
158617 Value comment_value;
158618
158619public:
158620 CatalogType GetCatalogType() const override;
158621 unique_ptr<AlterInfo> Copy() const override;
158622 string ToString() const override;
158623
158624 void Serialize(Serializer &serializer) const override;
158625 static unique_ptr<AlterInfo> Deserialize(Deserializer &deserializer);
158626
158627 explicit SetCommentInfo();
158628};
158629
158630
158631
158632
158633enum class AlterTableType :
uint8_t {
158634 INVALID = 0,
158635 RENAME_COLUMN = 1,
158636 RENAME_TABLE = 2,
158637 ADD_COLUMN = 3,
158638 REMOVE_COLUMN = 4,
158639 ALTER_COLUMN_TYPE = 5,
158640 SET_DEFAULT = 6,
158641 FOREIGN_KEY_CONSTRAINT = 7,
158642 SET_NOT_NULL = 8,
158643 DROP_NOT_NULL = 9,
158644 SET_COLUMN_COMMENT = 10,
158645 ADD_CONSTRAINT = 11,
158646 SET_PARTITIONED_BY = 12,
158647 SET_SORTED_BY = 13,
158648 ADD_FIELD = 14,
158649 REMOVE_FIELD = 15,
158650 RENAME_FIELD = 16,
158651 SET_TABLE_OPTIONS = 17,
158652 RESET_TABLE_OPTIONS = 18,
158653};
158654
158655struct AlterTableInfo : public AlterInfo {
158656 AlterTableInfo(AlterTableType type, AlterEntryData data);
158657 ~AlterTableInfo() override;
158658
158659 AlterTableType alter_table_type;
158660
158661public:
158662 CatalogType GetCatalogType() const override;
158663
158664 void Serialize(Serializer &serializer) const override;
158665 static unique_ptr<AlterInfo> Deserialize(Deserializer &deserializer);
158666
158667protected:
158668 explicit AlterTableInfo(AlterTableType type);
158669};
158670
158671
158672
158673
158674struct RenameColumnInfo : public AlterTableInfo {
158675 RenameColumnInfo(AlterEntryData data, string old_name_p, string new_name_p);
158676 ~RenameColumnInfo() override;
158677
158679 string old_name;
158681 string new_name;
158682
158683public:
158684 unique_ptr<AlterInfo> Copy() const override;
158685 string ToString() const override;
158686
158687 void Serialize(Serializer &serializer) const override;
158688 static unique_ptr<AlterTableInfo> Deserialize(Deserializer &deserializer);
158689
158690private:
158691 RenameColumnInfo();
158692};
158693
158694
158695
158696
158697struct RenameFieldInfo : public AlterTableInfo {
158698 RenameFieldInfo(AlterEntryData data, vector<string> column_path, string new_name_p);
158699 ~RenameFieldInfo() override;
158700
158702 vector<string> column_path;
158704 string new_name;
158705
158706public:
158707 unique_ptr<AlterInfo> Copy() const override;
158708 string ToString() const override;
158709 string GetColumnName() const override {
158710 return column_path[0];
158711 }
158712
158713 void Serialize(Serializer &serializer) const override;
158714 static unique_ptr<AlterTableInfo> Deserialize(Deserializer &deserializer);
158715
158716private:
158717 RenameFieldInfo();
158718};
158719
158720
158721
158722
158723struct RenameTableInfo : public AlterTableInfo {
158724 RenameTableInfo(AlterEntryData data, string new_name);
158725 ~RenameTableInfo() override;
158726
158728 string new_table_name;
158729
158730public:
158731 unique_ptr<AlterInfo> Copy() const override;
158732 string ToString() const override;
158733
158734 void Serialize(Serializer &serializer) const override;
158735 static unique_ptr<AlterTableInfo> Deserialize(Deserializer &deserializer);
158736
158737private:
158738 RenameTableInfo();
158739};
158740
158741
158742
158743
158744struct AddColumnInfo : public AlterTableInfo {
158745 AddColumnInfo(AlterEntryData data, ColumnDefinition new_column, bool if_column_not_exists);
158746 ~AddColumnInfo() override;
158747
158749 ColumnDefinition new_column;
158751 bool if_column_not_exists;
158752
158753public:
158754 unique_ptr<AlterInfo> Copy() const override;
158755 string ToString() const override;
158756
158757 void Serialize(Serializer &serializer) const override;
158758 static unique_ptr<AlterTableInfo> Deserialize(Deserializer &deserializer);
158759
158760private:
158761 explicit AddColumnInfo(ColumnDefinition new_column);
158762};
158763
158764
158765
158766
158767struct AddFieldInfo : public AlterTableInfo {
158768 AddFieldInfo(AlterEntryData data, vector<string> column_path, ColumnDefinition new_field, bool if_field_not_exists);
158769 ~AddFieldInfo() override;
158770
158772 vector<string> column_path;
158774 ColumnDefinition new_field;
158776 bool if_field_not_exists;
158777
158778public:
158779 unique_ptr<AlterInfo> Copy() const override;
158780 string ToString() const override;
158781 string GetColumnName() const override {
158782 return column_path[0];
158783 }
158784
158785 void Serialize(Serializer &serializer) const override;
158786 static unique_ptr<AlterTableInfo> Deserialize(Deserializer &deserializer);
158787
158788private:
158789 explicit AddFieldInfo(ColumnDefinition new_column);
158790};
158791
158792
158793
158794
158795struct RemoveColumnInfo : public AlterTableInfo {
158796 RemoveColumnInfo(AlterEntryData data, string removed_column, bool if_column_exists, bool cascade);
158797 ~RemoveColumnInfo() override;
158798
158800 string removed_column;
158802 bool if_column_exists;
158804 bool cascade;
158805
158806public:
158807 unique_ptr<AlterInfo> Copy() const override;
158808 string ToString() const override;
158809 void Serialize(Serializer &serializer) const override;
158810 static unique_ptr<AlterTableInfo> Deserialize(Deserializer &deserializer);
158811 string GetColumnName() const override {
158812 return removed_column;
158813 }
158814
158815private:
158816 RemoveColumnInfo();
158817};
158818
158819
158820
158821
158822struct RemoveFieldInfo : public AlterTableInfo {
158823 RemoveFieldInfo(AlterEntryData data, vector<string> column_path, bool if_column_exists, bool cascade);
158824 ~RemoveFieldInfo() override;
158825
158827 vector<string> column_path;
158829 bool if_column_exists;
158831 bool cascade;
158832
158833public:
158834 unique_ptr<AlterInfo> Copy() const override;
158835 string ToString() const override;
158836 string GetColumnName() const override {
158837 return column_path[0];
158838 }
158839
158840 void Serialize(Serializer &serializer) const override;
158841 static unique_ptr<AlterTableInfo> Deserialize(Deserializer &deserializer);
158842
158843private:
158844 RemoveFieldInfo();
158845};
158846
158847
158848
158849struct ChangeColumnTypeInfo : public AlterTableInfo {
158850 ChangeColumnTypeInfo(AlterEntryData data, string column_name, LogicalType target_type,
158851 unique_ptr<ParsedExpression> expression);
158852 ~ChangeColumnTypeInfo() override;
158853
158855 string column_name;
158857 LogicalType target_type;
158859 unique_ptr<ParsedExpression> expression;
158860
158861public:
158862 unique_ptr<AlterInfo> Copy() const override;
158863 string ToString() const override;
158864 void Serialize(Serializer &serializer) const override;
158865 static unique_ptr<AlterTableInfo> Deserialize(Deserializer &deserializer);
158866 string GetColumnName() const override {
158867 return column_name;
158868 };
158869
158870private:
158871 ChangeColumnTypeInfo();
158872};
158873
158874
158875
158876
158877struct SetDefaultInfo : public AlterTableInfo {
158878 SetDefaultInfo(AlterEntryData data, string column_name, unique_ptr<ParsedExpression> new_default);
158879 ~SetDefaultInfo() override;
158880
158882 string column_name;
158884 unique_ptr<ParsedExpression> expression;
158885
158886public:
158887 unique_ptr<AlterInfo> Copy() const override;
158888 string ToString() const override;
158889 void Serialize(Serializer &serializer) const override;
158890 static unique_ptr<AlterTableInfo> Deserialize(Deserializer &deserializer);
158891
158892private:
158893 SetDefaultInfo();
158894};
158895
158896
158897
158898
158899struct AlterForeignKeyInfo : public AlterTableInfo {
158900 AlterForeignKeyInfo(AlterEntryData data, string fk_table, vector<string> pk_columns, vector<string> fk_columns,
158901 vector<PhysicalIndex> pk_keys, vector<PhysicalIndex> fk_keys, AlterForeignKeyType type);
158902 ~AlterForeignKeyInfo() override;
158903
158904 string fk_table;
158905 vector<string> pk_columns;
158906 vector<string> fk_columns;
158907 vector<PhysicalIndex> pk_keys;
158908 vector<PhysicalIndex> fk_keys;
158909 AlterForeignKeyType type;
158910
158911public:
158912 unique_ptr<AlterInfo> Copy() const override;
158913 string ToString() const override;
158914 void Serialize(Serializer &serializer) const override;
158915 static unique_ptr<AlterTableInfo> Deserialize(Deserializer &deserializer);
158916
158917private:
158918 AlterForeignKeyInfo();
158919};
158920
158921
158922
158923
158924struct SetNotNullInfo : public AlterTableInfo {
158925 SetNotNullInfo(AlterEntryData data, string column_name);
158926 ~SetNotNullInfo() override;
158927
158929 string column_name;
158930
158931public:
158932 unique_ptr<AlterInfo> Copy() const override;
158933 string ToString() const override;
158934 void Serialize(Serializer &serializer) const override;
158935 static unique_ptr<AlterTableInfo> Deserialize(Deserializer &deserializer);
158936
158937private:
158938 SetNotNullInfo();
158939};
158940
158941
158942
158943
158944struct DropNotNullInfo : public AlterTableInfo {
158945 DropNotNullInfo(AlterEntryData data, string column_name);
158946 ~DropNotNullInfo() override;
158947
158949 string column_name;
158950
158951public:
158952 unique_ptr<AlterInfo> Copy() const override;
158953 string ToString() const override;
158954 void Serialize(Serializer &serializer) const override;
158955 static unique_ptr<AlterTableInfo> Deserialize(Deserializer &deserializer);
158956
158957private:
158958 DropNotNullInfo();
158959};
158960
158961
158962
158963
158964enum class AlterViewType :
uint8_t { INVALID = 0, RENAME_VIEW = 1 };
158965
158966struct AlterViewInfo : public AlterInfo {
158967 AlterViewInfo(AlterViewType type, AlterEntryData data);
158968 ~AlterViewInfo() override;
158969
158970 AlterViewType alter_view_type;
158971
158972public:
158973 CatalogType GetCatalogType() const override;
158974 void Serialize(Serializer &serializer) const override;
158975 static unique_ptr<AlterInfo> Deserialize(Deserializer &deserializer);
158976
158977protected:
158978 explicit AlterViewInfo(AlterViewType type);
158979};
158980
158981
158982
158983
158984struct RenameViewInfo : public AlterViewInfo {
158985 RenameViewInfo(AlterEntryData data, string new_name);
158986 ~RenameViewInfo() override;
158987
158989 string new_view_name;
158990
158991public:
158992 unique_ptr<AlterInfo> Copy() const override;
158993 string ToString() const override;
158994 void Serialize(Serializer &serializer) const override;
158995 static unique_ptr<AlterViewInfo> Deserialize(Deserializer &deserializer);
158996
158997private:
158998 RenameViewInfo();
158999};
159000
159001
159002
159003
159004struct AddConstraintInfo : public AlterTableInfo {
159005 AddConstraintInfo(AlterEntryData data, unique_ptr<Constraint> constraint);
159006 ~AddConstraintInfo() override;
159007
159009 unique_ptr<Constraint> constraint;
159010
159011public:
159012 unique_ptr<AlterInfo> Copy() const override;
159013 string ToString() const override;
159014 void Serialize(Serializer &serializer) const override;
159015 static unique_ptr<AlterTableInfo> Deserialize(Deserializer &deserializer);
159016
159017private:
159018 AddConstraintInfo();
159019};
159020
159021
159022
159023
159024struct SetPartitionedByInfo : public AlterTableInfo {
159025 SetPartitionedByInfo(AlterEntryData data, vector<unique_ptr<ParsedExpression>> partition_keys);
159026 ~SetPartitionedByInfo() override;
159027
159029 vector<unique_ptr<ParsedExpression>> partition_keys;
159030
159031public:
159032 unique_ptr<AlterInfo> Copy() const override;
159033 string ToString() const override;
159034 void Serialize(Serializer &serializer) const override;
159035 static unique_ptr<AlterTableInfo> Deserialize(Deserializer &deserializer);
159036
159037private:
159038 SetPartitionedByInfo();
159039};
159040
159041
159042
159043
159044struct SetSortedByInfo : public AlterTableInfo {
159045 SetSortedByInfo(AlterEntryData data, vector<OrderByNode> orders);
159046 ~SetSortedByInfo() override;
159047
159049 vector<OrderByNode> orders;
159050
159051public:
159052 unique_ptr<AlterInfo> Copy() const override;
159053 string ToString() const override;
159054 void Serialize(Serializer &serializer) const override;
159055 static unique_ptr<AlterTableInfo> Deserialize(Deserializer &deserializer);
159056
159057private:
159058 SetSortedByInfo();
159059};
159060
159061
159062
159063
159064struct SetTableOptionsInfo : public AlterTableInfo {
159065 SetTableOptionsInfo(AlterEntryData data, case_insensitive_map_t<unique_ptr<ParsedExpression>> table_options);
159066 ~SetTableOptionsInfo() override;
159067
159068 case_insensitive_map_t<unique_ptr<ParsedExpression>> table_options;
159069
159070public:
159071 unique_ptr<AlterInfo> Copy() const override;
159072 string ToString() const override;
159073
159074 void Serialize(Serializer &serializer) const override;
159075 static unique_ptr<AlterTableInfo> Deserialize(Deserializer &deserializer);
159076
159077private:
159078 SetTableOptionsInfo();
159079};
159080
159081
159082
159083
159084struct ResetTableOptionsInfo : public AlterTableInfo {
159085 ResetTableOptionsInfo(AlterEntryData data, case_insensitive_set_t table_options);
159086 ~ResetTableOptionsInfo() override;
159087
159088 case_insensitive_set_t table_options;
159089
159090public:
159091 unique_ptr<AlterInfo> Copy() const override;
159092 string ToString() const override;
159093
159094 void Serialize(Serializer &serializer) const override;
159095 static unique_ptr<AlterTableInfo> Deserialize(Deserializer &deserializer);
159096
159097private:
159098 ResetTableOptionsInfo();
159099};
159100
159101}
159102
159103
159104namespace duckdb {
159105class DuckTransaction;
159106class SequenceCatalogEntry;
159107
159108struct SequenceValue {
159109 SequenceCatalogEntry *entry;
159112};
159113
159114struct SequenceData {
159115 explicit SequenceData(CreateSequenceInfo &info);
159116
159132 bool cycle;
159133};
159134
159136class SequenceCatalogEntry : public StandardEntry {
159137public:
159138 static constexpr const CatalogType Type = CatalogType::SEQUENCE_ENTRY;
159139 static constexpr const char *Name = "sequence";
159140
159141public:
159143 SequenceCatalogEntry(Catalog &catalog, SchemaCatalogEntry &schema, CreateSequenceInfo &info);
159144
159145public:
159146 unique_ptr<CatalogEntry> Copy(ClientContext &context) const override;
159147 unique_ptr<CreateInfo> GetInfo() const override;
159148
159149 SequenceData GetData() const;
159151 int64_t NextValue(DuckTransaction &transaction);
159152 void ReplayValue(uint64_t usage_count, int64_t counter);
159153
159154 string ToSQL() const override;
159155
159156private:
159158 mutable mutex lock;
159160 SequenceData data;
159161};
159162}
159163
159164
159165
159166
159167
159168
159169namespace duckdb {
159170class Catalog;
159171class SequenceCatalogEntry;
159172class SchemaCatalogEntry;
159173
159174class AttachedDatabase;
159175class ColumnData;
159176class ClientContext;
159177class CatalogEntry;
159178class DataTable;
159179class DatabaseInstance;
159180class LocalStorage;
159181class MetaTransaction;
159182class TransactionManager;
159183class WriteAheadLog;
159184
159185class ChunkVectorInfo;
159186
159187struct DeleteInfo;
159188struct UpdateInfo;
159189struct DatabaseModificationType;
159190
159193class Transaction {
159194public:
159195 DUCKDB_API Transaction(TransactionManager &manager, ClientContext &context);
159196 DUCKDB_API virtual ~Transaction();
159197
159198 TransactionManager &manager;
159199 weak_ptr<ClientContext> context;
159202 atomic<transaction_t> active_query;
159203
159204public:
159205 DUCKDB_API static Transaction &Get(ClientContext &context, AttachedDatabase &db);
159206 DUCKDB_API static Transaction &Get(ClientContext &context, Catalog &catalog);
159208 DUCKDB_API static optional_ptr<Transaction> TryGet(ClientContext &context, AttachedDatabase &db);
159209
159211 DUCKDB_API bool IsReadOnly();
159213 DUCKDB_API virtual void SetReadWrite();
159215 DUCKDB_API virtual void SetModifications(DatabaseModificationType type);
159216
159217 virtual bool IsDuckTransaction() const {
159218 return false;
159219 }
159220
159221public:
159222 template <class TARGET>
159223 TARGET &Cast() {
159224 DynamicCastCheck<TARGET>(this);
159225 return reinterpret_cast<TARGET &>(*this);
159226 }
159227 template <class TARGET>
159228 const TARGET &Cast() const {
159229 DynamicCastCheck<TARGET>(this);
159230 return reinterpret_cast<const TARGET &>(*this);
159231 }
159232
159233private:
159234 bool is_read_only;
159235};
159236
159237}
159238
159239
159240
159241
159242
159243
159244
159245
159246
159247
159248
159249
159250
159251
159252
159253namespace duckdb {
159254class SchemaCatalogEntry;
159255
159257struct SimilarCatalogEntry {
159259 string name;
159261 double score = 0.0;
159263 optional_ptr<SchemaCatalogEntry> schema;
159264
159265 bool Found() const {
159266 return !name.empty();
159267 }
159268
159269 DUCKDB_API string GetQualifiedName(bool qualify_catalog, bool qualify_schema) const;
159270};
159271
159272}
159273
159274#include <functional>
159275#include <memory>
159276
159277namespace duckdb {
159278struct AlterInfo;
159279struct ChangeOwnershipInfo;
159280
159281class ClientContext;
159282class LogicalDependencyList;
159283
159284class DuckCatalog;
159285class TableCatalogEntry;
159286class SequenceCatalogEntry;
159287
159288class CatalogEntryMap {
159289public:
159290 CatalogEntryMap() {
159291 }
159292
159293public:
159294 void AddEntry(unique_ptr<CatalogEntry> entry);
159295 void UpdateEntry(unique_ptr<CatalogEntry> entry);
159296 void DropEntry(CatalogEntry &entry);
159297 case_insensitive_tree_t<unique_ptr<CatalogEntry>> &Entries();
159298 optional_ptr<CatalogEntry> GetEntry(const string &name);
159299
159300private:
159302 case_insensitive_tree_t<unique_ptr<CatalogEntry>> entries;
159303};
159304
159306class CatalogSet {
159307public:
159308 struct EntryLookup {
159309 enum class FailureReason { SUCCESS, DELETED, NOT_PRESENT, INVISIBLE };
159310 optional_ptr<CatalogEntry> result;
159311 FailureReason reason;
159312 };
159313
159314public:
159315 DUCKDB_API explicit CatalogSet(Catalog &catalog, unique_ptr<DefaultGenerator> defaults = nullptr);
159316 ~CatalogSet();
159317
159320 DUCKDB_API bool CreateEntry(CatalogTransaction transaction, const string &name, unique_ptr<CatalogEntry> value,
159321 const LogicalDependencyList &dependencies);
159322 DUCKDB_API bool CreateEntry(ClientContext &context, const string &name, unique_ptr<CatalogEntry> value,
159323 const LogicalDependencyList &dependencies);
159324
159325 DUCKDB_API bool AlterEntry(CatalogTransaction transaction, const string &name, AlterInfo &alter_info);
159326
159327 DUCKDB_API bool DropEntry(CatalogTransaction transaction, const string &name, bool cascade,
159328 bool allow_drop_internal = false);
159329 DUCKDB_API bool DropEntry(ClientContext &context, const string &name, bool cascade,
159330 bool allow_drop_internal = false);
159332 DUCKDB_API void VerifyExistenceOfDependency(transaction_t commit_id, CatalogEntry &entry);
159334 DUCKDB_API void CommitDrop(transaction_t commit_id, transaction_t start_time, CatalogEntry &entry);
159335
159336 DUCKDB_API DuckCatalog &GetCatalog();
159337
159338 bool AlterOwnership(CatalogTransaction transaction, ChangeOwnershipInfo &info);
159339
159340 void CleanupEntry(CatalogEntry &catalog_entry);
159341
159343 DUCKDB_API EntryLookup GetEntryDetailed(CatalogTransaction transaction, const string &name);
159344 DUCKDB_API optional_ptr<CatalogEntry> GetEntry(CatalogTransaction transaction, const string &name);
159345 DUCKDB_API optional_ptr<CatalogEntry> GetEntry(ClientContext &context, const string &name);
159346
159349 SimilarCatalogEntry SimilarEntry(CatalogTransaction transaction, const string &name);
159350
159353 void Undo(CatalogEntry &entry);
159354
159356 DUCKDB_API void Scan(const std::function<void(CatalogEntry &)> &callback);
159358 DUCKDB_API void ScanWithPrefix(CatalogTransaction transaction, const std::function<void(CatalogEntry &)> &callback,
159359 const string &prefix);
159360 DUCKDB_API void Scan(CatalogTransaction transaction, const std::function<void(CatalogEntry &)> &callback);
159361 DUCKDB_API void ScanWithReturn(CatalogTransaction transaction, const std::function<bool(CatalogEntry &)> &callback);
159362 DUCKDB_API void Scan(ClientContext &context, const std::function<void(CatalogEntry &)> &callback);
159363 DUCKDB_API void ScanWithReturn(ClientContext &context, const std::function<bool(CatalogEntry &)> &callback);
159364
159365 template <class T>
159366 vector<reference<T>> GetEntries(CatalogTransaction transaction) {
159367 vector<reference<T>> result;
159368 Scan(transaction, [&](CatalogEntry &entry) { result.push_back(entry.Cast<T>()); });
159369 return result;
159370 }
159371
159372 DUCKDB_API bool CreatedByOtherActiveTransaction(CatalogTransaction transaction, transaction_t timestamp);
159373 DUCKDB_API bool CommittedAfterStarting(CatalogTransaction transaction, transaction_t timestamp);
159374 DUCKDB_API bool HasConflict(CatalogTransaction transaction, transaction_t timestamp);
159375 DUCKDB_API bool UseTimestamp(CatalogTransaction transaction, transaction_t timestamp);
159376 static bool IsCommitted(transaction_t timestamp);
159377
159378 static void UpdateTimestamp(CatalogEntry &entry, transaction_t timestamp);
159379
159380 mutex &GetCatalogLock() {
159381 return catalog_lock;
159382 }
159383
159384 void Verify(Catalog &catalog);
159385
159387 void SetDefaultGenerator(unique_ptr<DefaultGenerator> defaults);
159388
159389private:
159390 bool DropDependencies(CatalogTransaction transaction, const string &name, bool cascade,
159391 bool allow_drop_internal = false);
159394 CatalogEntry &GetEntryForTransaction(CatalogTransaction transaction, CatalogEntry ¤t, bool &visible);
159396 CatalogEntry &GetEntryForTransaction(CatalogTransaction transaction, CatalogEntry ¤t);
159397 CatalogEntry &GetCommittedEntry(CatalogEntry ¤t);
159398 optional_ptr<CatalogEntry> GetEntryInternal(CatalogTransaction transaction, const string &name);
159399 optional_ptr<CatalogEntry> CreateCommittedEntry(unique_ptr<CatalogEntry> entry);
159400
159402 void CreateDefaultEntries(CatalogTransaction transaction, unique_lock<mutex> &lock);
159404 optional_ptr<CatalogEntry> CreateDefaultEntry(CatalogTransaction transaction, const string &name,
159405 unique_lock<mutex> &lock);
159406
159407 bool DropEntryInternal(CatalogTransaction transaction, const string &name, bool allow_drop_internal = false);
159408
159409 bool CreateEntryInternal(CatalogTransaction transaction, const string &name, unique_ptr<CatalogEntry> value,
159410 unique_lock<mutex> &read_lock, bool should_be_empty = true);
159411 void CheckCatalogEntryInvariants(CatalogEntry &value, const string &name);
159413 bool VerifyVacancy(CatalogTransaction transaction, CatalogEntry &entry);
159415 bool StartChain(CatalogTransaction transaction, const string &name, unique_lock<mutex> &read_lock);
159416 bool RenameEntryInternal(CatalogTransaction transaction, CatalogEntry &old, const string &new_name,
159417 AlterInfo &alter_info, unique_lock<mutex> &read_lock);
159418
159419private:
159420 DuckCatalog &catalog;
159422 mutex catalog_lock;
159423 CatalogEntryMap map;
159425 unique_ptr<DefaultGenerator> defaults;
159426};
159427}
159428
159429
159430
159431namespace duckdb {
159432class ClientContext;
159433
159434class StandardEntry;
159435class TableCatalogEntry;
159436class TableFunctionCatalogEntry;
159437class SequenceCatalogEntry;
159438
159439enum class OnCreateConflict :
uint8_t;
159440
159441struct AlterTableInfo;
159442struct CreateIndexInfo;
159443struct CreateFunctionInfo;
159444struct CreateCollationInfo;
159445struct CreateCoordinateSystemInfo;
159446struct CreateViewInfo;
159447struct BoundCreateTableInfo;
159448struct CreatePragmaFunctionInfo;
159449struct CreateSequenceInfo;
159450struct CreateSchemaInfo;
159451struct CreateTableFunctionInfo;
159452struct CreateCopyFunctionInfo;
159453struct CreateTypeInfo;
159454
159455struct DropInfo;
159456
159458class SchemaCatalogEntry : public InCatalogEntry {
159459public:
159460 static constexpr const CatalogType Type = CatalogType::SCHEMA_ENTRY;
159461 static constexpr const char *Name = "schema";
159462
159463public:
159464 SchemaCatalogEntry(Catalog &catalog, CreateSchemaInfo &info);
159465
159466public:
159467 unique_ptr<CreateInfo> GetInfo() const override;
159468
159470 virtual void Scan(ClientContext &context, CatalogType type,
159471 const std::function<void(CatalogEntry &)> &callback) = 0;
159473 virtual void Scan(CatalogType type, const std::function<void(CatalogEntry &)> &callback) = 0;
159474
159475 string ToSQL() const override;
159476
159478 virtual optional_ptr<CatalogEntry> CreateIndex(CatalogTransaction transaction, CreateIndexInfo &info,
159479 TableCatalogEntry &table) = 0;
159480 optional_ptr<CatalogEntry> CreateIndex(ClientContext &context, CreateIndexInfo &info, TableCatalogEntry &table);
159482 virtual optional_ptr<CatalogEntry> CreateFunction(CatalogTransaction transaction, CreateFunctionInfo &info) = 0;
159484 virtual optional_ptr<CatalogEntry> CreateTable(CatalogTransaction transaction, BoundCreateTableInfo &info) = 0;
159486 virtual optional_ptr<CatalogEntry> CreateView(CatalogTransaction transaction, CreateViewInfo &info) = 0;
159488 virtual optional_ptr<CatalogEntry> CreateSequence(CatalogTransaction transaction, CreateSequenceInfo &info) = 0;
159490 virtual optional_ptr<CatalogEntry> CreateTableFunction(CatalogTransaction transaction,
159491 CreateTableFunctionInfo &info) = 0;
159493 virtual optional_ptr<CatalogEntry> CreateCopyFunction(CatalogTransaction transaction,
159494 CreateCopyFunctionInfo &info) = 0;
159496 virtual optional_ptr<CatalogEntry> CreatePragmaFunction(CatalogTransaction transaction,
159497 CreatePragmaFunctionInfo &info) = 0;
159499 virtual optional_ptr<CatalogEntry> CreateCollation(CatalogTransaction transaction, CreateCollationInfo &info) = 0;
159501 virtual optional_ptr<CatalogEntry> CreateCoordinateSystem(CatalogTransaction transaction,
159502 CreateCoordinateSystemInfo &info) {
159503 throw NotImplementedException("Coordinate systems are not supported in schema '%s'", name);
159504 }
159505
159507 virtual optional_ptr<CatalogEntry> CreateType(CatalogTransaction transaction, CreateTypeInfo &info) = 0;
159508
159510 DUCKDB_API virtual optional_ptr<CatalogEntry> LookupEntry(CatalogTransaction transaction,
159511 const EntryLookupInfo &lookup_info) = 0;
159512 DUCKDB_API virtual CatalogSet::EntryLookup LookupEntryDetailed(CatalogTransaction transaction,
159513 const EntryLookupInfo &lookup_info);
159514 DUCKDB_API virtual SimilarCatalogEntry GetSimilarEntry(CatalogTransaction transaction,
159515 const EntryLookupInfo &lookup_info);
159516
159517 DUCKDB_API optional_ptr<CatalogEntry> GetEntry(CatalogTransaction transaction, CatalogType type,
159518 const string &name);
159519
159521 virtual void DropEntry(ClientContext &context, DropInfo &info) = 0;
159522
159524 virtual void Alter(CatalogTransaction transaction, AlterInfo &info) = 0;
159525
159526 CatalogTransaction GetCatalogTransaction(ClientContext &context);
159527};
159528}
159529
159530
159531
159532
159533
159534
159535
159536
159537
159538
159539
159540
159541
159542
159543
159544
159545
159546
159547#include <deque>
159548
159549namespace duckdb {
159550
159551template <class DATA_TYPE, bool SAFE = true>
159552class deque : public std::deque<DATA_TYPE, std::allocator<DATA_TYPE>> {
159553public:
159554 using original = std::deque<DATA_TYPE, std::allocator<DATA_TYPE>>;
159555 using original::original;
159556 using value_type =
typename original::value_type;
159557 using allocator_type = typename original::allocator_type;
159558 using size_type = typename original::size_type;
159559 using difference_type = typename original::difference_type;
159560 using reference = typename original::reference;
159561 using const_reference = typename original::const_reference;
159562 using pointer = typename original::pointer;
159563 using const_pointer = typename original::const_pointer;
159564 using iterator = typename original::iterator;
159565 using const_iterator = typename original::const_iterator;
159566 using reverse_iterator = typename original::reverse_iterator;
159567 using const_reverse_iterator = typename original::const_reverse_iterator;
159568
159569private:
159570 static inline void AssertIndexInBounds(idx_t index, idx_t size) {
159571#if defined(DUCKDB_DEBUG_NO_SAFETY) || defined(DUCKDB_CLANG_TIDY)
159572 return;
159573#else
159574 if (DUCKDB_UNLIKELY(index >= size)) {
159575 throw InternalException("Attempted to access index %ld within deque of size %ld", index, size);
159576 }
159577#endif
159578 }
159579
159580public:
159581#ifdef DUCKDB_CLANG_TIDY
159582 [[clang::reinitializes]]
159583#endif
159584 inline void
159585 clear() noexcept {
159586 original::clear();
159587 }
159588
159589
159590
159591 deque() = default;
159592 deque(original &&other) : original(std::move(other)) {
159593 }
159594 template <bool INTERNAL_SAFE>
159595 deque(deque<DATA_TYPE, INTERNAL_SAFE> &&other) : original(std::move(other)) {
159596 }
159597
159598 template <bool INTERNAL_SAFE = false>
159599 inline typename original::reference
get(
typename original::size_type __n) {
159600 if (MemorySafety<INTERNAL_SAFE>::ENABLED) {
159601 AssertIndexInBounds(__n, original::size());
159602 }
159603 return original::operator[](__n);
159604 }
159605
159606 template <bool INTERNAL_SAFE = false>
159607 inline typename original::const_reference
get(
typename original::size_type __n)
const {
159608 if (MemorySafety<INTERNAL_SAFE>::ENABLED) {
159609 AssertIndexInBounds(__n, original::size());
159610 }
159611 return original::operator[](__n);
159612 }
159613
159614 typename original::reference operator[](typename original::size_type __n) {
159616 }
159617 typename original::const_reference operator[](typename original::size_type __n) const {
159619 }
159620
159621 typename original::reference front() {
159622 if (MemorySafety<SAFE>::ENABLED && original::empty()) {
159623 throw InternalException("'front' called on an empty deque!");
159624 }
159626 }
159627
159628 typename original::const_reference front() const {
159629 if (MemorySafety<SAFE>::ENABLED && original::empty()) {
159630 throw InternalException("'front' called on an empty deque!");
159631 }
159633 }
159634
159635 typename original::reference back() {
159636 if (MemorySafety<SAFE>::ENABLED && original::empty()) {
159637 throw InternalException("'back' called on an empty deque!");
159638 }
159639 return get<SAFE>(original::size() - 1);
159640 }
159641
159642 typename original::const_reference back() const {
159643 if (MemorySafety<SAFE>::ENABLED && original::empty()) {
159644 throw InternalException("'back' called on an empty deque!");
159645 }
159646 return get<SAFE>(original::size() - 1);
159647 }
159648};
159649
159650template <typename T>
159651using unsafe_deque = deque<T, false>;
159652
159653}
159654
159655
159656
159657
159658
159659
159660
159661
159662
159663
159664
159665
159666
159667
159668namespace duckdb {
159669
159670enum class PreparedStatementMode :
uint8_t {
159671 PREPARE_ONLY,
159672 PREPARE_AND_EXECUTE,
159673};
159674
159675}
159676
159677
159678
159679
159680
159681
159682
159683
159684
159685
159686
159687
159688
159689
159690
159691
159692
159693
159694
159695
159696
159697
159698
159699
159700
159701
159702
159703
159704
159705namespace duckdb {
159706
159707enum class ExplainOutputType :
uint8_t { ALL = 0, OPTIMIZED_ONLY = 1, PHYSICAL_ONLY = 2 };
159708
159709}
159710
159711
159712
159713
159714
159715
159716
159717
159718
159719
159720
159721
159722
159723
159724
159725
159726
159727
159728
159729
159730
159731
159732
159733
159734
159735
159736
159737#ifndef DUCKDB_C_API
159738#ifdef _WIN32
159739#ifdef DUCKDB_STATIC_BUILD
159740#define DUCKDB_C_API
159741#else
159742#if defined(DUCKDB_BUILD_LIBRARY) && !defined(DUCKDB_BUILD_LOADABLE_EXTENSION)
159743#define DUCKDB_C_API __declspec(dllexport)
159744#else
159745#define DUCKDB_C_API __declspec(dllimport)
159746#endif
159747#endif
159748#else
159749#define DUCKDB_C_API
159750#endif
159751#endif
159752
159754#ifndef DUCKDB_EXTENSION_API
159755#ifdef _WIN32
159756#ifdef DUCKDB_STATIC_BUILD
159757#define DUCKDB_EXTENSION_API
159758#else
159759#define DUCKDB_EXTENSION_API __declspec(dllexport)
159760#endif
159761#else
159762#define DUCKDB_EXTENSION_API __attribute__((visibility("default")))
159763#endif
159764#endif
159765
159766#include <stdbool.h>
159767#include <stdint.h>
159768#include <stddef.h>
159769
159770#ifdef __cplusplus
159771extern "C" {
159772#endif
159773
159774
159775
159776
159777
159780
159782typedef enum DUCKDB_TYPE {
159783 DUCKDB_TYPE_INVALID = 0,
159784
159785 DUCKDB_TYPE_BOOLEAN = 1,
159786
159787 DUCKDB_TYPE_TINYINT = 2,
159788
159789 DUCKDB_TYPE_SMALLINT = 3,
159790
159791 DUCKDB_TYPE_INTEGER = 4,
159792
159793 DUCKDB_TYPE_BIGINT = 5,
159794
159795 DUCKDB_TYPE_UTINYINT = 6,
159796
159797 DUCKDB_TYPE_USMALLINT = 7,
159798
159799 DUCKDB_TYPE_UINTEGER = 8,
159800
159801 DUCKDB_TYPE_UBIGINT = 9,
159802
159803 DUCKDB_TYPE_FLOAT = 10,
159804
159805 DUCKDB_TYPE_DOUBLE = 11,
159806
159807 DUCKDB_TYPE_TIMESTAMP = 12,
159808
159809 DUCKDB_TYPE_DATE = 13,
159810
159811 DUCKDB_TYPE_TIME = 14,
159812
159813 DUCKDB_TYPE_INTERVAL = 15,
159814
159815 DUCKDB_TYPE_HUGEINT = 16,
159816
159817 DUCKDB_TYPE_UHUGEINT = 32,
159818
159819 DUCKDB_TYPE_VARCHAR = 17,
159820
159821 DUCKDB_TYPE_BLOB = 18,
159822
159823 DUCKDB_TYPE_DECIMAL = 19,
159824
159825 DUCKDB_TYPE_TIMESTAMP_S = 20,
159826
159827 DUCKDB_TYPE_TIMESTAMP_MS = 21,
159828
159829 DUCKDB_TYPE_TIMESTAMP_NS = 22,
159830
159831 DUCKDB_TYPE_ENUM = 23,
159832
159833 DUCKDB_TYPE_LIST = 24,
159834
159835 DUCKDB_TYPE_STRUCT = 25,
159836
159837 DUCKDB_TYPE_MAP = 26,
159838
159839 DUCKDB_TYPE_ARRAY = 33,
159840
159841 DUCKDB_TYPE_UUID = 27,
159842
159843 DUCKDB_TYPE_UNION = 28,
159844
159845 DUCKDB_TYPE_BIT = 29,
159846
159847 DUCKDB_TYPE_TIME_TZ = 30,
159848
159849 DUCKDB_TYPE_TIMESTAMP_TZ = 31,
159850
159851 DUCKDB_TYPE_ANY = 34,
159852
159853 DUCKDB_TYPE_BIGNUM = 35,
159854
159855 DUCKDB_TYPE_SQLNULL = 36,
159856
159857 DUCKDB_TYPE_STRING_LITERAL = 37,
159858
159859 DUCKDB_TYPE_INTEGER_LITERAL = 38,
159860
159861 DUCKDB_TYPE_TIME_NS = 39,
159862
159863 DUCKDB_TYPE_GEOMETRY = 40,
159864} duckdb_type;
159865
159867typedef enum duckdb_state { DuckDBSuccess = 0, DuckDBError = 1 } duckdb_state;
159868
159870typedef enum duckdb_pending_state {
159871 DUCKDB_PENDING_RESULT_READY = 0,
159872 DUCKDB_PENDING_RESULT_NOT_READY = 1,
159873 DUCKDB_PENDING_ERROR = 2,
159874 DUCKDB_PENDING_NO_TASKS_AVAILABLE = 3
159875} duckdb_pending_state;
159876
159878typedef enum duckdb_result_type {
159879 DUCKDB_RESULT_TYPE_INVALID = 0,
159880 DUCKDB_RESULT_TYPE_CHANGED_ROWS = 1,
159881 DUCKDB_RESULT_TYPE_NOTHING = 2,
159882 DUCKDB_RESULT_TYPE_QUERY_RESULT = 3,
159883} duckdb_result_type;
159884
159886typedef enum duckdb_statement_type {
159887 DUCKDB_STATEMENT_TYPE_INVALID = 0,
159888 DUCKDB_STATEMENT_TYPE_SELECT = 1,
159889 DUCKDB_STATEMENT_TYPE_INSERT = 2,
159890 DUCKDB_STATEMENT_TYPE_UPDATE = 3,
159891 DUCKDB_STATEMENT_TYPE_EXPLAIN = 4,
159892 DUCKDB_STATEMENT_TYPE_DELETE = 5,
159893 DUCKDB_STATEMENT_TYPE_PREPARE = 6,
159894 DUCKDB_STATEMENT_TYPE_CREATE = 7,
159895 DUCKDB_STATEMENT_TYPE_EXECUTE = 8,
159896 DUCKDB_STATEMENT_TYPE_ALTER = 9,
159897 DUCKDB_STATEMENT_TYPE_TRANSACTION = 10,
159898 DUCKDB_STATEMENT_TYPE_COPY = 11,
159899 DUCKDB_STATEMENT_TYPE_ANALYZE = 12,
159900 DUCKDB_STATEMENT_TYPE_VARIABLE_SET = 13,
159901 DUCKDB_STATEMENT_TYPE_CREATE_FUNC = 14,
159902 DUCKDB_STATEMENT_TYPE_DROP = 15,
159903 DUCKDB_STATEMENT_TYPE_EXPORT = 16,
159904 DUCKDB_STATEMENT_TYPE_PRAGMA = 17,
159905 DUCKDB_STATEMENT_TYPE_VACUUM = 18,
159906 DUCKDB_STATEMENT_TYPE_CALL = 19,
159907 DUCKDB_STATEMENT_TYPE_SET = 20,
159908 DUCKDB_STATEMENT_TYPE_LOAD = 21,
159909 DUCKDB_STATEMENT_TYPE_RELATION = 22,
159910 DUCKDB_STATEMENT_TYPE_EXTENSION = 23,
159911 DUCKDB_STATEMENT_TYPE_LOGICAL_PLAN = 24,
159912 DUCKDB_STATEMENT_TYPE_ATTACH = 25,
159913 DUCKDB_STATEMENT_TYPE_DETACH = 26,
159914 DUCKDB_STATEMENT_TYPE_MULTI = 27,
159915} duckdb_statement_type;
159916
159918typedef enum duckdb_error_type {
159919 DUCKDB_ERROR_INVALID = 0,
159920 DUCKDB_ERROR_OUT_OF_RANGE = 1,
159921 DUCKDB_ERROR_CONVERSION = 2,
159922 DUCKDB_ERROR_UNKNOWN_TYPE = 3,
159923 DUCKDB_ERROR_DECIMAL = 4,
159924 DUCKDB_ERROR_MISMATCH_TYPE = 5,
159925 DUCKDB_ERROR_DIVIDE_BY_ZERO = 6,
159926 DUCKDB_ERROR_OBJECT_SIZE = 7,
159927 DUCKDB_ERROR_INVALID_TYPE = 8,
159928 DUCKDB_ERROR_SERIALIZATION = 9,
159929 DUCKDB_ERROR_TRANSACTION = 10,
159930 DUCKDB_ERROR_NOT_IMPLEMENTED = 11,
159931 DUCKDB_ERROR_EXPRESSION = 12,
159932 DUCKDB_ERROR_CATALOG = 13,
159933 DUCKDB_ERROR_PARSER = 14,
159934 DUCKDB_ERROR_PLANNER = 15,
159935 DUCKDB_ERROR_SCHEDULER = 16,
159936 DUCKDB_ERROR_EXECUTOR = 17,
159937 DUCKDB_ERROR_CONSTRAINT = 18,
159938 DUCKDB_ERROR_INDEX = 19,
159939 DUCKDB_ERROR_STAT = 20,
159940 DUCKDB_ERROR_CONNECTION = 21,
159941 DUCKDB_ERROR_SYNTAX = 22,
159942 DUCKDB_ERROR_SETTINGS = 23,
159943 DUCKDB_ERROR_BINDER = 24,
159944 DUCKDB_ERROR_NETWORK = 25,
159945 DUCKDB_ERROR_OPTIMIZER = 26,
159946 DUCKDB_ERROR_NULL_POINTER = 27,
159947 DUCKDB_ERROR_IO = 28,
159948 DUCKDB_ERROR_INTERRUPT = 29,
159949 DUCKDB_ERROR_FATAL = 30,
159950 DUCKDB_ERROR_INTERNAL = 31,
159951 DUCKDB_ERROR_INVALID_INPUT = 32,
159952 DUCKDB_ERROR_OUT_OF_MEMORY = 33,
159953 DUCKDB_ERROR_PERMISSION = 34,
159954 DUCKDB_ERROR_PARAMETER_NOT_RESOLVED = 35,
159955 DUCKDB_ERROR_PARAMETER_NOT_ALLOWED = 36,
159956 DUCKDB_ERROR_DEPENDENCY = 37,
159957 DUCKDB_ERROR_HTTP = 38,
159958 DUCKDB_ERROR_MISSING_EXTENSION = 39,
159959 DUCKDB_ERROR_AUTOLOAD = 40,
159960 DUCKDB_ERROR_SEQUENCE = 41,
159961 DUCKDB_INVALID_CONFIGURATION = 42
159962} duckdb_error_type;
159963
159965typedef enum duckdb_cast_mode { DUCKDB_CAST_NORMAL = 0, DUCKDB_CAST_TRY = 1 } duckdb_cast_mode;
159966
159967typedef enum duckdb_file_flag {
159968 DUCKDB_FILE_FLAG_INVALID = 0,
159969
159970 DUCKDB_FILE_FLAG_READ = 1,
159971
159972 DUCKDB_FILE_FLAG_WRITE = 2,
159973
159974 DUCKDB_FILE_FLAG_CREATE = 3,
159975
159976 DUCKDB_FILE_FLAG_CREATE_NEW = 4,
159977
159978 DUCKDB_FILE_FLAG_APPEND = 5,
159979} duckdb_file_flag;
159980
159985typedef enum duckdb_config_option_scope {
159986 DUCKDB_CONFIG_OPTION_SCOPE_INVALID = 0,
159987
159988
159989 DUCKDB_CONFIG_OPTION_SCOPE_LOCAL = 1,
159990
159991 DUCKDB_CONFIG_OPTION_SCOPE_SESSION = 2,
159992
159993 DUCKDB_CONFIG_OPTION_SCOPE_GLOBAL = 3,
159994} duckdb_config_option_scope;
159995
159997typedef enum duckdb_catalog_entry_type {
159998 DUCKDB_CATALOG_ENTRY_TYPE_INVALID = 0,
159999 DUCKDB_CATALOG_ENTRY_TYPE_TABLE = 1,
160000 DUCKDB_CATALOG_ENTRY_TYPE_SCHEMA = 2,
160001 DUCKDB_CATALOG_ENTRY_TYPE_VIEW = 3,
160002 DUCKDB_CATALOG_ENTRY_TYPE_INDEX = 4,
160003 DUCKDB_CATALOG_ENTRY_TYPE_PREPARED_STATEMENT = 5,
160004 DUCKDB_CATALOG_ENTRY_TYPE_SEQUENCE = 6,
160005 DUCKDB_CATALOG_ENTRY_TYPE_COLLATION = 7,
160006 DUCKDB_CATALOG_ENTRY_TYPE_TYPE = 8,
160007 DUCKDB_CATALOG_ENTRY_TYPE_DATABASE = 9,
160008} duckdb_catalog_entry_type;
160009
160010
160011
160012
160013
160016
160019
160022typedef void (*duckdb_delete_callback_t)(void *data);
160023
160025typedef void *(*duckdb_copy_callback_t)(void *data);
160026
160029typedef void *duckdb_task_state;
160030
160031
160032
160033
160034
160037typedef struct {
160039} duckdb_date;
160040
160041typedef struct {
160045} duckdb_date_struct;
160046
160049typedef struct {
160051} duckdb_time;
160052
160053typedef struct {
160058} duckdb_time_struct;
160059
160061typedef struct {
160063} duckdb_time_ns;
160064
160067typedef struct {
160069} duckdb_time_tz;
160070
160071typedef struct {
160072 duckdb_time_struct time;
160074} duckdb_time_tz_struct;
160075
160078typedef struct {
160080} duckdb_timestamp;
160081
160082typedef struct {
160083 duckdb_date_struct date;
160084 duckdb_time_struct time;
160085} duckdb_timestamp_struct;
160086
160088typedef struct {
160090} duckdb_timestamp_s;
160091
160093typedef struct {
160095} duckdb_timestamp_ms;
160096
160098typedef struct {
160100} duckdb_timestamp_ns;
160101
160103typedef struct {
160107} duckdb_interval;
160108
160112typedef struct {
160115} duckdb_hugeint;
160116
160120typedef struct {
160123} duckdb_uhugeint;
160124
160127typedef struct {
160130 duckdb_hugeint value;
160131} duckdb_decimal;
160132
160134typedef struct {
160135 double percentage;
160138} duckdb_query_progress_type;
160139
160144typedef struct {
160145 union {
160146 struct {
160148 char prefix[4];
160149 char *ptr;
160150 } pointer;
160151 struct {
160153 char inlined[12];
160154 } inlined;
160155 } value;
160156} duckdb_string_t;
160157
160162typedef struct {
160165} duckdb_list_entry;
160166
160170typedef struct {
160171
160172 void *deprecated_data;
160173
160174 bool *deprecated_nullmask;
160175
160176 duckdb_type deprecated_type;
160177
160178 char *deprecated_name;
160179 void *internal_data;
160180} duckdb_column;
160181
160184typedef struct _duckdb_vector {
160185 void *internal_ptr;
160186} * duckdb_vector;
160187
160191typedef struct _duckdb_selection_vector {
160192 void *internal_ptr;
160193} * duckdb_selection_vector;
160194
160195
160196
160197
160198
160201typedef struct {
160202 char *data;
160204} duckdb_string;
160205
160208typedef struct {
160209 void *data;
160211} duckdb_blob;
160212
160218typedef struct {
160221} duckdb_bit;
160222
160226typedef struct {
160229 bool is_negative;
160230} duckdb_bignum;
160231
160234typedef struct {
160235
160236 idx_t deprecated_column_count;
160237
160238 idx_t deprecated_row_count;
160239
160240 idx_t deprecated_rows_changed;
160241
160242 duckdb_column *deprecated_columns;
160243
160244 char *deprecated_error_message;
160245 void *internal_data;
160246} duckdb_result;
160247
160249typedef struct _duckdb_instance_cache {
160250 void *internal_ptr;
160251} * duckdb_instance_cache;
160252
160254typedef struct _duckdb_database {
160255 void *internal_ptr;
160256} * duckdb_database;
160257
160259typedef struct _duckdb_connection {
160260 void *internal_ptr;
160261} * duckdb_connection;
160262
160264typedef struct _duckdb_client_context {
160265 void *internal_ptr;
160266} * duckdb_client_context;
160267
160270typedef struct _duckdb_prepared_statement {
160271 void *internal_ptr;
160272} * duckdb_prepared_statement;
160273
160275typedef struct _duckdb_extracted_statements {
160276 void *internal_ptr;
160277} * duckdb_extracted_statements;
160278
160281typedef struct _duckdb_pending_result {
160282 void *internal_ptr;
160283} * duckdb_pending_result;
160284
160287typedef struct _duckdb_appender {
160288 void *internal_ptr;
160289} * duckdb_appender;
160290
160293typedef struct _duckdb_table_description {
160294 void *internal_ptr;
160295} * duckdb_table_description;
160296
160299typedef struct _duckdb_config {
160300 void *internal_ptr;
160301} * duckdb_config;
160302
160305typedef struct _duckdb_config_option {
160306 void *internal_ptr;
160307} * duckdb_config_option;
160308
160311typedef struct _duckdb_logical_type {
160312 void *internal_ptr;
160313} * duckdb_logical_type;
160314
160317typedef struct _duckdb_create_type_info {
160318 void *internal_ptr;
160319} * duckdb_create_type_info;
160320
160323typedef struct _duckdb_data_chunk {
160324 void *internal_ptr;
160325} * duckdb_data_chunk;
160326
160329typedef struct _duckdb_value {
160330 void *internal_ptr;
160331} * duckdb_value;
160332
160335typedef struct _duckdb_profiling_info {
160336 void *internal_ptr;
160337} * duckdb_profiling_info;
160338
160341typedef struct _duckdb_error_data {
160342 void *internal_ptr;
160343} * duckdb_error_data;
160344
160347typedef struct _duckdb_expression {
160348 void *internal_ptr;
160349} * duckdb_expression;
160350
160351
160352
160353
160354
160356typedef struct _duckdb_extension_info {
160357 void *internal_ptr;
160358} * duckdb_extension_info;
160359
160360
160361
160362
160363
160366typedef struct _duckdb_function_info {
160367 void *internal_ptr;
160368} * duckdb_function_info;
160369
160372typedef struct _duckdb_bind_info {
160373 void *internal_ptr;
160374} * duckdb_bind_info;
160375
160378typedef struct _duckdb_init_info {
160379 void *internal_ptr;
160380} * duckdb_init_info;
160381
160382
160383
160384
160385
160387typedef struct _duckdb_scalar_function {
160388 void *internal_ptr;
160389} * duckdb_scalar_function;
160390
160392typedef struct _duckdb_scalar_function_set {
160393 void *internal_ptr;
160394} * duckdb_scalar_function_set;
160395
160397typedef void (*duckdb_scalar_function_bind_t)(duckdb_bind_info info);
160398
160400typedef void (*duckdb_scalar_function_init_t)(duckdb_init_info info);
160401
160403typedef void (*duckdb_scalar_function_t)(duckdb_function_info info, duckdb_data_chunk input, duckdb_vector output);
160404
160405
160406
160407
160408
160410typedef struct _duckdb_aggregate_function {
160411 void *internal_ptr;
160412} * duckdb_aggregate_function;
160413
160415typedef struct _duckdb_aggregate_function_set {
160416 void *internal_ptr;
160417} * duckdb_aggregate_function_set;
160418
160420typedef struct _duckdb_aggregate_state {
160421 void *internal_ptr;
160422} * duckdb_aggregate_state;
160423
160425typedef idx_t (*duckdb_aggregate_state_size)(duckdb_function_info info);
160426
160428typedef void (*duckdb_aggregate_init_t)(duckdb_function_info info, duckdb_aggregate_state state);
160429
160431typedef void (*duckdb_aggregate_destroy_t)(duckdb_aggregate_state *states,
idx_t count);
160432
160434typedef void (*duckdb_aggregate_update_t)(duckdb_function_info info, duckdb_data_chunk input,
160435 duckdb_aggregate_state *states);
160436
160438typedef void (*duckdb_aggregate_combine_t)(duckdb_function_info info, duckdb_aggregate_state *source,
160439 duckdb_aggregate_state *target,
idx_t count);
160440
160442typedef void (*duckdb_aggregate_finalize_t)(duckdb_function_info info, duckdb_aggregate_state *source,
160443 duckdb_vector result,
idx_t count,
idx_t offset);
160444
160445
160446
160447
160448
160450typedef struct _duckdb_table_function {
160451 void *internal_ptr;
160452} * duckdb_table_function;
160453
160455typedef void (*duckdb_table_function_bind_t)(duckdb_bind_info info);
160456
160458typedef void (*duckdb_table_function_init_t)(duckdb_init_info info);
160459
160461typedef void (*duckdb_table_function_t)(duckdb_function_info info, duckdb_data_chunk output);
160462
160463
160464
160465
160466
160468typedef struct _duckdb_copy_function {
160469 void *internal_ptr;
160470} * duckdb_copy_function;
160471
160473typedef struct _duckdb_copy_function_bind_info {
160474 void *internal_ptr;
160475} * duckdb_copy_function_bind_info;
160476
160478typedef struct _duckdb_copy_function_global_init_info {
160479 void *internal_ptr;
160480} * duckdb_copy_function_global_init_info;
160481
160483typedef struct _duckdb_copy_function_sink_info {
160484 void *internal_ptr;
160485} * duckdb_copy_function_sink_info;
160486
160488typedef struct _duckdb_copy_function_finalize_info {
160489 void *internal_ptr;
160490} * duckdb_copy_function_finalize_info;
160491
160493typedef void (*duckdb_copy_function_bind_t)(duckdb_copy_function_bind_info info);
160494
160496typedef void (*duckdb_copy_function_global_init_t)(duckdb_copy_function_global_init_info info);
160497
160499typedef void (*duckdb_copy_function_sink_t)(duckdb_copy_function_sink_info info, duckdb_data_chunk input);
160500
160502typedef void (*duckdb_copy_function_finalize_t)(duckdb_copy_function_finalize_info info);
160503
160504
160505
160506
160507
160509typedef struct _duckdb_cast_function {
160510 void *internal_ptr;
160511} * duckdb_cast_function;
160512
160514typedef bool (*duckdb_cast_function_t)(duckdb_function_info info,
idx_t count, duckdb_vector input,
160515 duckdb_vector output);
160516
160517
160518
160519
160520
160522typedef struct _duckdb_replacement_scan_info {
160523 void *internal_ptr;
160524} * duckdb_replacement_scan_info;
160525
160527typedef void (*duckdb_replacement_callback_t)(duckdb_replacement_scan_info info, const char *table_name, void *data);
160528
160529
160530
160531
160532
160536
160537struct ArrowArray;
160538
160539struct ArrowSchema;
160540
160542typedef struct _duckdb_arrow {
160543 void *internal_ptr;
160544} * duckdb_arrow;
160545
160547typedef struct _duckdb_arrow_stream {
160548 void *internal_ptr;
160549} * duckdb_arrow_stream;
160550
160552typedef struct _duckdb_arrow_schema {
160553 void *internal_ptr;
160554} * duckdb_arrow_schema;
160555
160560typedef struct _duckdb_arrow_converted_schema {
160561 void *internal_ptr;
160562} * duckdb_arrow_converted_schema;
160563
160565typedef struct _duckdb_arrow_array {
160566 void *internal_ptr;
160567} * duckdb_arrow_array;
160568
160571typedef struct _duckdb_arrow_options {
160572 void *internal_ptr;
160573} * duckdb_arrow_options;
160574
160575
160576
160577
160578
160579typedef struct _duckdb_file_open_options {
160580 void *internal_ptr;
160581} * duckdb_file_open_options;
160582
160583typedef struct _duckdb_file_system {
160584 void *internal_ptr;
160585} * duckdb_file_system;
160586
160587typedef struct _duckdb_file_handle {
160588 void *internal_ptr;
160589} * duckdb_file_handle;
160590
160591
160592
160593
160594
160597typedef struct _duckdb_catalog {
160598 void *internal_ptr;
160599} * duckdb_catalog;
160600
160603typedef struct _duckdb_catalog_entry {
160604 void *internal_ptr;
160605} * duckdb_catalog_entry;
160606
160607
160608
160609
160610
160612typedef struct _duckdb_log_storage {
160613 void *internal_ptr;
160614} * duckdb_log_storage;
160615
160617typedef void (*duckdb_logger_write_log_entry_t)(
void *extra_data, duckdb_timestamp *
timestamp,
const char *level,
160618 const char *log_type, const char *log_message);
160619
160620
160621
160622
160623
160625struct duckdb_extension_access {
160627 void (*set_error)(duckdb_extension_info info, const char *error);
160629 duckdb_database *(*get_database)(duckdb_extension_info info);
160631 const void *(*get_api)(duckdb_extension_info info, const char *version);
160632};
160633
160634#ifndef DUCKDB_API_EXCLUDE_FUNCTIONS
160635
160636
160637
160638
160639
160640
160641
160642
160643
160644
160645
160646
160655
160669 duckdb_database *out_database, duckdb_config config,
160670 char **out_error);
160671
160678
160688DUCKDB_C_API duckdb_state
duckdb_open(
const char *path, duckdb_database *out_database);
160689
160701DUCKDB_C_API duckdb_state
duckdb_open_ext(
const char *path, duckdb_database *out_database, duckdb_config config,
160702 char **out_error);
160703
160712DUCKDB_C_API
void duckdb_close(duckdb_database *database);
160713
160723DUCKDB_C_API duckdb_state
duckdb_connect(duckdb_database database, duckdb_connection *out_connection);
160724
160731
160739
160746
160754 duckdb_client_context *out_context);
160755
160762 duckdb_arrow_options *out_arrow_options);
160763
160771
160778
160785
160792
160803DUCKDB_C_API duckdb_value
duckdb_get_table_names(duckdb_connection connection,
const char *query,
bool qualified);
160804
160805
160806
160807
160808
160809
160810
160811
160826
160835
160847DUCKDB_C_API duckdb_state
duckdb_get_config_flag(
size_t index,
const char **out_name,
const char **out_description);
160848
160862DUCKDB_C_API duckdb_state
duckdb_set_config(duckdb_config config,
const char *name,
const char *option);
160863
160870
160871
160872
160873
160874
160875
160876
160877
160878
160888
160895
160903
160911
160919
160920
160921
160922
160923
160924
160925
160926
160940DUCKDB_C_API duckdb_state
duckdb_query(duckdb_connection connection,
const char *query, duckdb_result *out_result);
160941
160948
160960
160971
160979
160992
161001
161009
161010#ifndef DUCKDB_API_NO_DEPRECATED
161020
161021#endif
161022
161031
161032#ifndef DUCKDB_API_NO_DEPRECATED
161053
161076
161077#endif
161078
161088
161097
161098#ifndef DUCKDB_API_NO_DEPRECATED
161119
161129
161139
161140#endif
161141
161149
161150
161151
161152
161153
161154
161155
161156
161157
161158
161159
161160
161161
161162
161163
161164#ifndef DUCKDB_API_NO_DEPRECATED
161171
161178
161185
161192
161199
161205DUCKDB_C_API duckdb_hugeint
duckdb_value_hugeint(duckdb_result *result, idx_t col, idx_t row);
161206
161213
161219DUCKDB_C_API duckdb_decimal
duckdb_value_decimal(duckdb_result *result, idx_t col, idx_t row);
161220
161227
161234
161241
161248
161255
161262
161268DUCKDB_C_API duckdb_date
duckdb_value_date(duckdb_result *result, idx_t col, idx_t row);
161269
161275DUCKDB_C_API duckdb_time
duckdb_value_time(duckdb_result *result, idx_t col, idx_t row);
161276
161283
161290
161298
161304DUCKDB_C_API duckdb_string
duckdb_value_string(duckdb_result *result, idx_t col, idx_t row);
161305
161315
161325
161332DUCKDB_C_API duckdb_blob
duckdb_value_blob(duckdb_result *result, idx_t col, idx_t row);
161333
161340
161341#endif
161342
161343
161344
161345
161346
161347
161348
161349
161358
161366
161374
161381
161389
161397
161407
161408
161409
161410
161411
161412
161413
161414
161415
161423
161430DUCKDB_C_API duckdb_date
duckdb_to_date(duckdb_date_struct date);
161431
161439
161447
161456
161465
161472DUCKDB_C_API duckdb_time
duckdb_to_time(duckdb_time_struct time);
161473
161481
161489
161497
161505
161513
161521
161522
161523
161524
161525
161526
161527
161528
161536
161546
161554
161564
161565
161566
161567
161568
161569
161570
161571
161581
161589
161590
161591
161592
161593
161594
161595
161596
161597
161598
161599
161600
161601
161602
161603
161604
161618DUCKDB_C_API duckdb_state
duckdb_prepare(duckdb_connection connection,
const char *query,
161619 duckdb_prepared_statement *out_prepared_statement);
161620
161627
161638
161647
161656DUCKDB_C_API
const char *
duckdb_parameter_name(duckdb_prepared_statement prepared_statement, idx_t index);
161657
161667DUCKDB_C_API duckdb_type
duckdb_param_type(duckdb_prepared_statement prepared_statement, idx_t param_idx);
161668
161681 idx_t param_idx);
161682
161687
161695
161704
161716 idx_t col_idx);
161717
161728DUCKDB_C_API duckdb_logical_type
161730
161741 idx_t col_idx);
161742
161743
161744
161745
161746
161747
161748
161749
161750
161756DUCKDB_C_API duckdb_state
duckdb_bind_value(duckdb_prepared_statement prepared_statement, idx_t param_idx,
161757 duckdb_value val);
161758
161763 idx_t *param_idx_out, const char *name);
161764
161768DUCKDB_C_API duckdb_state
duckdb_bind_boolean(duckdb_prepared_statement prepared_statement, idx_t param_idx,
bool val);
161769
161773DUCKDB_C_API duckdb_state
duckdb_bind_int8(duckdb_prepared_statement prepared_statement, idx_t param_idx, int8_t val);
161774
161778DUCKDB_C_API duckdb_state
duckdb_bind_int16(duckdb_prepared_statement prepared_statement, idx_t param_idx, int16_t val);
161779
161783DUCKDB_C_API duckdb_state
duckdb_bind_int32(duckdb_prepared_statement prepared_statement, idx_t param_idx, int32_t val);
161784
161788DUCKDB_C_API duckdb_state
duckdb_bind_int64(duckdb_prepared_statement prepared_statement, idx_t param_idx, int64_t val);
161789
161793DUCKDB_C_API duckdb_state
duckdb_bind_hugeint(duckdb_prepared_statement prepared_statement, idx_t param_idx,
161794 duckdb_hugeint val);
161795
161799DUCKDB_C_API duckdb_state
duckdb_bind_uhugeint(duckdb_prepared_statement prepared_statement, idx_t param_idx,
161800 duckdb_uhugeint val);
161801
161805DUCKDB_C_API duckdb_state
duckdb_bind_decimal(duckdb_prepared_statement prepared_statement, idx_t param_idx,
161806 duckdb_decimal val);
161807
161811DUCKDB_C_API duckdb_state
duckdb_bind_uint8(duckdb_prepared_statement prepared_statement, idx_t param_idx, uint8_t val);
161812
161816DUCKDB_C_API duckdb_state
duckdb_bind_uint16(duckdb_prepared_statement prepared_statement, idx_t param_idx,
161817 uint16_t val);
161818
161822DUCKDB_C_API duckdb_state
duckdb_bind_uint32(duckdb_prepared_statement prepared_statement, idx_t param_idx,
161823 uint32_t val);
161824
161828DUCKDB_C_API duckdb_state
duckdb_bind_uint64(duckdb_prepared_statement prepared_statement, idx_t param_idx,
161829 uint64_t val);
161830
161834DUCKDB_C_API duckdb_state
duckdb_bind_float(duckdb_prepared_statement prepared_statement, idx_t param_idx,
float val);
161835
161839DUCKDB_C_API duckdb_state
duckdb_bind_double(duckdb_prepared_statement prepared_statement, idx_t param_idx,
double val);
161840
161844DUCKDB_C_API duckdb_state
duckdb_bind_date(duckdb_prepared_statement prepared_statement, idx_t param_idx,
161845 duckdb_date val);
161846
161850DUCKDB_C_API duckdb_state
duckdb_bind_time(duckdb_prepared_statement prepared_statement, idx_t param_idx,
161851 duckdb_time val);
161852
161856DUCKDB_C_API duckdb_state
duckdb_bind_timestamp(duckdb_prepared_statement prepared_statement, idx_t param_idx,
161857 duckdb_timestamp val);
161858
161863 duckdb_timestamp val);
161864
161868DUCKDB_C_API duckdb_state
duckdb_bind_interval(duckdb_prepared_statement prepared_statement, idx_t param_idx,
161869 duckdb_interval val);
161870
161876DUCKDB_C_API duckdb_state
duckdb_bind_varchar(duckdb_prepared_statement prepared_statement, idx_t param_idx,
161877 const char *val);
161878
161885 const char *val, idx_t length);
161886
161890DUCKDB_C_API duckdb_state
duckdb_bind_blob(duckdb_prepared_statement prepared_statement, idx_t param_idx,
161891 const void *data, idx_t length);
161892
161896DUCKDB_C_API duckdb_state
duckdb_bind_null(duckdb_prepared_statement prepared_statement, idx_t param_idx);
161897
161898
161899
161900
161901
161902
161903
161904
161918 duckdb_result *out_result);
161919
161920#ifndef DUCKDB_API_NO_DEPRECATED
161937 duckdb_result *out_result);
161938
161939#endif
161940
161941
161942
161943
161944
161945
161946
161947
161948
161962 duckdb_extracted_statements *out_extracted_statements);
161963
161978 duckdb_extracted_statements extracted_statements,
161979 idx_t index,
161980 duckdb_prepared_statement *out_prepared_statement);
161981
161990
161996
161997
161998
161999
162000
162001
162002
162003
162017 duckdb_pending_result *out_result);
162018
162019#ifndef DUCKDB_API_NO_DEPRECATED
162035 duckdb_pending_result *out_result);
162036
162037#endif
162038
162045
162055
162069
162081
162094DUCKDB_C_API duckdb_state
duckdb_execute_pending(duckdb_pending_result pending_result, duckdb_result *out_result);
162095
162104
162105
162106
162107
162108
162109
162110
162111
162112
162113
162120
162130
162139
162147
162155
162163
162171
162179
162187
162195
162203
162210
162218
162226
162234
162242
162250
162258
162266
162274
162282
162291
162299
162307
162315
162323
162331
162339
162348
162356
162364
162372
162380
162388
162396
162404
162412
162420
162428
162436
162444
162452
162461
162469
162477
162485
162493
162501
162509
162517
162525
162533
162541
162549
162557
162565
162574
162582
162591
162599
162608
162617
162627DUCKDB_C_API duckdb_value
duckdb_create_list_value(duckdb_logical_type type, duckdb_value *values, idx_t value_count);
162628
162638DUCKDB_C_API duckdb_value
duckdb_create_array_value(duckdb_logical_type type, duckdb_value *values, idx_t value_count);
162639
162651 duckdb_value *values, idx_t entry_count);
162652
162663 duckdb_value value);
162664
162672
162681
162690
162698
162705
162713
162722
162731
162739
162748
162756
162757
162758
162759
162760
162761
162762
162763
162775
162784
162792
162801
162811
162821
162831DUCKDB_C_API duckdb_logical_type
duckdb_create_union_type(duckdb_logical_type *member_types,
const char **member_names,
162832 idx_t member_count);
162833
162843DUCKDB_C_API duckdb_logical_type
duckdb_create_struct_type(duckdb_logical_type *member_types,
const char **member_names,
162844 idx_t member_count);
162845
162855
162865
162873
162881
162889
162897
162905
162913
162924
162933
162943
162951
162961
162971
162979
162990
163001
163009
163020
163031
163038
163048 duckdb_create_type_info info);
163049
163050
163051
163052
163053
163054
163055
163056
163057
163058
163059
163060
163061
163071
163078
163087
163095
163106
163114
163122
163123
163124
163125
163126
163127
163128
163129
163130
163139
163146
163156
163167
163189
163199
163211
163224 idx_t str_len);
163225
163238 idx_t str_len);
163239
163249
163257
163269
163281
163291
163301
163311DUCKDB_C_API
void duckdb_slice_vector(duckdb_vector vector, duckdb_selection_vector sel, idx_t len);
163312
163326DUCKDB_C_API
void duckdb_vector_copy_sel(duckdb_vector src, duckdb_vector dst, duckdb_selection_vector sel,
163327 idx_t src_count, idx_t src_offset, idx_t dst_offset);
163328
163336
163343DUCKDB_C_API void duckdb_vector_reference_vector(duckdb_vector to_vector, duckdb_vector from_vector);
163344
163345
163346
163347
163348
163349
163350
163351
163352
163361
163373
163383
163393
163394
163395
163396
163397
163398
163399
163400
163401
163402
163411
163418
163426
163436
163443
163451
163459 duckdb_logical_type type);
163460
163468 duckdb_logical_type type);
163469
163478 duckdb_delete_callback_t destroy);
163479
163487 duckdb_scalar_function_bind_t bind);
163488
163499 duckdb_delete_callback_t destroy);
163500
163508
163516
163524 duckdb_scalar_function_t function);
163525
163538 duckdb_scalar_function scalar_function);
163539
163547
163555
163564
163572
163580
163589
163595
163605 duckdb_scalar_function function);
163606
163619
163627
163636
163644
163652 duckdb_scalar_function_init_t init);
163653
163661
163670 duckdb_delete_callback_t destroy);
163671
163679 duckdb_client_context *out_context);
163680
163689
163697
163698
163699
163700
163701
163702
163703
163704
163705
163706
163715
163722
163730
163731
163732
163733
163734
163735
163736
163737
163738
163747
163753
163761
163769 duckdb_logical_type type);
163770
163778 duckdb_logical_type type);
163779
163791 duckdb_aggregate_state_size state_size,
163792 duckdb_aggregate_init_t state_init,
163793 duckdb_aggregate_update_t update,
163794 duckdb_aggregate_combine_t combine,
163795 duckdb_aggregate_finalize_t finalize);
163796
163804 duckdb_aggregate_destroy_t destroy);
163805
163817 duckdb_aggregate_function aggregate_function);
163818
163825
163834 void *extra_info, duckdb_delete_callback_t destroy);
163835
163843
163851
163860
163866
163876 duckdb_aggregate_function function);
163877
163890 duckdb_aggregate_function_set set);
163891
163892
163893
163894
163895
163896
163897
163898
163899
163908
163915
163923
163931
163940 duckdb_logical_type type);
163941
163950 duckdb_delete_callback_t destroy);
163951
163959 duckdb_table_function_bind_t bind);
163960
163968 duckdb_table_function_init_t init);
163969
163977 duckdb_table_function_init_t init);
163978
163986 duckdb_table_function_t function);
163987
163999 bool pushdown);
164000
164013
164014
164015
164016
164017
164018
164019
164020
164021
164029
164037
164046
164054
164065
164076
164086
164094
164102
164103
164104
164105
164106
164107
164108
164109
164110
164118
164129
164138
164148
164159
164167
164175
164176
164177
164178
164179
164180
164181
164182
164183
164191
164202
164210
164218
164226
164227
164228
164229
164230
164231
164232
164233
164234
164244 void *extra_data, duckdb_delete_callback_t delete_callback);
164245
164254 const char *function_name);
164255
164263
164271
164272
164273
164274
164275
164276
164277
164278
164286
164297
164306
164314
164323
164324
164325
164326
164327
164328
164329
164330
164331
164332
164333
164334
164335
164347DUCKDB_C_API duckdb_state
duckdb_appender_create(duckdb_connection connection,
const char *schema,
const char *table,
164348 duckdb_appender *out_appender);
164349
164363 const char *schema, const char *table,
164364 duckdb_appender *out_appender);
164365
164381 idx_t column_count, duckdb_logical_type *types,
164382 const char *table_name, const char **column_names,
164383 duckdb_appender *out_appender);
164384
164393
164405
164406#ifndef DUCKDB_API_NO_DEPRECATED
164420
164421#endif
164422
164431
164442
164451
164462
164474
164485
164494
164499
164507
164512
164525 idx_t row);
164526
164531
164535DUCKDB_C_API duckdb_state
duckdb_append_int8(duckdb_appender appender, int8_t value);
164536
164541
164546
164551
164556
164561
164566
164571
164576
164581
164586
164591
164595DUCKDB_C_API duckdb_state
duckdb_append_date(duckdb_appender appender, duckdb_date value);
164596
164600DUCKDB_C_API duckdb_state
duckdb_append_time(duckdb_appender appender, duckdb_time value);
164601
164606
164611
164616
164621
164625DUCKDB_C_API duckdb_state
duckdb_append_blob(duckdb_appender appender,
const void *data, idx_t length);
164626
164631
164635DUCKDB_C_API duckdb_state
duckdb_append_value(duckdb_appender appender, duckdb_value value);
164636
164646
164647
164648
164649
164650
164651
164652
164653
164665 const char *table, duckdb_table_description *out);
164666
164679 const char *schema, const char *table,
164680 duckdb_table_description *out);
164681
164688
164698
164707DUCKDB_C_API duckdb_state
duckdb_column_has_default(duckdb_table_description table_description, idx_t index,
bool *out);
164708
164716
164726
164736 idx_t index);
164737
164738
164739
164740
164741
164742
164743
164744
164755DUCKDB_C_API duckdb_error_data
duckdb_to_arrow_schema(duckdb_arrow_options arrow_options, duckdb_logical_type *types,
164756 const char **names, idx_t column_count,
164757 struct ArrowSchema *out_schema);
164758
164769 struct ArrowArray *out_arrow_array);
164770
164781 duckdb_arrow_converted_schema *out_types);
164782
164794 struct ArrowArray *arrow_array,
164795 duckdb_arrow_converted_schema converted_schema,
164796 duckdb_data_chunk *out_chunk);
164797
164804
164805#ifndef DUCKDB_API_NO_DEPRECATED
164821DUCKDB_C_API duckdb_state
duckdb_query_arrow(duckdb_connection connection,
const char *query, duckdb_arrow *out_result);
164822
164834
164846 duckdb_arrow_schema *out_schema);
164847
164859 duckdb_arrow_array *out_array);
164860
164875
164885
164895
164906
164919
164928
164937
164949 duckdb_arrow *out_result);
164950
164961DUCKDB_C_API duckdb_state
duckdb_arrow_scan(duckdb_connection connection,
const char *table_name,
164962 duckdb_arrow_stream arrow);
164963
164978 duckdb_arrow_schema arrow_schema, duckdb_arrow_array arrow_array,
164979 duckdb_arrow_stream *out_stream);
164980
164981#endif
164982
164983
164984
164985
164986
164987
164988
164989
164999
165010
165020
165034
165041
165049
165059
165066
165067
165068
165069
165070
165071
165072
165073
165074#ifndef DUCKDB_API_NO_DEPRECATED
165094
165095#endif
165096
165108
165109
165110
165111
165112
165113
165114
165115
165122
165130 duckdb_logical_type source_type);
165131
165139 duckdb_logical_type target_type);
165140
165148
165156 duckdb_cast_function_t function);
165157
165165 duckdb_delete_callback_t destroy);
165166
165174
165182
165190
165200 duckdb_vector output);
165201
165210
165217
165218
165219
165220
165221
165222
165223
165224
165225
165232
165240
165248
165257DUCKDB_C_API duckdb_error_data
duckdb_expression_fold(duckdb_client_context context, duckdb_expression expr,
165258 duckdb_value *out_value);
165259
165260
165261
165262
165263
165264
165265
165266
165267
165275
165281
165289
165302 duckdb_file_open_options options, duckdb_file_handle *out_file);
165303
165310
165321 bool value);
165322
165328
165336
165344
165354
165364
165372
165380
165389
165398
165407
165408
165409
165410
165411
165412
165413
165414
165421
165427
165435
165443
165453
165462 duckdb_config_option_scope default_scope);
165463
165471
165480
165492 duckdb_config_option_scope *out_scope);
165493
165494
165495
165496
165497
165498
165499
165500
165509
165517
165526 duckdb_delete_callback_t destructor);
165527
165535 duckdb_copy_function copy_function);
165536
165542
165549
165557
165565
165575
165583
165592 idx_t col_idx);
165593
165601
165610 duckdb_delete_callback_t destructor);
165611
165618 duckdb_copy_function_global_init_t init);
165619
165627 const char *error);
165628
165636
165645DUCKDB_C_API duckdb_client_context
165647
165655
165665
165674 void *global_state,
165675 duckdb_delete_callback_t destructor);
165676
165683 duckdb_copy_function_sink_t function);
165684
165692
165700
165710
165718
165726
165733 duckdb_copy_function_finalize_t finalize);
165734
165742
165750
165759DUCKDB_C_API duckdb_client_context
165761
165769
165777
165797 duckdb_table_function table_function);
165798
165809
165824
165838 idx_t col_idx);
165839
165840
165841
165842
165843
165844
165845
165846
165847
165848
165849
165860
165870
165884 duckdb_catalog_entry_type entry_type,
165885 const char *schema_name, const char *entry_name);
165886
165895
165903
165912
165921
165922
165923
165924
165925
165926
165927
165928
165929
165936
165943
165951 duckdb_logger_write_log_entry_t function);
165952
165961 duckdb_delete_callback_t delete_callback);
165962
165970
165979
165980
165981
165982
165983
165984
165985
165986
165995
165996#endif
165997
165998#ifdef __cplusplus
165999}
166000#endif
166001
166002
166003
166004
166005
166006
166007
166008
166009
166010
166011
166012
166013
166014
166015
166016
166017
166018
166019
166020
166021
166022
166023
166024#include <chrono>
166025
166026namespace duckdb {
166027using std::chrono::duration;
166028using std::chrono::duration_cast;
166029using std::chrono::high_resolution_clock;
166030using std::chrono::microseconds;
166031using std::chrono::milliseconds;
166032using std::chrono::nanoseconds;
166033using std::chrono::steady_clock;
166034using std::chrono::system_clock;
166035using std::chrono::time_point;
166036}
166037
166038
166039
166040namespace duckdb {
166041
166043template <typename T>
166044class BaseProfiler {
166045public:
166047 void Start() {
166048 finished = false;
166049 ran = true;
166050 start = Tick();
166051 }
166053 void End() {
166054 end = Tick();
166055 finished = true;
166056 }
166058 void Reset() {
166059 finished = false;
166060 ran = false;
166061 }
166062
166067 double Elapsed() const {
166068 if (!ran) {
166069 return 0;
166070 }
166071 auto measured_end = finished ? end : Tick();
166072 return std::chrono::duration_cast<std::chrono::duration<double>>(measured_end - start).count();
166073 }
166074
166075 idx_t ElapsedNanos()
const {
166076 if (!ran) {
166077 return 0;
166078 }
166079 auto measured_end = finished ? end : Tick();
166080 return static_cast<idx_t>(std::chrono::duration_cast<std::chrono::nanoseconds>(measured_end - start).count());
166081 }
166082
166083private:
166085 time_point<T> Tick() const {
166086 return T::now();
166087 }
166089 time_point<T> start;
166091 time_point<T> end;
166093 bool finished = false;
166095 bool ran = false;
166096};
166097
166098using Profiler = BaseProfiler<steady_clock>;
166099
166100}
166101
166102
166103
166104
166105
166106
166107
166108
166109
166110
166111
166112namespace duckdb {
166113
166114class ProgressBarDisplay {
166115public:
166116 ProgressBarDisplay() {
166117 }
166118 virtual ~ProgressBarDisplay() {
166119 }
166120
166121public:
166122 virtual void Update(double percentage) = 0;
166123 virtual void Finish() = 0;
166124};
166125
166126}
166127
166128
166129namespace duckdb {
166130
166131struct ClientConfig;
166132typedef std::function<unique_ptr<ProgressBarDisplay>()> progress_bar_display_create_func_t;
166133
166134struct QueryProgress {
166135 friend class ProgressBar;
166136
166137public:
166138 QueryProgress();
166139 void Initialize();
166140 void Restart();
166141 double GetPercentage();
166143 uint64_t GetTotalRowsToProcess();
166144 QueryProgress &
operator=(
const QueryProgress &other);
166145 QueryProgress(const QueryProgress &other);
166146
166147private:
166148 atomic<double> percentage;
166149 atomic<uint64_t> rows_processed;
166150 atomic<uint64_t> total_rows_to_process;
166151};
166152
166153class ProgressBar {
166154public:
166155 static unique_ptr<ProgressBarDisplay> DefaultProgressBarDisplay();
166156 static void SystemOverrideCheck(ClientConfig &config);
166157
166158 explicit ProgressBar(
166159 Executor &executor, idx_t show_progress_after,
166160 progress_bar_display_create_func_t create_display_func = ProgressBar::DefaultProgressBarDisplay);
166161
166163 void Start();
166165 void Update(bool final);
166166 QueryProgress GetDetailedQueryProgress();
166167 void PrintProgress(double percentage);
166168 void FinishProgressBarPrint();
166169 bool ShouldPrint(bool final) const;
166170 bool PrintEnabled() const;
166171
166172private:
166174 Executor &executor;
166176 Profiler profiler;
166178 idx_t show_progress_after;
166180 QueryProgress query_progress;
166182 unique_ptr<ProgressBarDisplay> display;
166184 bool supported = true;
166186 bool finished = false;
166187};
166188}
166189
166190
166191
166192
166193
166194
166195
166196
166197
166198
166199
166200
166201
166202
166203
166204
166205
166206
166207
166208
166209
166210
166211
166212
166213
166214
166215
166216
166217
166218
166219
166220
166221
166222
166223
166224
166225
166226
166227
166228
166229
166230
166231
166232
166233
166234
166235
166236namespace duckdb {
166237
166238enum class OptimizerType :
uint32_t {
166239 INVALID = 0,
166240 EXPRESSION_REWRITER = 1,
166241 FILTER_PULLUP = 2,
166242 FILTER_PUSHDOWN = 3,
166243 EMPTY_RESULT_PULLUP = 4,
166244 CTE_FILTER_PUSHER = 5,
166245 REGEX_RANGE = 6,
166246 IN_CLAUSE = 7,
166247 JOIN_ORDER = 8,
166248 DELIMINATOR = 9,
166249 UNNEST_REWRITER = 10,
166250 UNUSED_COLUMNS = 11,
166251 STATISTICS_PROPAGATION = 12,
166252 COMMON_SUBEXPRESSIONS = 13,
166253 COMMON_AGGREGATE = 14,
166254 COLUMN_LIFETIME = 15,
166255 BUILD_SIDE_PROBE_SIDE = 16,
166256 LIMIT_PUSHDOWN = 17,
166257 TOP_N = 18,
166258 COMPRESSED_MATERIALIZATION = 19,
166259 DUPLICATE_GROUPS = 20,
166260 REORDER_FILTER = 21,
166261 SAMPLING_PUSHDOWN = 22,
166262 JOIN_FILTER_PUSHDOWN = 23,
166263 EXTENSION = 24,
166264 MATERIALIZED_CTE = 25,
166265 SUM_REWRITER = 26,
166266 LATE_MATERIALIZATION = 27,
166267 CTE_INLINING = 28,
166268 ROW_GROUP_PRUNER = 29,
166269 TOP_N_WINDOW_ELIMINATION = 30,
166270 COMMON_SUBPLAN = 31,
166271 JOIN_ELIMINATION = 32,
166272 WINDOW_SELF_JOIN = 33
166273};
166274
166275string OptimizerTypeToString(OptimizerType type);
166276OptimizerType OptimizerTypeFromString(const string &str);
166277vector<string> ListAllOptimizers();
166278
166279}
166280
166281
166282namespace duckdb {
166283
166284enum class MetricGroup :
uint8_t {
166285 ALL,
166286 CORE,
166287 DEFAULT,
166288 EXECUTION,
166289 FILE,
166290 OPERATOR,
166291 OPTIMIZER,
166292 PHASE_TIMING,
166293 INVALID,
166294};
166295
166296enum class MetricType :
uint8_t {
166297
166298 CPU_TIME = 2,
166299 CUMULATIVE_CARDINALITY = 4,
166300 CUMULATIVE_ROWS_SCANNED = 7,
166301 EXTRA_INFO = 3,
166302 LATENCY = 11,
166303 QUERY_NAME = 0,
166304 RESULT_SET_SIZE = 10,
166305 ROWS_RETURNED = 12,
166306
166307 BLOCKED_THREAD_TIME = 1,
166308 SYSTEM_PEAK_BUFFER_MEMORY = 14,
166309 SYSTEM_PEAK_TEMP_DIR_SIZE = 15,
166310 TOTAL_MEMORY_ALLOCATED = 91,
166311
166312 ATTACH_LOAD_STORAGE_LATENCY = 92,
166313 ATTACH_REPLAY_WAL_LATENCY = 93,
166314 CHECKPOINT_LATENCY = 94,
166315 COMMIT_LOCAL_STORAGE_LATENCY = 95,
166316 TOTAL_BYTES_READ = 16,
166317 TOTAL_BYTES_WRITTEN = 17,
166318 WAITING_TO_ATTACH_LATENCY = 96,
166319 WAL_REPLAY_ENTRY_COUNT = 97,
166320 WRITE_TO_WAL_LATENCY = 98,
166321
166322 OPERATOR_CARDINALITY = 6,
166323 OPERATOR_NAME = 13,
166324 OPERATOR_ROWS_SCANNED = 8,
166325 OPERATOR_TIMING = 9,
166326 OPERATOR_TYPE = 5,
166327
166328 OPTIMIZER_EXPRESSION_REWRITER = 26,
166329 OPTIMIZER_FILTER_PULLUP = 27,
166330 OPTIMIZER_FILTER_PUSHDOWN = 28,
166331 OPTIMIZER_EMPTY_RESULT_PULLUP = 29,
166332 OPTIMIZER_CTE_FILTER_PUSHER = 30,
166333 OPTIMIZER_REGEX_RANGE = 31,
166334 OPTIMIZER_IN_CLAUSE = 32,
166335 OPTIMIZER_JOIN_ORDER = 33,
166336 OPTIMIZER_DELIMINATOR = 34,
166337 OPTIMIZER_UNNEST_REWRITER = 35,
166338 OPTIMIZER_UNUSED_COLUMNS = 36,
166339 OPTIMIZER_STATISTICS_PROPAGATION = 37,
166340 OPTIMIZER_COMMON_SUBEXPRESSIONS = 38,
166341 OPTIMIZER_COMMON_AGGREGATE = 39,
166342 OPTIMIZER_COLUMN_LIFETIME = 40,
166343 OPTIMIZER_BUILD_SIDE_PROBE_SIDE = 41,
166344 OPTIMIZER_LIMIT_PUSHDOWN = 42,
166345 OPTIMIZER_TOP_N = 43,
166346 OPTIMIZER_COMPRESSED_MATERIALIZATION = 44,
166347 OPTIMIZER_DUPLICATE_GROUPS = 45,
166348 OPTIMIZER_REORDER_FILTER = 46,
166349 OPTIMIZER_SAMPLING_PUSHDOWN = 47,
166350 OPTIMIZER_JOIN_FILTER_PUSHDOWN = 48,
166351 OPTIMIZER_EXTENSION = 49,
166352 OPTIMIZER_MATERIALIZED_CTE = 50,
166353 OPTIMIZER_SUM_REWRITER = 51,
166354 OPTIMIZER_LATE_MATERIALIZATION = 52,
166355 OPTIMIZER_CTE_INLINING = 53,
166356 OPTIMIZER_ROW_GROUP_PRUNER = 54,
166357 OPTIMIZER_TOP_N_WINDOW_ELIMINATION = 55,
166358 OPTIMIZER_COMMON_SUBPLAN = 56,
166359 OPTIMIZER_JOIN_ELIMINATION = 57,
166360 OPTIMIZER_WINDOW_SELF_JOIN = 58,
166361
166362 ALL_OPTIMIZERS = 18,
166363 CUMULATIVE_OPTIMIZER_TIMING = 19,
166364 PHYSICAL_PLANNER = 22,
166365 PHYSICAL_PLANNER_COLUMN_BINDING = 23,
166366 PHYSICAL_PLANNER_CREATE_PLAN = 25,
166367 PHYSICAL_PLANNER_RESOLVE_TYPES = 24,
166368 PLANNER = 20,
166369 PLANNER_BINDING = 21,
166370};
166371
166372struct MetricTypeHashFunction {
166374 return std::hash<uint8_t>()(
static_cast<uint8_t>(
index));
166375 }
166376};
166377
166378typedef unordered_set<MetricType, MetricTypeHashFunction> profiler_settings_t;
166379typedef unordered_map<MetricType, Value, MetricTypeHashFunction> profiler_metrics_t;
166380
166381class MetricsUtils {
166382public:
166383 static constexpr uint8_t START_OPTIMIZER =
static_cast<uint8_t>(MetricType::OPTIMIZER_EXPRESSION_REWRITER);
166384 static constexpr uint8_t END_OPTIMIZER =
static_cast<uint8_t>(MetricType::OPTIMIZER_WINDOW_SELF_JOIN);
166385
166386public:
166387
166388
166389 static profiler_settings_t GetAllMetrics();
166390 static profiler_settings_t GetMetricsByGroupType(MetricGroup type);
166391
166392
166393 static profiler_settings_t GetCoreMetrics();
166394 static bool IsCoreMetric(MetricType type);
166395
166396
166397 static profiler_settings_t GetDefaultMetrics();
166398 static bool IsDefaultMetric(MetricType type);
166399
166400
166401 static profiler_settings_t GetExecutionMetrics();
166402 static bool IsExecutionMetric(MetricType type);
166403
166404
166405 static profiler_settings_t GetFileMetrics();
166406 static bool IsFileMetric(MetricType type);
166407
166408
166409 static profiler_settings_t GetOperatorMetrics();
166410 static bool IsOperatorMetric(MetricType type);
166411
166412
166413 static profiler_settings_t GetOptimizerMetrics();
166414 static bool IsOptimizerMetric(MetricType type);
166415 static MetricType GetOptimizerMetricByType(OptimizerType type);
166416 static OptimizerType GetOptimizerTypeByMetric(MetricType type);
166417
166418
166419 static profiler_settings_t GetPhaseTimingMetrics();
166420 static bool IsPhaseTimingMetric(MetricType type);
166421
166422
166423 static profiler_settings_t GetRootScopeMetrics();
166424 static bool IsRootScopeMetric(MetricType type);
166425};
166426}
166427
166428
166429namespace duckdb_yyjson {
166432}
166433
166434namespace duckdb {
166435enum class ProfilingParameterNames :
uint8_t { FORMAT, COVERAGE, SAVE_LOCATION, MODE, METRICS };
166436
166437class ProfilingInfo {
166438public:
166440 profiler_settings_t settings;
166442 profiler_settings_t expanded_settings;
166444 profiler_metrics_t metrics;
166445
166446public:
166447 ProfilingInfo() = default;
166448 explicit ProfilingInfo(const profiler_settings_t &n_settings, const idx_t depth = 0);
166449 ProfilingInfo(ProfilingInfo &) = default;
166450 ProfilingInfo &
operator=(ProfilingInfo
const &) =
default;
166451
166452public:
166453 void ResetMetrics();
166455 static bool Enabled(const profiler_settings_t &settings, const MetricType metric);
166457 static void Expand(profiler_settings_t &settings, const MetricType metric);
166458
166459public:
166460 string GetMetricAsString(const MetricType metric) const;
166461 void WriteMetricsToLog(ClientContext &context);
166462 void WriteMetricsToJSON(duckdb_yyjson::yyjson_mut_doc *doc, duckdb_yyjson::yyjson_mut_val *destination);
166463
166464public:
166465 template <class METRIC_TYPE>
166466 METRIC_TYPE GetMetricValue(const MetricType type) const {
166467 auto val = metrics.at(type);
166468 return val.GetValue<METRIC_TYPE>();
166469 }
166470
166471 template <class METRIC_TYPE>
166472 void MetricUpdate(const MetricType type, const Value &value,
166473 const std::function<METRIC_TYPE(const METRIC_TYPE &, const METRIC_TYPE &)> &update_fun) {
166474 if (metrics.find(type) == metrics.end()) {
166475 metrics[type] = value;
166476 return;
166477 }
166478 auto new_value = update_fun(metrics[type].GetValue<METRIC_TYPE>(), value.GetValue<METRIC_TYPE>());
166479 metrics[type] = Value::CreateValue(new_value);
166480 }
166481
166482 template <class METRIC_TYPE>
166483 void MetricUpdate(const MetricType type, const METRIC_TYPE &value,
166484 const std::function<METRIC_TYPE(const METRIC_TYPE &, const METRIC_TYPE &)> &update_fun) {
166485 auto new_value = Value::CreateValue(value);
166486 MetricUpdate<METRIC_TYPE>(type, new_value, update_fun);
166487 }
166488
166489 template <class METRIC_TYPE>
166490 void MetricSum(const MetricType type, const Value &value) {
166491 MetricUpdate<METRIC_TYPE>(type, value, [](const METRIC_TYPE &old_value, const METRIC_TYPE &new_value) {
166492 return old_value + new_value;
166493 });
166494 }
166495
166496 template <class METRIC_TYPE>
166497 void MetricSum(const MetricType type, const METRIC_TYPE &value) {
166498 auto new_value = Value::CreateValue(value);
166499 return MetricSum<METRIC_TYPE>(type, new_value);
166500 }
166501
166502 template <class METRIC_TYPE>
166503 void MetricMax(const MetricType type, const Value &value) {
166504 MetricUpdate<METRIC_TYPE>(type, value, [](const METRIC_TYPE &old_value, const METRIC_TYPE &new_value) {
166505 return MaxValue(old_value, new_value);
166506 });
166507 }
166508
166509 template <class METRIC_TYPE>
166510 void MetricMax(const MetricType type, const METRIC_TYPE &value) {
166511 auto new_value = Value::CreateValue(value);
166512 return MetricMax<METRIC_TYPE>(type, new_value);
166513 }
166514};
166515
166516
166517template <>
166518inline InsertionOrderPreservingMap<string>
166519ProfilingInfo::GetMetricValue<InsertionOrderPreservingMap<string>>(const MetricType type) const {
166520 auto val = metrics.at(type);
166521 InsertionOrderPreservingMap<string> result;
166522 auto children = MapValue::GetChildren(val);
166523 for (auto &child : children) {
166524 auto struct_children = StructValue::GetChildren(child);
166525 auto key = struct_children[0].GetValue<string>();
166526 auto value = struct_children[1].GetValue<string>();
166527 result.insert(key, value);
166528 }
166529 return result;
166530}
166531}
166532
166533
166534
166535
166536
166537
166538
166539
166540
166541
166542
166543
166544
166545
166546
166547
166548
166549
166550
166551
166552
166553
166554
166555
166556
166557
166558namespace duckdb {
166559
166560enum class LambdaSyntax :
uint8_t { DEFAULT = 0, ENABLE_SINGLE_ARROW = 1, DISABLE_SINGLE_ARROW = 2 };
166561
166562}
166563
166564
166565namespace duckdb {
166566
166567enum class LambdaSyntaxType :
uint8_t { SINGLE_ARROW_STORAGE = 0, SINGLE_ARROW = 1, LAMBDA_KEYWORD = 2 };
166568
166572class LambdaExpression : public ParsedExpression {
166573public:
166574 static constexpr const ExpressionClass
TYPE = ExpressionClass::LAMBDA;
166575
166576public:
166577 LambdaExpression(vector<string> named_parameters_p, unique_ptr<ParsedExpression> expr);
166578 LambdaExpression(unique_ptr<ParsedExpression> lhs, unique_ptr<ParsedExpression> expr);
166579
166581 LambdaSyntaxType syntax_type;
166584 unique_ptr<ParsedExpression> lhs;
166586 unique_ptr<ParsedExpression> expr;
166588 unique_ptr<ParsedExpression> copied_expr;
166589
166590public:
166593 vector<reference<const ParsedExpression>> ExtractColumnRefExpressions(string &error_message) const;
166595 static string InvalidParametersErrorMessage();
166597 static bool IsLambdaParameter(const vector<unordered_set<string>> &lambda_params, const string &column_name);
166598
166599 string ToString() const override;
166600 static bool Equal(const LambdaExpression &a, const LambdaExpression &b);
166601 hash_t Hash()
const override;
166602 unique_ptr<ParsedExpression> Copy() const override;
166603
166604 void Serialize(Serializer &serializer) const override;
166605 static unique_ptr<ParsedExpression> Deserialize(Deserializer &deserializer);
166606
166607private:
166608 LambdaExpression();
166609};
166610
166611}
166612
166613
166614
166615
166616
166617
166618
166619
166620
166621
166622
166623
166624
166625
166626
166627
166628
166629
166630
166631
166632
166633
166634
166635
166636
166637
166638
166639
166640
166641
166642
166643
166644
166645
166646
166647
166648
166649
166650
166651
166652
166653
166654
166655
166656
166657
166658
166659
166660
166661
166662
166663namespace duckdb {
166664
166666class ProfilingNode {
166667public:
166668 explicit ProfilingNode() {
166669 }
166670 virtual ~ProfilingNode() {};
166671
166672private:
166673 ProfilingInfo profiling_info;
166674
166675public:
166677 vector<unique_ptr<ProfilingNode>> children;
166678
166679public:
166680 idx_t GetChildCount() {
166681 return children.size();
166682 }
166683 ProfilingInfo &GetProfilingInfo() {
166684 return profiling_info;
166685 }
166686 const ProfilingInfo &GetProfilingInfo() const {
166687 return profiling_info;
166688 }
166689 optional_ptr<ProfilingNode> GetChild(idx_t idx) {
166690 return children[idx].get();
166691 }
166692 optional_ptr<ProfilingNode> AddChild(unique_ptr<ProfilingNode> child) {
166693 children.push_back(std::move(child));
166694 return children.back().get();
166695 }
166696};
166697
166698}
166699
166700
166701
166702
166703
166704
166705
166706
166707
166708
166709
166710
166711
166712
166713
166714
166715
166716
166717namespace duckdb_yyjson {
166720}
166721
166722namespace duckdb {
166723
166724struct ActiveTimer;
166725
166726
166727struct QueryMetrics {
166728public:
166729 QueryMetrics() {
166730 Reset();
166731 }
166732
166733 ProfilingInfo query_global_info;
166734
166735 std::string query_name;
166736 unique_ptr<ActiveTimer> latency_timer;
166737
166738public:
166739 void UpdateMetric(const MetricType metric, idx_t addition) {
166740 active_metrics[GetMetricsIndex(metric)] += addition;
166741 }
166742
166743 idx_t GetMetricValue(
const MetricType metric)
const {
166744 return active_metrics[GetMetricsIndex(metric)];
166745 }
166746
166747 double GetMetricInSeconds(const MetricType metric) const {
166748 return static_cast<double>(active_metrics[GetMetricsIndex(metric)]) / 1e9;
166749 }
166750
166751 void Reset() {
166752 for(idx_t i = 0; i < ACTIVELY_TRACKED_METRICS; i++) {
166753 active_metrics[i] = 0;
166754 }
166755
166756 latency_timer.reset();
166757 query_name = "";
166758 }
166759
166760 void Merge(const QueryMetrics &other) {
166761 for(idx_t i = 0; i < ACTIVELY_TRACKED_METRICS; i++) {
166762 active_metrics[i] += other.active_metrics[i];
166763 }
166764 }
166765
166766 static idx_t GetMetricsIndex(MetricType type) {
166767 switch(type) {
166768 case MetricType::ATTACH_LOAD_STORAGE_LATENCY: return 0;
166769 case MetricType::ATTACH_REPLAY_WAL_LATENCY: return 1;
166770 case MetricType::CHECKPOINT_LATENCY: return 2;
166771 case MetricType::COMMIT_LOCAL_STORAGE_LATENCY: return 3;
166772 case MetricType::LATENCY: return 4;
166773 case MetricType::WAITING_TO_ATTACH_LATENCY: return 5;
166774 case MetricType::WRITE_TO_WAL_LATENCY: return 6;
166775 case MetricType::TOTAL_BYTES_READ: return 7;
166776 case MetricType::TOTAL_BYTES_WRITTEN: return 8;
166777 case MetricType::TOTAL_MEMORY_ALLOCATED: return 9;
166778 case MetricType::WAL_REPLAY_ENTRY_COUNT: return 10;
166779 default:
166780 throw InternalException("MetricType %s is not actively tracked.", EnumUtil::ToString(type));
166781 }
166782 }
166783
166784private:
166785 static constexpr const idx_t ACTIVELY_TRACKED_METRICS = 11;
166786
166787 atomic<idx_t> active_metrics[ACTIVELY_TRACKED_METRICS];
166788};
166789
166790class ProfilingUtils {
166791public:
166792 static void SetMetricToDefault(profiler_metrics_t &metrics, const MetricType &type);
166793 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);
166794 static void CollectMetrics(const MetricType &type, QueryMetrics &query_metrics, Value &metric, ProfilingNode &node, ProfilingInfo &child_info);
166795};
166796
166797struct ActiveTimer {
166798public:
166799 ActiveTimer() : metric(MetricType::EXTRA_INFO), is_active(false) {
166800 }
166801 ActiveTimer(QueryMetrics &query_metrics, const MetricType metric, const bool is_active = true) : query_metrics(query_metrics), metric(metric), is_active(is_active) {
166802
166803 if (!is_active) {
166804 return;
166805 }
166806 profiler.Start();
166807 }
166808 ~ActiveTimer() {
166809 if (is_active) {
166810
166811 EndTimer();
166812 }
166813 }
166814
166815 ActiveTimer(const ActiveTimer &other) = delete;
166816 ActiveTimer &
operator=(
const ActiveTimer &) =
delete;
166818 ActiveTimer(ActiveTimer &&other) noexcept : is_active(false) {
166819 std::swap(query_metrics, other.query_metrics);
166820 std::swap(metric, other.metric);
166821 std::swap(profiler, other.profiler);
166822 std::swap(is_active, other.is_active);
166823 }
166824 ActiveTimer &
operator=(ActiveTimer &&other)
noexcept {
166825 std::swap(query_metrics, other.query_metrics);
166826 std::swap(metric, other.metric);
166827 std::swap(profiler, other.profiler);
166828 std::swap(is_active, other.is_active);
166829 return *this;
166830 }
166831
166832
166833 void EndTimer() {
166834 if (!is_active) {
166835 return;
166836 }
166837
166838 is_active = false;
166839 profiler.End();
166840 query_metrics->UpdateMetric(metric, profiler.ElapsedNanos());
166841 }
166842
166843 void Reset() {
166844 if (!is_active) {
166845 return;
166846 }
166847 profiler.Reset();
166848 is_active = false;
166849 }
166850
166851private:
166852 optional_ptr<QueryMetrics> query_metrics;
166853 MetricType metric;
166854 Profiler profiler;
166855 bool is_active;
166856};
166857
166858}
166859
166860
166861namespace duckdb {
166862
166863class ClientContext;
166864class ExpressionExecutor;
166865class ProfilingNode;
166866class PhysicalOperator;
166867class SQLStatement;
166868struct ActiveTimer;
166869
166870enum class ProfilingCoverage :
uint8_t { SELECT = 0, ALL = 1 };
166871
166872struct OperatorInformation {
166873 explicit OperatorInformation() {
166874 }
166875
166876 string name;
166877
166878 double time = 0;
166879 idx_t elements_returned = 0;
166880 idx_t result_set_size = 0;
166881 idx_t system_peak_buffer_manager_memory = 0;
166882 idx_t system_peak_temp_directory_size = 0;
166883 idx_t rows_scanned = 0;
166884
166885 InsertionOrderPreservingMap<string> extra_info;
166886
166887 template <typename T>
166888 void AddMetric(MetricType type, T metric) {
166889 switch (type) {
166890 case MetricType::OPERATOR_TIMING:
166891 time += metric;
166892 break;
166893 case MetricType::OPERATOR_CARDINALITY:
166894 elements_returned += LossyNumericCast<idx_t>(metric);
166895 break;
166896 case MetricType::RESULT_SET_SIZE:
166897 result_set_size += LossyNumericCast<idx_t>(metric);
166898 break;
166899 case MetricType::SYSTEM_PEAK_BUFFER_MEMORY: {
166900 if (metric > system_peak_buffer_manager_memory) {
166901 system_peak_buffer_manager_memory += LossyNumericCast<idx_t>(metric);
166902 }
166903 break;
166904 }
166905 case MetricType::SYSTEM_PEAK_TEMP_DIR_SIZE: {
166906 if (metric > system_peak_temp_directory_size) {
166907 system_peak_temp_directory_size = LossyNumericCast<idx_t>(metric);
166908 }
166909 break;
166910 }
166911 case MetricType::OPERATOR_ROWS_SCANNED:
166912 rows_scanned = LossyNumericCast<idx_t>(metric);
166913 break;
166914 default:
166915 throw InternalException("OperatorProfiler: Unknown metric type");
166916 }
166917 }
166918};
166919
166922class OperatorProfiler {
166923 friend class QueryProfiler;
166924
166925public:
166926 DUCKDB_API explicit OperatorProfiler(ClientContext &context);
166927 ~OperatorProfiler() {
166928 }
166929
166930public:
166931 DUCKDB_API void StartOperator(optional_ptr<const PhysicalOperator> phys_op);
166932 DUCKDB_API void EndOperator(optional_ptr<DataChunk> chunk);
166933 DUCKDB_API void FinishSource(GlobalSourceState &gstate, LocalSourceState &lstate);
166934
166936 DUCKDB_API void Flush(const PhysicalOperator &phys_op);
166937 DUCKDB_API OperatorInformation &GetOperatorInfo(const PhysicalOperator &phys_op);
166938 DUCKDB_API bool OperatorInfoIsInitialized(const PhysicalOperator &phys_op);
166939
166940public:
166941 ClientContext &context;
166942
166943private:
166945 bool enabled;
166947 profiler_settings_t settings;
166948
166950 Profiler op;
166952 optional_ptr<const PhysicalOperator> active_operator;
166954 reference_map_t<const PhysicalOperator, OperatorInformation> operator_infos;
166955};
166956
166958class QueryProfiler {
166959public:
166960 using TreeMap = reference_map_t<const PhysicalOperator, reference<ProfilingNode>>;
166961
166962public:
166963 DUCKDB_API explicit QueryProfiler(ClientContext &context);
166964
166965public:
166966 DUCKDB_API bool IsEnabled() const;
166967 DUCKDB_API bool IsDetailedEnabled() const;
166968 DUCKDB_API ProfilerPrintFormat GetPrintFormat(ExplainFormat
format = ExplainFormat::DEFAULT)
const;
166969 DUCKDB_API bool PrintOptimizerOutput() const;
166970 DUCKDB_API string GetSaveLocation() const;
166971
166972 DUCKDB_API static QueryProfiler &Get(ClientContext &context);
166973
166974 DUCKDB_API void Start(const string &query);
166975 DUCKDB_API void Reset();
166976 DUCKDB_API void StartQuery(const string &query, bool is_explain_analyze = false, bool start_at_optimizer = false);
166977 DUCKDB_API void EndQuery();
166979 DUCKDB_API void FinalizeMetrics();
166980
166982 DUCKDB_API void AddToCounter(MetricType type, const idx_t amount);
166983
166985 DUCKDB_API ActiveTimer StartTimer(MetricType type);
166986
166987 DUCKDB_API void StartExplainAnalyze();
166988
166990 DUCKDB_API void Flush(OperatorProfiler &profiler);
166992 DUCKDB_API void SetBlockedTime(const double &blocked_thread_time);
166993
166994 DUCKDB_API void StartPhase(MetricType phase_metric);
166995 DUCKDB_API void EndPhase();
166996
166997 DUCKDB_API void Initialize(const PhysicalOperator &root);
166998
166999 DUCKDB_API string QueryTreeToString() const;
167000 DUCKDB_API void QueryTreeToStream(std::ostream &str) const;
167001 DUCKDB_API void Print();
167002
167005 DUCKDB_API
string ToString(ExplainFormat
format = ExplainFormat::DEFAULT)
const;
167006 DUCKDB_API
string ToString(ProfilerPrintFormat
format)
const;
167007
167008
167009 static Value JSONSanitize(const Value &input);
167010 static string JSONSanitize(const string &text);
167011 static string DrawPadded(const string &str, idx_t width);
167012 DUCKDB_API void ToLog() const;
167013 DUCKDB_API string ToJSON() const;
167014 DUCKDB_API void WriteToFile(const char *path, string &info) const;
167015 DUCKDB_API
idx_t GetBytesRead()
const;
167016 DUCKDB_API
idx_t GetBytesWritten()
const;
167017
167018 idx_t OperatorSize() {
167019 return tree_map.size();
167020 }
167021
167022 void Finalize(ProfilingNode &node);
167023
167025 optional_ptr<ProfilingNode> GetRoot() {
167026 return root.get();
167027 }
167028
167031 DUCKDB_API void GetRootUnderLock(const std::function<void(optional_ptr<ProfilingNode>)> &callback) {
167032 lock_guard<std::mutex> guard(lock);
167033 callback(GetRoot());
167034 }
167035
167036private:
167037 unique_ptr<ProfilingNode> CreateTree(const PhysicalOperator &root, const profiler_settings_t &settings,
167038 const idx_t depth = 0);
167039 void Render(const ProfilingNode &node, std::ostream &str) const;
167040 string RenderDisabledMessage(ProfilerPrintFormat
format)
const;
167041
167042private:
167043 ClientContext &context;
167044
167046 bool running;
167048 mutable std::mutex lock;
167049
167051 bool query_requires_profiling;
167052
167054 unique_ptr<ProfilingNode> root;
167055
167057 QueryMetrics query_metrics;
167058
167060 TreeMap tree_map;
167062 bool is_explain_analyze;
167064 bool metrics_finalized;
167065
167066public:
167067 const TreeMap &GetTreeMap() const {
167068 return tree_map;
167069 }
167070
167071private:
167073 Profiler phase_profiler;
167075 using PhaseTimingStorage = unordered_map<MetricType, double, MetricTypeHashFunction>;
167076 PhaseTimingStorage phase_timings;
167077 using PhaseTimingItem = PhaseTimingStorage::value_type;
167079 vector<MetricType> phase_stack;
167080
167081private:
167082 void MoveOptimizerPhasesToRoot();
167083 void FinalizeMetricsInternal();
167084
167087 bool OperatorRequiresProfiling(const PhysicalOperatorType op_type);
167088 ExplainFormat GetExplainFormat(ProfilerPrintFormat
format)
const;
167089};
167090
167091}
167092
167093
167094
167095
167096
167097
167098
167099
167100
167101
167102
167103
167104
167105
167106
167107
167108
167109
167110
167111
167112
167113
167114
167115
167116
167117
167118
167119
167120
167121
167122
167123
167124
167125
167126
167127
167128
167129
167130namespace duckdb {
167131
167132enum class SetScope :
uint8_t {
167133 AUTOMATIC = 0,
167134 LOCAL = 1,
167135 SESSION = 2,
167136 GLOBAL = 3,
167137 VARIABLE = 4
167138};
167139
167140}
167141
167142
167143namespace duckdb {
167144class ClientContext;
167145class DatabaseInstance;
167146struct DBConfig;
167147
167150 GLOBAL,
167152 LOCAL,
167154 SECRET,
167156 INVALID
167157};
167158
167160 INVALID,
167169};
167170
167171struct SettingLookupResult {
167172public:
167173 SettingLookupResult() : scope(
SettingScope::INVALID) {
167174 }
167175 explicit SettingLookupResult(SettingScope scope) : scope(scope) {
167176 D_ASSERT(scope != SettingScope::INVALID);
167177 }
167178
167179public:
167180 operator bool() {
167181 return scope != SettingScope::INVALID;
167182 }
167183
167184public:
167186 D_ASSERT(scope != SettingScope::INVALID);
167187 return scope;
167188 }
167189
167190private:
167192};
167193
167194struct SettingCallbackInfo {
167195 explicit SettingCallbackInfo(ClientContext &context, SetScope scope);
167196 explicit SettingCallbackInfo(DBConfig &config, optional_ptr<DatabaseInstance> db);
167197
167198 DBConfig &config;
167199 optional_ptr<DatabaseInstance>
db;
167200 optional_ptr<ClientContext> context;
167201 SetScope scope;
167202};
167203
167204typedef void (*set_callback_t)(SettingCallbackInfo &info, Value ¶meter);
167205typedef void (*set_global_function_t)(DatabaseInstance *
db, DBConfig &config,
const Value ¶meter);
167206typedef void (*set_local_function_t)(ClientContext &context, const Value ¶meter);
167207typedef void (*reset_global_function_t)(DatabaseInstance *
db, DBConfig &config);
167208typedef void (*reset_local_function_t)(ClientContext &context);
167209typedef Value (*get_setting_function_t)(const ClientContext &context);
167210
167211struct ConfigurationOption {
167212 const char *name;
167213 const char *description;
167214 const char *parameter_type;
167215 set_global_function_t set_global;
167216 set_local_function_t set_local;
167217 reset_global_function_t reset_global;
167218 reset_local_function_t reset_local;
167219 get_setting_function_t get_setting;
167221 const char *default_value;
167222 set_callback_t set_callback;
167223 optional_idx setting_idx;
167224};
167225
167226struct ConfigurationAlias {
167227 const char *alias;
167228 idx_t option_index;
167229};
167230
167231typedef void (*set_option_callback_t)(ClientContext &context, SetScope scope, Value ¶meter);
167232
167233struct ExtensionOption {
167234 ExtensionOption() : set_function(nullptr), default_scope(SetScope::AUTOMATIC) {
167235 }
167236
167237 ExtensionOption(string description_p, LogicalType type_p, set_option_callback_t set_function_p,
167238 Value default_value_p, SetScope default_scope_p)
167239 : description(std::move(description_p)), type(std::move(type_p)), set_function(set_function_p),
167240 default_value(std::move(default_value_p)), default_scope(default_scope_p) {
167241 }
167242
167243 string description;
167244 LogicalType type;
167245 set_option_callback_t set_function;
167246 Value default_value;
167247 SetScope default_scope;
167248 optional_idx setting_index;
167249};
167250
167251}
167252
167253
167254
167255namespace duckdb {
167256
167257struct GenericSetting {
167258 GenericSetting() : is_set(false) {
167259 }
167260
167261 bool is_set;
167262 Value value;
167263};
167264
167265struct UserSettingsMap {
167266public:
167267 void SetUserSetting(idx_t setting_index, Value target_value);
167268 void ClearSetting(idx_t setting_index);
167269 bool IsSet(idx_t setting_index) const;
167270 bool TryGetSetting(idx_t setting_index, Value &result_value) const;
167271
167272private:
167273 vector<GenericSetting> settings;
167274};
167275
167276#ifndef __MINGW32__
167277struct GlobalUserSettings;
167278
167279struct CachedGlobalSettings {
167280 CachedGlobalSettings();
167281 CachedGlobalSettings(const GlobalUserSettings &global_user_settings, idx_t version, UserSettingsMap settings);
167282
167283 optional_ptr<const GlobalUserSettings> global_user_settings;
167285 UserSettingsMap settings;
167286 hugeint_t uuid;
167287};
167288#endif
167289
167290struct GlobalUserSettings {
167291public:
167292 GlobalUserSettings();
167293
167294 GlobalUserSettings(const GlobalUserSettings &other);
167295 GlobalUserSettings &
operator=(
const GlobalUserSettings &);
167296
167297 void SetUserSetting(idx_t setting_index, Value target_value);
167298 void ClearSetting(idx_t setting_index);
167299 bool IsSet(idx_t setting_index) const;
167300 SettingLookupResult TryGetSetting(idx_t setting_index, Value &result_value) const;
167301 bool HasExtensionOption(const string &name) const;
167302 idx_t AddExtensionOption(
const string &name, ExtensionOption extension_option);
167303 case_insensitive_map_t<ExtensionOption> GetExtensionSettings() const;
167304 bool TryGetExtensionOption(
const String &name, ExtensionOption &result)
const;
167305 hugeint_t GetUUID() const;
167306
167307#ifndef __MINGW32__
167308 CachedGlobalSettings &GetSettings() const;
167309#endif
167310
167311private:
167312 mutable mutex lock;
167314 UserSettingsMap settings_map;
167316 case_insensitive_map_t<ExtensionOption> extension_parameters;
167318 atomic<idx_t> settings_version;
167320 hugeint_t uuid;
167321};
167322
167323struct LocalUserSettings {
167324public:
167325 ~LocalUserSettings();
167326
167327 void SetUserSetting(idx_t setting_index, Value target_value);
167328 void ClearSetting(idx_t setting_index);
167329 bool IsSet(idx_t setting_index) const;
167330 SettingLookupResult TryGetSetting(const GlobalUserSettings &global_settings, idx_t setting_index,
167331 Value &result_value) const;
167332
167333private:
167335 UserSettingsMap settings_map;
167336};
167337}
167338
167339
167340namespace duckdb {
167341
167342class ClientContext;
167343class PhysicalResultCollector;
167344class PreparedStatementData;
167345
167346typedef std::function<unique_ptr<PhysicalOperator>(ClientContext &context, PreparedStatementData &data)>
167347 get_result_collector_t;
167348
167349struct ClientConfig {
167351 bool enable_profiler = false;
167353 bool enable_detailed_profiling = false;
167355 ProfilerPrintFormat profiler_print_format = ProfilerPrintFormat::QUERY_TREE;
167358 string profiler_save_location;
167361 profiler_settings_t profiler_settings = MetricsUtils::GetDefaultMetrics();
167363 LogicalTypeId profiler_settings_type = LogicalTypeId::VARCHAR;
167364
167367 bool emit_profiler_output = true;
167368
167370 const char *system_progress_bar_disable_reason = nullptr;
167372 bool enable_progress_bar = false;
167374 bool print_progress_bar = true;
167376 int wait_time = 2000;
167377
167379 bool query_verification_enabled = false;
167381 bool verify_external = false;
167383 bool verify_fetch_row = false;
167385 bool verify_serializer = false;
167387 bool enable_optimizer = true;
167389 bool enable_caching_operators = true;
167391 bool verify_parallelism = false;
167393 bool force_external = false;
167395 bool force_fetch_row = false;
167398 bool use_replacement_scans = true;
167399
167401 idx_t streaming_buffer_size = 1000000;
167402
167404 progress_bar_display_create_func_t display_create_func = nullptr;
167405
167408 ProfilingCoverage profiling_coverage = ProfilingCoverage::SELECT;
167409
167411 LocalUserSettings user_settings;
167412
167414 case_insensitive_map_t<Value> user_variables;
167415
167417 get_result_collector_t get_result_collector = nullptr;
167418
167420 bool enable_http_logging = true;
167421
167424 string http_logging_output;
167425
167426public:
167427 static ClientConfig &GetConfig(ClientContext &context);
167428 static const ClientConfig &GetConfig(const ClientContext &context);
167429
167430 bool AnyVerification() const;
167431
167432 void SetUserVariable(
const String &name, Value value);
167433 bool GetUserVariable(const string &name, Value &result);
167434 void ResetUserVariable(
const String &name);
167435
167436public:
167437 void SetDefaultStreamingBufferSize();
167438};
167439
167440struct ScopedConfigSetting {
167441public:
167442 using config_modify_func_t = std::function<void(ClientConfig &config)>;
167443
167444public:
167445 explicit ScopedConfigSetting(ClientConfig &config, config_modify_func_t set_f = nullptr,
167446 config_modify_func_t unset_f = nullptr)
167447 : config(config), set(std::move(set_f)), unset(std::move(unset_f)) {
167448 if (set) {
167449 set(config);
167450 }
167451 }
167452 ~ScopedConfigSetting() {
167453 if (unset) {
167454 unset(config);
167455 }
167456 }
167457
167458public:
167459 ClientConfig &config;
167460 config_modify_func_t set;
167461 config_modify_func_t unset;
167462};
167463
167464}
167465
167466
167467
167468
167469
167470
167471
167472
167473
167474
167475
167476
167477
167478
167479
167480
167481
167482
167483
167484
167485
167486
167487
167488
167489namespace duckdb {
167490class TransactionException : public Exception {
167491public:
167492 DUCKDB_API explicit TransactionException(const string &msg);
167493
167494 template <typename... ARGS>
167495 explicit TransactionException(const string &msg, ARGS &&...params)
167496 : TransactionException(ConstructMessage(msg, std::forward<ARGS>(
params)...)) {
167497 }
167498};
167499}
167500
167501
167502
167503
167504
167505
167506
167507
167508
167509
167510
167511
167512
167513
167514
167515
167516
167517
167518
167519
167520
167521
167522
167523
167524
167525
167526
167527
167528
167529
167530namespace duckdb {
167531
167532class DataChunk;
167533
167535class ChunkScanState {
167536public:
167537 explicit ChunkScanState();
167538 virtual ~ChunkScanState();
167539
167540public:
167541 ChunkScanState(const ChunkScanState &other) = delete;
167542 ChunkScanState(ChunkScanState &&other) = default;
167543 ChunkScanState &
operator=(
const ChunkScanState &other) =
delete;
167544 ChunkScanState &
operator=(ChunkScanState &&other) =
default;
167545
167546public:
167547 virtual bool LoadNextChunk(ErrorData &error) = 0;
167548 virtual bool HasError() const = 0;
167549 virtual ErrorData &GetError() = 0;
167550 virtual const vector<LogicalType> &Types() const = 0;
167551 virtual const vector<string> &Names() const = 0;
167552 idx_t CurrentOffset()
const;
167553 idx_t RemainingInChunk()
const;
167554 DataChunk &CurrentChunk();
167555 bool ChunkIsEmpty() const;
167556 bool Finished() const;
167557 bool ScanStarted() const;
167558 void IncreaseOffset(idx_t increment, bool unsafe = false);
167559
167560protected:
167562 bool finished = false;
167563 unique_ptr<DataChunk> current_chunk;
167564};
167565
167566}
167567
167568
167569
167570
167571
167572
167573
167574
167575
167576
167577
167578
167579
167580
167581
167582
167583
167584
167585
167586
167587
167588
167589
167590
167591
167592
167593
167594
167595
167596
167597
167598
167599#include <cstdint>
167600
167601namespace duckdb {
167602
167603enum class ArrowTypeInfoType :
uint8_t {
LIST, STRUCT, DATE_TIME,
STRING, ARRAY, DECIMAL };
167604
167605}
167606
167607
167608
167609namespace duckdb {
167610
167611
167612
167613
167614enum class ArrowDateTimeType :
uint8_t {
167615 MILLISECONDS,
167616 MICROSECONDS,
167617 NANOSECONDS,
167618 SECONDS,
167619 DAYS,
167620 MONTHS,
167621 MONTH_DAY_NANO
167622};
167623
167624}
167625
167626
167627
167628namespace duckdb {
167629
167630
167631
167632
167633enum class ArrowVariableSizeType :
uint8_t { NORMAL, FIXED_SIZE, SUPER_SIZE, VIEW };
167634
167635}
167636
167637
167638
167639namespace duckdb {
167640
167642
167643enum class ArrowArrayPhysicalType :
uint8_t { DICTIONARY_ENCODED, RUN_END_ENCODED, DEFAULT };
167644
167645struct ArrowTypeInfo {
167646public:
167647 explicit ArrowTypeInfo() : type() {
167648 }
167649
167650 explicit ArrowTypeInfo(ArrowTypeInfoType type);
167651 virtual ~ArrowTypeInfo();
167652
167653 ArrowTypeInfoType type;
167654
167655public:
167656 template <class TARGET>
167657 TARGET &Cast() {
167658 D_ASSERT(dynamic_cast<TARGET *>(this));
167659 if (type != TARGET::TYPE) {
167660 throw InternalException("Failed to cast ArrowTypeInfo, type mismatch (expected: %s, got: %s)",
167661 EnumUtil::ToString(TARGET::TYPE), EnumUtil::ToString(type));
167662 }
167663 return reinterpret_cast<TARGET &>(*this);
167664 }
167665 template <class TARGET>
167666 const TARGET &Cast() const {
167667 D_ASSERT(dynamic_cast<const TARGET *>(this));
167668 if (type != TARGET::TYPE) {
167669 throw InternalException("Failed to cast ArrowTypeInfo, type mismatch (expected: %s, got: %s)",
167670 EnumUtil::ToString(TARGET::TYPE), EnumUtil::ToString(type));
167671 }
167672 return reinterpret_cast<const TARGET &>(*this);
167673 }
167674};
167675
167676struct ArrowStructInfo : public ArrowTypeInfo {
167677public:
167678 static constexpr const ArrowTypeInfoType
TYPE = ArrowTypeInfoType::STRUCT;
167679
167680public:
167681 explicit ArrowStructInfo(vector<shared_ptr<ArrowType>> children);
167682 ~ArrowStructInfo() override;
167683
167684public:
167685 idx_t ChildCount()
const;
167686 const ArrowType &GetChild(idx_t index)
const;
167687 const vector<shared_ptr<ArrowType>> &GetChildren() const;
167688
167689private:
167690 vector<shared_ptr<ArrowType>> children;
167691};
167692
167693struct ArrowDateTimeInfo : public ArrowTypeInfo {
167694public:
167695 static constexpr const ArrowTypeInfoType
TYPE = ArrowTypeInfoType::DATE_TIME;
167696
167697public:
167698 explicit ArrowDateTimeInfo(ArrowDateTimeType size);
167699 ~ArrowDateTimeInfo() override;
167700
167701public:
167702 ArrowDateTimeType GetDateTimeType() const;
167703
167704private:
167705 ArrowDateTimeType size_type;
167706};
167707
167708enum class DecimalBitWidth :
uint8_t { DECIMAL_32, DECIMAL_64, DECIMAL_128, DECIMAL_256 };
167709
167710struct ArrowDecimalInfo final : public ArrowTypeInfo {
167711public:
167712 static constexpr const ArrowTypeInfoType
TYPE = ArrowTypeInfoType::DECIMAL;
167713
167714public:
167715 explicit ArrowDecimalInfo(DecimalBitWidth bit_width);
167716 ~ArrowDecimalInfo() override;
167717
167718public:
167719 DecimalBitWidth GetBitWidth() const;
167720
167721private:
167722 DecimalBitWidth bit_width;
167723};
167724
167725struct ArrowStringInfo : public ArrowTypeInfo {
167726public:
167727 static constexpr const ArrowTypeInfoType
TYPE = ArrowTypeInfoType::STRING;
167728
167729public:
167730 explicit ArrowStringInfo(ArrowVariableSizeType size);
167731 explicit ArrowStringInfo(idx_t fixed_size);
167732 ~ArrowStringInfo() override;
167733
167734public:
167735 ArrowVariableSizeType GetSizeType() const;
167736 idx_t FixedSize()
const;
167737
167738private:
167739 ArrowVariableSizeType size_type;
167741};
167742
167743struct ArrowListInfo : public ArrowTypeInfo {
167744public:
167745 static constexpr const ArrowTypeInfoType
TYPE = ArrowTypeInfoType::LIST;
167746
167747public:
167748 static unique_ptr<ArrowListInfo> ListView(shared_ptr<ArrowType> child, ArrowVariableSizeType size);
167749 static unique_ptr<ArrowListInfo> List(shared_ptr<ArrowType> child, ArrowVariableSizeType size);
167750 ~ArrowListInfo() override;
167751
167752public:
167753 ArrowVariableSizeType GetSizeType() const;
167754 bool IsView() const;
167756
167757private:
167758 explicit ArrowListInfo(shared_ptr<ArrowType> child, ArrowVariableSizeType size);
167759
167760private:
167761 ArrowVariableSizeType size_type;
167762 bool is_view = false;
167763 shared_ptr<ArrowType> child;
167764};
167765
167766struct ArrowArrayInfo : public ArrowTypeInfo {
167767public:
167768 static constexpr const ArrowTypeInfoType
TYPE = ArrowTypeInfoType::ARRAY;
167769
167770public:
167771 explicit ArrowArrayInfo(shared_ptr<ArrowType> child, idx_t fixed_size);
167772 ~ArrowArrayInfo() override;
167773
167774public:
167775 idx_t FixedSize()
const;
167777
167778private:
167779 shared_ptr<ArrowType> child;
167781};
167782
167783}
167784
167785
167786
167787namespace duckdb {
167788struct DBConfig;
167789
167790struct ArrowArrayScanState;
167791
167792typedef void (*cast_arrow_duck_t)(ClientContext &context, Vector &source, Vector &result,
idx_t count);
167793
167794typedef void (*cast_duck_arrow_t)(ClientContext &context, Vector &source, Vector &result,
idx_t count);
167795
167796class ArrowTypeExtensionData {
167797public:
167798 explicit ArrowTypeExtensionData(const LogicalType &duckdb_type, const LogicalType &internal_type_p,
167799 cast_arrow_duck_t arrow_to_duckdb = nullptr,
167800 cast_duck_arrow_t duckdb_to_arrow = nullptr)
167801 : arrow_to_duckdb(arrow_to_duckdb), duckdb_to_arrow(duckdb_to_arrow), duckdb_type(duckdb_type),
167802 internal_type(internal_type_p) {
167803 }
167804
167805 explicit ArrowTypeExtensionData(const LogicalType &duckdb_type)
167806 : duckdb_type(duckdb_type), internal_type(duckdb_type) {
167807 }
167808
167810 cast_arrow_duck_t arrow_to_duckdb = nullptr;
167812 cast_duck_arrow_t duckdb_to_arrow = nullptr;
167813
167814 LogicalType GetInternalType() const;
167815
167817 static unordered_map<idx_t, const shared_ptr<ArrowTypeExtensionData>>
167818 GetExtensionTypes(ClientContext &context, const vector<LogicalType> &duckdb_types);
167819 LogicalType GetDuckDBType() const;
167820
167821private:
167823 LogicalType duckdb_type;
167825 LogicalType internal_type;
167826};
167827
167829public:
167831 explicit ArrowType(LogicalType type_p, unique_ptr<ArrowTypeInfo> type_info =
nullptr)
167832 : type(std::move(type_p)), type_info(std::move(type_info)) {
167833 }
167834 explicit ArrowType(
string error_message_p,
bool not_implemented_p =
false)
167835 : type(
LogicalTypeId::INVALID), type_info(nullptr), error_message(std::move(error_message_p)),
167836 not_implemented(not_implemented_p) {
167837 }
167838
167839public:
167840 LogicalType GetDuckType(bool use_dictionary = false) const;
167841
167842 void SetDictionary(unique_ptr<ArrowType> dictionary);
167843 bool HasDictionary() const;
167844 const ArrowType &GetDictionary()
const;
167845
167846 bool RunEndEncoded() const;
167847 void SetRunEndEncoded();
167848
167849 template <class T>
167850 const T &GetTypeInfo() const {
167851 return type_info->Cast<T>();
167852 }
167853 void ThrowIfInvalid() const;
167854
167855 static unique_ptr<ArrowType> GetTypeFromFormat(
string &
format);
167856 static unique_ptr<ArrowType> GetTypeFromFormat(ClientContext &context, ArrowSchema &schema,
string &
format);
167857
167858 static unique_ptr<ArrowType> GetTypeFromSchema(ClientContext &context, ArrowSchema &schema);
167859
167860 static unique_ptr<ArrowType> CreateListType(ClientContext &context, ArrowSchema &child,
167861 ArrowVariableSizeType size_type, bool view);
167862
167863 static unique_ptr<ArrowType> GetArrowLogicalType(ClientContext &context, ArrowSchema &schema);
167864
167865 bool HasExtension() const;
167866
167867 ArrowArrayPhysicalType GetPhysicalType() const;
167868
167870 shared_ptr<ArrowTypeExtensionData> extension_data;
167871
167872protected:
167873 LogicalType type;
167875 unique_ptr<ArrowType> dictionary_type;
167877 bool run_end_encoded = false;
167878 unique_ptr<ArrowTypeInfo> type_info;
167880 string error_message;
167882 bool not_implemented = false;
167883};
167884
167885using arrow_column_map_t = unordered_map<idx_t, shared_ptr<ArrowType>>;
167886
167887struct ArrowTableSchema {
167888public:
167889 void AddColumn(idx_t index, shared_ptr<ArrowType> type, const string &name);
167890 const arrow_column_map_t &GetColumns() const;
167891 vector<LogicalType> &GetTypes();
167892 vector<string> &GetNames();
167893
167894private:
167895 arrow_column_map_t arrow_convert_data;
167896 vector<LogicalType> types;
167897 vector<string> column_names;
167898};
167899
167900}
167901
167902#include <mutex>
167903
167904namespace duckdb {
167905class ArrowSchemaMetadata;
167906struct DuckDBArrowSchemaHolder;
167907
167908struct DBConfig;
167909struct ArrowExtensionMetadata {
167910public:
167911 ArrowExtensionMetadata() {
167912 }
167913
167914 ArrowExtensionMetadata(string extension_name, string vendor_name, string type_name, string arrow_format);
167915
167916 hash_t GetHash()
const;
167917
167918 string ToString() const;
167919
167920 string GetExtensionName() const;
167921
167922 string GetVendorName() const;
167923
167924 string GetTypeName() const;
167925
167926 string GetArrowFormat() const;
167927
167928 void SetArrowFormat(string arrow_format);
167929
167930 bool IsCanonical() const;
167931
167932 bool operator==(
const ArrowExtensionMetadata &other)
const;
167933
167935 static constexpr const char *ARROW_EXTENSION_NON_CANONICAL = "arrow.opaque";
167936
167937private:
167939 string extension_name {};
167942 string vendor_name {};
167944 string type_name {};
167946 string arrow_format {};
167947};
167948
167949class ArrowTypeExtension;
167950
167951typedef void (*populate_arrow_schema_t)(DuckDBArrowSchemaHolder &root_holder, ArrowSchema &child,
167952 const LogicalType &type, ClientContext &context,
167953 const ArrowTypeExtension &extension);
167954
167955typedef unique_ptr<ArrowType> (*get_type_t)(ClientContext &context, const ArrowSchema &schema,
167956 const ArrowSchemaMetadata &schema_metadata);
167957
167958class ArrowTypeExtension {
167959public:
167960 ArrowTypeExtension() {};
167962 explicit ArrowTypeExtension(ArrowExtensionMetadata &extension_metadata, unique_ptr<ArrowType> type);
167964 ArrowTypeExtension(string extension_name, string arrow_format, shared_ptr<ArrowTypeExtensionData> type);
167965 ArrowTypeExtension(string vendor_name, string type_name, string arrow_format,
167966 shared_ptr<ArrowTypeExtensionData> type);
167967
167969 ArrowTypeExtension(string extension_name, populate_arrow_schema_t populate_arrow_schema, get_type_t get_type,
167970 shared_ptr<ArrowTypeExtensionData> type);
167971 ArrowTypeExtension(string vendor_name, string type_name, populate_arrow_schema_t populate_arrow_schema,
167972 get_type_t get_type, shared_ptr<ArrowTypeExtensionData> type, cast_arrow_duck_t arrow_to_duckdb,
167973 cast_duck_arrow_t duckdb_to_arrow);
167974
167975 ArrowExtensionMetadata GetInfo() const;
167976
167977 unique_ptr<ArrowType> GetType(ClientContext &context, const ArrowSchema &schema,
167978 const ArrowSchemaMetadata &schema_metadata) const;
167979
167980 shared_ptr<ArrowTypeExtensionData> GetTypeExtension() const;
167981
167983
167984 LogicalType GetLogicalType() const;
167985
167986 bool HasType() const;
167987
167988 static void PopulateArrowSchema(DuckDBArrowSchemaHolder &root_holder, ArrowSchema &child,
167989 const LogicalType &duckdb_type, ClientContext &context,
167990 const ArrowTypeExtension &extension);
167991
167993 populate_arrow_schema_t populate_arrow_schema = nullptr;
167995 get_type_t get_type = nullptr;
167996
167997private:
167999 ArrowExtensionMetadata extension_metadata;
168001 shared_ptr<ArrowTypeExtensionData> type_extension;
168002};
168003
168004struct HashArrowTypeExtension {
168005 size_t operator()(ArrowExtensionMetadata
const &arrow_extension_info)
const noexcept {
168006 return arrow_extension_info.GetHash();
168007 }
168008};
168009
168010struct TypeInfo {
168011 TypeInfo();
168012 explicit TypeInfo(const LogicalType &type);
168013 explicit TypeInfo(string alias);
168014 string alias;
168016 hash_t GetHash()
const;
168017 bool operator==(
const TypeInfo &other)
const;
168018};
168019
168020struct HashTypeInfo {
168021 size_t operator()(TypeInfo
const &type_info)
const noexcept {
168022 return type_info.GetHash();
168023 }
168024};
168025
168027struct ArrowTypeExtensionSet {
168028 ArrowTypeExtensionSet() {};
168029 static void Initialize(const DBConfig &config);
168030 std::mutex lock;
168031 unordered_map<ArrowExtensionMetadata, ArrowTypeExtension, HashArrowTypeExtension> type_extensions;
168032 unordered_map<TypeInfo, vector<ArrowExtensionMetadata>, HashTypeInfo> type_to_info;
168033};
168034
168035}
168036
168037
168038
168039
168040
168041
168042
168043
168044
168045
168046
168047
168048
168049
168050
168051
168052
168053
168054namespace duckdb {
168055
168056class CGroups {
168057public:
168058 static optional_idx GetMemoryLimit(FileSystem &fs);
168059 static idx_t GetCPULimit(FileSystem &fs, idx_t physical_cores);
168060};
168061
168062}
168063
168064
168065
168066
168067
168068
168069
168070
168071
168072
168073
168074
168075
168076
168077namespace duckdb {
168078
168079enum class AccessMode :
uint8_t {
UNDEFINED = 0, AUTOMATIC = 1, READ_ONLY = 2, READ_WRITE = 3 };
168080
168081}
168082
168083
168084
168085
168086
168087
168088
168089
168090
168091
168092
168093
168094
168095namespace duckdb {
168096
168097enum class CacheValidationMode :
uint8_t {
168098
168099 VALIDATE_ALL = 0,
168100
168101 VALIDATE_REMOTE = 1,
168102
168103 NO_VALIDATION = 2,
168104};
168105
168106}
168107
168108
168109
168110
168111
168112
168113
168114
168115
168116
168117
168118
168119
168120namespace duckdb {
168121
168122enum class ThreadPinMode :
uint8_t { OFF = 0, ON = 1, AUTO = 2 };
168123
168124}
168125
168126
168127
168128
168129
168130
168131
168132
168133
168134
168135
168136
168137
168138
168139
168140
168141
168142
168143
168144
168145
168146
168147
168148
168149
168150
168151
168152
168153
168154
168155
168156
168157
168158
168159
168160
168161
168162
168163
168164
168165
168166
168167
168168
168169
168170
168171
168172
168173
168174
168175
168176
168177
168178
168179
168180
168181
168182
168183
168184
168185
168186
168187
168188
168189namespace duckdb {
168190
168192struct JoinCondition {
168193public:
168194 JoinCondition() {
168195 }
168196
168199 static unique_ptr<Expression> CreateExpression(JoinCondition cond);
168200 static unique_ptr<Expression> CreateExpression(vector<JoinCondition> conditions);
168201
168202 void Serialize(Serializer &serializer) const;
168203 static JoinCondition Deserialize(Deserializer &deserializer);
168204
168205public:
168206 unique_ptr<Expression> left;
168207 unique_ptr<Expression> right;
168208 ExpressionType comparison;
168209};
168210
168211class JoinSide {
168212public:
168213 enum JoinValue :
uint8_t { NONE, LEFT, RIGHT, BOTH };
168214
168215 JoinSide() = default;
168216 constexpr JoinSide(JoinValue val) : value(val) {
168217 }
168218
168220 return value == a.value;
168221 }
168223 return value != a.value;
168224 }
168225
168226 static JoinSide CombineJoinSide(JoinSide left, JoinSide right);
168227 static JoinSide GetJoinSide(idx_t table_binding, const unordered_set<idx_t> &left_bindings,
168228 const unordered_set<uint64_t> &right_bindings);
168229 static JoinSide GetJoinSide(Expression &expression, const unordered_set<idx_t> &left_bindings,
168230 const unordered_set<idx_t> &right_bindings);
168231 static JoinSide GetJoinSide(const unordered_set<idx_t> &bindings, const unordered_set<idx_t> &left_bindings,
168232 const unordered_set<idx_t> &right_bindings);
168233
168234private:
168235 JoinValue value;
168236};
168237
168238}
168239
168240
168241
168242
168243
168244namespace duckdb {
168245class ClientContext;
168246class ColumnDataCollection;
168247
168248class PhysicalPlan {
168249public:
168250 explicit PhysicalPlan(Allocator &allocator) : arena(allocator) {};
168251
168252 ~PhysicalPlan() {
168253
168254 for (auto &op : ops) {
168255 auto &op_ref = op.get();
168256 op_ref.~PhysicalOperator();
168257 }
168258 }
168259
168260public:
168261 template <class T, class... ARGS>
168262 PhysicalOperator &Make(ARGS &&... args) {
168263 static_assert(std::is_base_of<PhysicalOperator, T>::value, "T must be a physical operator");
168264 auto ptr = arena.Make<T>(*this, std::forward<ARGS>(args)...);
168265 ops.push_back(*ptr);
168266 return *ptr;
168267 }
168268
168269 PhysicalOperator &Root() {
168270 D_ASSERT(root);
168271 return *root;
168272 }
168273 void SetRoot(PhysicalOperator &op) {
168274 root = op;
168275 }
168277 ArenaAllocator &ArenaRef() {
168278 return arena;
168279 }
168280
168281private:
168283 ArenaAllocator arena;
168285 vector<reference<PhysicalOperator>> ops;
168287 optional_ptr<PhysicalOperator> root;
168288};
168289
168291class PhysicalPlanGenerator {
168292public:
168293 explicit PhysicalPlanGenerator(ClientContext &context);
168294 ~PhysicalPlanGenerator();
168295
168296 LogicalDependencyList dependencies;
168299 unordered_map<idx_t, shared_ptr<ColumnDataCollection>> recursive_cte_tables;
168301 unordered_map<idx_t, shared_ptr<ColumnDataCollection>> recurring_cte_tables;
168303 unordered_map<idx_t, vector<const_reference<PhysicalOperator>>> materialized_ctes;
168305 idx_t delim_index = 0;
168306
168307public:
168310 unique_ptr<PhysicalPlan> Plan(unique_ptr<LogicalOperator> logical);
168311 PhysicalOperator &CreatePlan(LogicalOperator &op);
168312
168314 static bool UseBatchIndex(ClientContext &context, PhysicalOperator &plan);
168316 static bool PreserveInsertionOrder(ClientContext &context, PhysicalOperator &plan);
168318 static OrderPreservationType OrderPreservationRecursive(PhysicalOperator &op);
168319
168321 template <class T, class... ARGS>
168322 PhysicalOperator &Make(ARGS &&... args) {
168323 return physical_plan->Make<T>(std::forward<ARGS>(args)...);
168324 }
168325
168328 ArenaAllocator &ArenaRef();
168329
168330public:
168331 PhysicalOperator &ResolveDefaultsProjection(LogicalInsert &op, PhysicalOperator &child);
168332
168333protected:
168334 PhysicalOperator &CreatePlan(LogicalAggregate &op);
168335 PhysicalOperator &CreatePlan(LogicalAnyJoin &op);
168336 PhysicalOperator &CreatePlan(LogicalColumnDataGet &op);
168337 PhysicalOperator &CreatePlan(LogicalComparisonJoin &op);
168338 PhysicalOperator &CreatePlan(LogicalCopyDatabase &op);
168339 PhysicalOperator &CreatePlan(LogicalCreate &op);
168340 PhysicalOperator &CreatePlan(LogicalCreateTable &op);
168341 PhysicalOperator &CreatePlan(LogicalCreateIndex &op);
168342 PhysicalOperator &CreatePlan(LogicalCreateSecret &op);
168343 PhysicalOperator &CreatePlan(LogicalCrossProduct &op);
168344 PhysicalOperator &CreatePlan(LogicalDelete &op);
168345 PhysicalOperator &CreatePlan(LogicalDelimGet &op);
168346 PhysicalOperator &CreatePlan(LogicalDistinct &op);
168347 PhysicalOperator &CreatePlan(LogicalDummyScan &expr);
168348 PhysicalOperator &CreatePlan(LogicalEmptyResult &op);
168349 PhysicalOperator &CreatePlan(LogicalExpressionGet &op);
168350 PhysicalOperator &CreatePlan(LogicalExport &op);
168351 PhysicalOperator &CreatePlan(LogicalFilter &op);
168352 PhysicalOperator &CreatePlan(LogicalGet &op);
168353 PhysicalOperator &CreatePlan(LogicalLimit &op);
168354 PhysicalOperator &CreatePlan(LogicalMergeInto &op);
168355 PhysicalOperator &CreatePlan(LogicalOrder &op);
168356 PhysicalOperator &CreatePlan(LogicalTopN &op);
168357 PhysicalOperator &CreatePlan(LogicalPositionalJoin &op);
168358 PhysicalOperator &CreatePlan(LogicalProjection &op);
168359 PhysicalOperator &CreatePlan(LogicalInsert &op);
168360 PhysicalOperator &CreatePlan(LogicalCopyToFile &op);
168361 PhysicalOperator &CreatePlan(LogicalExplain &op);
168362 PhysicalOperator &CreatePlan(LogicalSetOperation &op);
168363 PhysicalOperator &CreatePlan(LogicalUpdate &op);
168364 PhysicalOperator &CreatePlan(LogicalPrepare &expr);
168365 PhysicalOperator &CreatePlan(LogicalWindow &expr);
168366 PhysicalOperator &CreatePlan(LogicalExecute &op);
168367 PhysicalOperator &CreatePlan(LogicalPragma &op);
168368 PhysicalOperator &CreatePlan(LogicalSample &op);
168369 PhysicalOperator &CreatePlan(LogicalSet &op);
168370 PhysicalOperator &CreatePlan(LogicalReset &op);
168371 PhysicalOperator &CreatePlan(LogicalSimple &op);
168372 PhysicalOperator &CreatePlan(LogicalVacuum &op);
168373 PhysicalOperator &CreatePlan(LogicalUnnest &op);
168374 PhysicalOperator &CreatePlan(LogicalRecursiveCTE &op);
168375 PhysicalOperator &CreatePlan(LogicalMaterializedCTE &op);
168376 PhysicalOperator &CreatePlan(LogicalCTERef &op);
168377 PhysicalOperator &CreatePlan(LogicalPivot &op);
168378
168379 PhysicalOperator &PlanAsOfJoin(LogicalComparisonJoin &op);
168380 PhysicalOperator &PlanComparisonJoin(LogicalComparisonJoin &op);
168381 PhysicalOperator &PlanDelimJoin(LogicalComparisonJoin &op);
168382 PhysicalOperator &ExtractAggregateExpressions(PhysicalOperator &child, vector<unique_ptr<Expression>> &expressions,
168383 vector<unique_ptr<Expression>> &groups,
168384 optional_ptr<vector<GroupingSet>> grouping_sets);
168385
168386private:
168387 ClientContext &context;
168388 unique_ptr<PhysicalPlan> physical_plan;
168389
168390private:
168391 PhysicalOperator &ResolveAndPlan(unique_ptr<LogicalOperator> logical);
168392 unique_ptr<PhysicalPlan> PlanInternal(LogicalOperator &logical);
168393 bool PreserveInsertionOrder(PhysicalOperator &plan);
168394 bool UseBatchIndex(PhysicalOperator &plan);
168395 optional_ptr<PhysicalOperator> PlanAsOfLoopJoin(LogicalComparisonJoin &op, PhysicalOperator &probe,
168396 PhysicalOperator &build);
168397};
168398}
168399
168400
168401namespace duckdb {
168402
168403class BoundIndex;
168404class PhysicalOperator;
168405class LogicalCreateIndex;
168406enum class IndexConstraintType :
uint8_t;
168407class Expression;
168408class TableIOManager;
168409class AttachedDatabase;
168410struct IndexStorageInfo;
168411class ClientContext;
168412
168413struct CreateIndexInput {
168414 ClientContext &context;
168415 TableIOManager &table_io_manager;
168416 AttachedDatabase &
db;
168417 IndexConstraintType constraint_type;
168418 const string &name;
168419 const vector<column_t> &column_ids;
168420 const vector<unique_ptr<Expression>> &unbound_expressions;
168421 const IndexStorageInfo &storage_info;
168422 const case_insensitive_map_t<Value> &options;
168423
168424 CreateIndexInput(ClientContext &context, TableIOManager &table_io_manager, AttachedDatabase &db,
168425 IndexConstraintType constraint_type, const string &name, const vector<column_t> &column_ids,
168426 const vector<unique_ptr<Expression>> &unbound_expressions, const IndexStorageInfo &storage_info,
168427 const case_insensitive_map_t<Value> &options)
168428 : context(context), table_io_manager(table_io_manager),
db(
db), constraint_type(constraint_type), name(name),
168429 column_ids(column_ids), unbound_expressions(unbound_expressions), storage_info(storage_info),
168430 options(options) {};
168431};
168432
168433struct IndexTypeInfo {
168434 DUCKDB_API virtual ~IndexTypeInfo() = default;
168435
168436 template <class TARGET>
168437 TARGET &Cast() {
168438 DynamicCastCheck<TARGET>(this);
168439 return reinterpret_cast<TARGET &>(*this);
168440 }
168441 template <class TARGET>
168442 const TARGET &Cast() const {
168443 DynamicCastCheck<TARGET>(this);
168444 return reinterpret_cast<const TARGET &>(*this);
168445 }
168446};
168447
168448struct IndexBuildBindData {
168449 DUCKDB_API virtual ~IndexBuildBindData() = default;
168450
168451 template <class TARGET>
168452 TARGET &Cast() {
168453 DynamicCastCheck<TARGET>(this);
168454 return reinterpret_cast<TARGET &>(*this);
168455 }
168456 template <class TARGET>
168457 const TARGET &Cast() const {
168458 DynamicCastCheck<TARGET>(this);
168459 return reinterpret_cast<const TARGET &>(*this);
168460 }
168461};
168462
168463struct IndexBuildGlobalState {
168464 DUCKDB_API virtual ~IndexBuildGlobalState() = default;
168465
168466 template <class TARGET>
168467 TARGET &Cast() {
168468 DynamicCastCheck<TARGET>(this);
168469 return reinterpret_cast<TARGET &>(*this);
168470 }
168471 template <class TARGET>
168472 const TARGET &Cast() const {
168473 DynamicCastCheck<TARGET>(this);
168474 return reinterpret_cast<const TARGET &>(*this);
168475 }
168476};
168477
168478struct IndexBuildLocalState {
168479 DUCKDB_API virtual ~IndexBuildLocalState() = default;
168480
168481 template <class TARGET>
168482 TARGET &Cast() {
168483 DynamicCastCheck<TARGET>(this);
168484 return reinterpret_cast<TARGET &>(*this);
168485 }
168486 template <class TARGET>
168487 const TARGET &Cast() const {
168488 DynamicCastCheck<TARGET>(this);
168489 return reinterpret_cast<const TARGET &>(*this);
168490 }
168491};
168492
168493class DuckTableEntry;
168494
168495struct IndexBuildInitLocalStateInput {
168496 optional_ptr<IndexBuildBindData> bind_data;
168497 ClientContext &context;
168498 DuckTableEntry &table;
168499 CreateIndexInfo &info;
168500 const vector<unique_ptr<Expression>> &expressions;
168501 const vector<column_t> storage_ids;
168502};
168503
168504struct IndexBuildInitGlobalStateInput {
168505 optional_ptr<IndexBuildBindData> bind_data;
168506 ClientContext &context;
168507 DuckTableEntry &table;
168508 CreateIndexInfo &info;
168509 const vector<unique_ptr<Expression>> &expressions;
168510 const vector<column_t> storage_ids;
168511};
168512
168513struct IndexBuildBindInput {
168514 ClientContext &context;
168515 DuckTableEntry &table;
168516 CreateIndexInfo &info;
168517 const vector<unique_ptr<Expression>> &expressions;
168518};
168519
168520struct IndexBuildSortInput {
168521 optional_ptr<IndexBuildBindData> bind_data;
168522};
168523
168524struct IndexBuildCombineInput {
168525 optional_ptr<IndexBuildBindData> bind_data;
168526 IndexBuildGlobalState &global_state;
168527 IndexBuildLocalState &local_state;
168528 DuckTableEntry &table;
168529 CreateIndexInfo &info;
168530};
168531
168532struct IndexBuildSinkInput {
168533 optional_ptr<IndexBuildBindData> bind_data;
168534 IndexBuildGlobalState &global_state;
168535 IndexBuildLocalState &local_state;
168536 DuckTableEntry &table;
168537 CreateIndexInfo &info;
168538};
168539
168540struct IndexBuildFinalizeInput {
168541 IndexBuildGlobalState &global_state;
168542};
168543
168544typedef unique_ptr<IndexBuildBindData> (*index_build_bind_t)(IndexBuildBindInput &input);
168545typedef bool (*index_build_sort_t)(IndexBuildSortInput &input);
168546typedef unique_ptr<IndexBuildGlobalState> (*index_build_global_init_t)(IndexBuildInitGlobalStateInput &input);
168547typedef unique_ptr<IndexBuildLocalState> (*index_build_local_init_t)(IndexBuildInitLocalStateInput &input);
168548typedef void (*index_build_sink_t)(IndexBuildSinkInput &input, DataChunk &key_chunk, DataChunk &row_chunk);
168549typedef void (*index_build_combine_t)(IndexBuildCombineInput &input);
168550typedef unique_ptr<BoundIndex> (*index_build_finalize_t)(IndexBuildFinalizeInput &input);
168551
168552struct PlanIndexInput {
168553 ClientContext &context;
168554 LogicalCreateIndex &op;
168555 PhysicalPlanGenerator &planner;
168556 PhysicalOperator &table_scan;
168557 shared_ptr<IndexTypeInfo> index_info;
168558
168559 PlanIndexInput(ClientContext &context_p, LogicalCreateIndex &op_p, PhysicalPlanGenerator &planner,
168560 PhysicalOperator &table_scan_p, shared_ptr<IndexTypeInfo> index_info_p = nullptr)
168561 : context(context_p), op(op_p), planner(planner), table_scan(table_scan_p),
168562 index_info(std::move(index_info_p)) {
168563 }
168564};
168565
168566typedef unique_ptr<BoundIndex> (*index_create_function_t)(CreateIndexInput &input);
168567typedef PhysicalOperator &(*index_build_plan_t)(PlanIndexInput &input);
168568
168570class IndexType {
168571public:
168572
168573 string name;
168574
168575
168576 index_build_bind_t build_bind = nullptr;
168577 index_build_sort_t build_sort = nullptr;
168578 index_build_global_init_t build_global_init = nullptr;
168579 index_build_local_init_t build_local_init = nullptr;
168580 index_build_sink_t build_sink = nullptr;
168581 index_build_combine_t build_combine = nullptr;
168582 index_build_finalize_t build_finalize = nullptr;
168583
168585 shared_ptr<IndexTypeInfo> index_info = nullptr;
168586
168587 index_build_plan_t create_plan = nullptr;
168588 index_create_function_t create_instance = nullptr;
168589};
168590
168591}
168592
168593
168594
168595
168596
168597
168598namespace duckdb {
168599
168600class IndexTypeSet {
168601 mutex lock;
168602 case_insensitive_tree_t<IndexType> functions;
168603
168604public:
168605 IndexTypeSet();
168606 DUCKDB_API optional_ptr<IndexType> FindByName(const string &name);
168607 DUCKDB_API
void RegisterIndexType(
const IndexType &
index_type);
168608};
168609
168610}
168611
168612
168613
168614
168615
168616
168617
168618
168619
168620
168621
168622
168623
168624
168625
168626
168627
168628namespace duckdb {
168629
168630class CastFunctionSet;
168631struct FunctionLocalState;
168632
168634struct BindCastInfo {
168635 DUCKDB_API virtual ~BindCastInfo();
168636
168637 template <class TARGET>
168638 TARGET &Cast() {
168639 DynamicCastCheck<TARGET>(this);
168640 return reinterpret_cast<TARGET &>(*this);
168641 }
168642 template <class TARGET>
168643 const TARGET &Cast() const {
168644 DynamicCastCheck<TARGET>(this);
168645 return reinterpret_cast<const TARGET &>(*this);
168646 }
168647};
168648
168650struct BoundCastData {
168651 DUCKDB_API virtual ~BoundCastData();
168652
168653 DUCKDB_API virtual unique_ptr<BoundCastData> Copy() const = 0;
168654
168655 template <class TARGET>
168656 TARGET &Cast() {
168657 DynamicCastCheck<TARGET>(this);
168658 return reinterpret_cast<TARGET &>(*this);
168659 }
168660 template <class TARGET>
168661 const TARGET &Cast() const {
168662 DynamicCastCheck<TARGET>(this);
168663 return reinterpret_cast<const TARGET &>(*this);
168664 }
168665};
168666
168667struct CastParameters {
168668 CastParameters() {
168669 }
168670 CastParameters(bool strict, string *error_message) : CastParameters(nullptr, strict, error_message, nullptr) {
168671 }
168672 CastParameters(BoundCastData *cast_data, bool strict, string *error_message,
168673 optional_ptr<FunctionLocalState> local_state, bool nullify_parent_p = false)
168674 : cast_data(cast_data), strict(strict), error_message(error_message), local_state(local_state),
168675 nullify_parent(nullify_parent_p) {
168676 }
168677 CastParameters(CastParameters &parent, optional_ptr<BoundCastData> cast_data,
168678 optional_ptr<FunctionLocalState> local_state)
168679 : cast_data(cast_data), strict(parent.strict), error_message(parent.error_message), local_state(local_state),
168680 query_location(parent.query_location) {
168681 }
168682
168684 optional_ptr<BoundCastData> cast_data;
168686 bool strict = false;
168687
168688 string *error_message = nullptr;
168690 optional_ptr<const Expression> cast_source;
168692 optional_ptr<const Expression> cast_target;
168694 optional_ptr<FunctionLocalState> local_state;
168696 optional_idx query_location;
168698 bool nullify_parent = false;
168699};
168700
168701struct CastLocalStateParameters {
168702 CastLocalStateParameters(optional_ptr<ClientContext> context_p, optional_ptr<BoundCastData> cast_data_p)
168703 : context(context_p), cast_data(cast_data_p) {
168704 }
168705 CastLocalStateParameters(ClientContext &context_p, optional_ptr<BoundCastData> cast_data_p)
168706 : context(&context_p), cast_data(cast_data_p) {
168707 }
168708 CastLocalStateParameters(CastLocalStateParameters &parent, optional_ptr<BoundCastData> cast_data_p)
168709 : context(parent.context), cast_data(cast_data_p) {
168710 }
168711
168712 optional_ptr<ClientContext> context;
168714 optional_ptr<BoundCastData> cast_data;
168715};
168716
168717typedef bool (*cast_function_t)(Vector &source, Vector &result,
idx_t count, CastParameters ¶meters);
168718typedef unique_ptr<FunctionLocalState> (*init_cast_local_state_t)(CastLocalStateParameters ¶meters);
168719
168720struct BoundCastInfo {
168721 DUCKDB_API
168722 BoundCastInfo(
168723 cast_function_t function, unique_ptr<BoundCastData> cast_data = nullptr,
168724 init_cast_local_state_t init_local_state = nullptr);
168725 cast_function_t function;
168726 init_cast_local_state_t init_local_state;
168727 unique_ptr<BoundCastData> cast_data;
168728
168729public:
168730 BoundCastInfo Copy() const;
168731};
168732
168733struct BindCastInput {
168734 DUCKDB_API BindCastInput(CastFunctionSet &function_set, optional_ptr<BindCastInfo> info,
168735 optional_ptr<ClientContext> context);
168736
168737 CastFunctionSet &function_set;
168738 optional_ptr<BindCastInfo> info;
168739 optional_ptr<ClientContext> context;
168740 optional_idx query_location;
168741
168742public:
168743 DUCKDB_API BoundCastInfo GetCastFunction(const LogicalType &source, const LogicalType &target);
168744};
168745
168746struct DefaultCasts {
168747 DUCKDB_API static BoundCastInfo GetDefaultCastFunction(BindCastInput &input, const LogicalType &source,
168748 const LogicalType &target);
168749
168750 DUCKDB_API static bool NopCast(Vector &source, Vector &result, idx_t count, CastParameters ¶meters);
168751 DUCKDB_API static bool TryVectorNullCast(Vector &source, Vector &result, idx_t count, CastParameters ¶meters);
168752 DUCKDB_API static bool ReinterpretCast(Vector &source, Vector &result, idx_t count, CastParameters ¶meters);
168753
168754private:
168755 static BoundCastInfo BlobCastSwitch(BindCastInput &input, const LogicalType &source, const LogicalType &target);
168756 static BoundCastInfo BitCastSwitch(BindCastInput &input, const LogicalType &source, const LogicalType &target);
168757 static BoundCastInfo DateCastSwitch(BindCastInput &input, const LogicalType &source, const LogicalType &target);
168758 static BoundCastInfo DecimalCastSwitch(BindCastInput &input, const LogicalType &source, const LogicalType &target);
168759 static BoundCastInfo EnumCastSwitch(BindCastInput &input, const LogicalType &source, const LogicalType &target);
168760 static BoundCastInfo IntervalCastSwitch(BindCastInput &input, const LogicalType &source, const LogicalType &target);
168761 static BoundCastInfo ListCastSwitch(BindCastInput &input, const LogicalType &source, const LogicalType &target);
168762 static BoundCastInfo ArrayCastSwitch(BindCastInput &input, const LogicalType &source, const LogicalType &target);
168763 static BoundCastInfo NumericCastSwitch(BindCastInput &input, const LogicalType &source, const LogicalType &target);
168764 static BoundCastInfo MapCastSwitch(BindCastInput &input, const LogicalType &source, const LogicalType &target);
168765 static BoundCastInfo PointerCastSwitch(BindCastInput &input, const LogicalType &source, const LogicalType &target);
168766 static BoundCastInfo StringCastSwitch(BindCastInput &input, const LogicalType &source, const LogicalType &target);
168767 static BoundCastInfo StructCastSwitch(BindCastInput &input, const LogicalType &source, const LogicalType &target);
168768 static BoundCastInfo TimeCastSwitch(BindCastInput &input, const LogicalType &source, const LogicalType &target);
168769 static BoundCastInfo TimeNsCastSwitch(BindCastInput &input, const LogicalType &source, const LogicalType &target);
168770 static BoundCastInfo TimeTzCastSwitch(BindCastInput &input, const LogicalType &source, const LogicalType &target);
168771 static BoundCastInfo TimestampCastSwitch(BindCastInput &input, const LogicalType &source,
168772 const LogicalType &target);
168773 static BoundCastInfo TimestampTzCastSwitch(BindCastInput &input, const LogicalType &source,
168774 const LogicalType &target);
168775 static BoundCastInfo TimestampNsCastSwitch(BindCastInput &input, const LogicalType &source,
168776 const LogicalType &target);
168777 static BoundCastInfo TimestampMsCastSwitch(BindCastInput &input, const LogicalType &source,
168778 const LogicalType &target);
168779 static BoundCastInfo TimestampSecCastSwitch(BindCastInput &input, const LogicalType &source,
168780 const LogicalType &target);
168781 static BoundCastInfo UnionCastSwitch(BindCastInput &input, const LogicalType &source, const LogicalType &target);
168782 static BoundCastInfo VariantCastSwitch(BindCastInput &input, const LogicalType &source, const LogicalType &target);
168783 static BoundCastInfo UUIDCastSwitch(BindCastInput &input, const LogicalType &source, const LogicalType &target);
168784 static BoundCastInfo GeoCastSwitch(BindCastInput &input, const LogicalType &source, const LogicalType &target);
168785 static BoundCastInfo TypeCastSwitch(BindCastInput &input, const LogicalType &source, const LogicalType &target);
168786 static BoundCastInfo BignumCastSwitch(BindCastInput &input, const LogicalType &source, const LogicalType &target);
168787 static BoundCastInfo ImplicitToUnionCast(BindCastInput &input, const LogicalType &source,
168788 const LogicalType &target);
168789 static BoundCastInfo ImplicitToVariantCast(BindCastInput &input, const LogicalType &source,
168790 const LogicalType &target);
168791};
168792
168793}
168794
168795
168796
168797
168798
168799
168800
168801
168802
168803
168804
168805
168806
168807
168808
168809namespace duckdb {
168810
168811class ClientContext;
168812class TableRef;
168813
168814struct ReplacementScanData {
168815public:
168816 virtual ~ReplacementScanData() {
168817 }
168818
168819public:
168820 template <class TARGET>
168821 TARGET &Cast() {
168822 DynamicCastCheck<TARGET>(this);
168823 return reinterpret_cast<TARGET &>(*this);
168824 }
168825 template <class TARGET>
168826 const TARGET &Cast() const {
168827 DynamicCastCheck<TARGET>(this);
168828 return reinterpret_cast<const TARGET &>(*this);
168829 }
168830};
168831
168832struct ReplacementScanInput {
168833public:
168834 explicit ReplacementScanInput(const string &catalog_name, const string &schema_name, const string &table_name)
168835 : catalog_name(catalog_name), schema_name(schema_name), table_name(table_name) {
168836 }
168837
168838public:
168839 const string &catalog_name;
168840 const string &schema_name;
168841 const string &table_name;
168842};
168843
168844typedef unique_ptr<TableRef> (*replacement_scan_t)(ClientContext &context, ReplacementScanInput &input,
168845 optional_ptr<ReplacementScanData> data);
168846
168849struct ReplacementScan {
168850 explicit ReplacementScan(replacement_scan_t function, unique_ptr<ReplacementScanData> data_p = nullptr)
168851 : function(function), data(std::move(data_p)) {
168852 }
168853
168854 static bool CanReplace(const string &table_name, const vector<string> &extensions) {
168856
168857 if (
StringUtil::EndsWith(lower_name, CompressionExtensionFromType(FileCompressionType::GZIP))) {
168858 lower_name = lower_name.substr(0, lower_name.size() - 3);
168859 }
else if (
StringUtil::EndsWith(lower_name, CompressionExtensionFromType(FileCompressionType::ZSTD))) {
168860 lower_name = lower_name.substr(0, lower_name.size() - 4);
168861 }
168862
168863 for (auto &extension : extensions) {
168866 return true;
168867 }
168868 }
168869
168870 return false;
168871 }
168872
168873 static string GetFullPath(const string &catalog, const string &schema, const string &table) {
168874 string table_name = catalog;
168875 if (!schema.empty()) {
168876 table_name += (!table_name.empty() ? "." : "") + schema;
168877 }
168878 table_name += (!table_name.empty() ? "." : "") + table;
168879 return table_name;
168880 }
168881
168882 static string GetFullPath(ReplacementScanInput &input) {
168883 return GetFullPath(input.catalog_name, input.schema_name, input.table_name);
168884 }
168885
168886 replacement_scan_t function;
168887 unique_ptr<ReplacementScanData> data;
168888};
168889
168890}
168891
168892
168893
168894
168895
168896
168897
168898
168899
168900
168901
168902
168903
168904namespace duckdb {
168905
168906enum class BitpackingMode :
uint8_t { INVALID, AUTO, CONSTANT, CONSTANT_DELTA, DELTA_FOR, FOR };
168907
168908}
168909
168910
168911
168912
168913
168914
168915
168916
168917
168918
168919
168920
168921
168922
168923
168924
168925
168926
168927
168928
168929
168930
168931
168932
168933
168934
168935
168936
168937
168938
168939
168940
168941namespace duckdb {
168942
168943class Serializer;
168944class Deserializer;
168945class QueryContext;
168946
168947struct ColumnSegmentState {
168948 virtual ~ColumnSegmentState() {
168949 }
168950
168951 virtual void Serialize(Serializer &serializer) const = 0;
168952 static unique_ptr<ColumnSegmentState> Deserialize(Deserializer &deserializer);
168953
168954 template <class TARGET>
168955 TARGET &Cast() {
168956 DynamicCastCheck<TARGET>(this);
168957 return reinterpret_cast<TARGET &>(*this);
168958 }
168959 template <class TARGET>
168960 const TARGET &Cast() const {
168961 DynamicCastCheck<TARGET>(this);
168962 return reinterpret_cast<const TARGET &>(*this);
168963 }
168964
168965public:
168966 vector<block_id_t> blocks;
168967};
168968
168969struct DataPointer {
168970 explicit DataPointer(BaseStatistics stats);
168971
168972 DataPointer(const DataPointer &other) = delete;
168973 DataPointer &
operator=(
const DataPointer &) =
delete;
168975 DUCKDB_API DataPointer(DataPointer &&other) noexcept;
168976 DUCKDB_API DataPointer &
operator=(DataPointer &&) noexcept;
168977
168978 uint64_t row_start;
168979 uint64_t tuple_count;
168980 BlockPointer block_pointer;
168981 CompressionType compression_type;
168983 BaseStatistics statistics;
168985 unique_ptr<ColumnSegmentState> segment_state;
168986
168987 void Serialize(Serializer &serializer) const;
168988 static DataPointer Deserialize(Deserializer &source);
168989};
168990
168991struct RowGroupPointer {
168995 vector<MetaBlockPointer> data_pointers;
168997 vector<MetaBlockPointer> deletes_pointers;
168999 bool has_metadata_blocks = false;
169002 vector<idx_t> extra_metadata_blocks;
169003};
169004
169005}
169006
169007
169008
169009namespace duckdb {
169010
169011struct DBConfig;
169012
169013class EncodingFunction;
169014
169015struct CSVEncoderBuffer;
169017typedef void (*encode_t)(CSVEncoderBuffer &encoded_buffer,
char *decoded_buffer,
idx_t &decoded_buffer_current_position,
169018 const idx_t decoded_buffer_size,
char *remaining_bytes_buffer,
idx_t &remaining_bytes_size,
169019 EncodingFunction *encoding_function);
169020
169022typedef struct {
169023 size_t key_len;
169024 const char *key;
169025 size_t value_len;
169026 const char *value;
169027} map_entry_encoding;
169028
169029class EncodingFunction {
169030public:
169031 DUCKDB_API EncodingFunction() : encode_function(nullptr), max_bytes_per_iteration(0) {
169032 }
169033
169034 DUCKDB_API EncodingFunction(const string &encode_name, encode_t encode_function, const idx_t bytes_per_iteration,
169035 const idx_t lookup_bytes)
169036 : name(encode_name), encode_function(encode_function), max_bytes_per_iteration(bytes_per_iteration),
169037 lookup_bytes(lookup_bytes) {
169038 D_ASSERT(encode_function);
169039 D_ASSERT(bytes_per_iteration > 0);
169040 D_ASSERT(lookup_bytes > 0);
169041 };
169042
169043 DUCKDB_API EncodingFunction(const string &encode_name, encode_t encode_function, const idx_t bytes_per_iteration,
169044 const idx_t lookup_bytes, const map_entry_encoding *map, const size_t map_size)
169045 : conversion_map(map), map_size(map_size), name(encode_name), encode_function(encode_function),
169046 max_bytes_per_iteration(bytes_per_iteration), lookup_bytes(lookup_bytes) {
169047 D_ASSERT(encode_function);
169048 D_ASSERT(bytes_per_iteration > 0);
169049 D_ASSERT(lookup_bytes > 0);
169050 };
169051
169052 DUCKDB_API ~EncodingFunction() {};
169053
169054 DUCKDB_API string GetName() const {
169055 return name;
169056 }
169057 DUCKDB_API
encode_t GetFunction()
const {
169058 return encode_function;
169059 }
169060 DUCKDB_API
idx_t GetBytesPerIteration()
const {
169061 return max_bytes_per_iteration;
169062 }
169063 DUCKDB_API
idx_t GetLookupBytes()
const {
169064 return lookup_bytes;
169065 }
169066
169068 const map_entry_encoding *conversion_map {};
169069 size_t map_size {};
169070
169071protected:
169073 string name;
169079 idx_t max_bytes_per_iteration;
169081 idx_t lookup_bytes = 1;
169082};
169083
169085struct EncodingFunctionSet {
169086 EncodingFunctionSet() {};
169087 static void Initialize(DBConfig &config);
169088 mutex lock;
169089 case_insensitive_map_t<EncodingFunction> functions;
169090};
169091
169092}
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
169125
169126
169127
169128
169129
169130
169131
169132namespace duckdb {
169133
169134
169136 LOG_TRACE = 10,
169137 LOG_DEBUG = 20,
169138 LOG_INFO = 30,
169139 LOG_WARNING = 40,
169140 LOG_ERROR = 50,
169141 LOG_FATAL = 60
169142};
169143
169144enum class LogContextScope :
uint8_t { DATABASE = 10, CONNECTION = 20, THREAD = 30 };
169145
169146enum class LogMode :
uint8_t { LEVEL_ONLY = 0, DISABLE_SELECTED = 1, ENABLE_SELECTED = 2 };
169147
169148struct LogConfig {
169149 constexpr static const char *IN_MEMORY_STORAGE_NAME = "memory";
169150 constexpr static const char *STDOUT_STORAGE_NAME = "stdout";
169151 constexpr static const char *FILE_STORAGE_NAME = "file";
169152
169153 constexpr static LogLevel DEFAULT_LOG_LEVEL = LogLevel::LOG_INFO;
169154 constexpr static const char *DEFAULT_LOG_STORAGE = IN_MEMORY_STORAGE_NAME;
169155
169156 LogConfig();
169157
169158 DUCKDB_API bool IsConsistent() const;
169159
169160 bool enabled;
169161 LogMode mode;
169163 string storage;
169164
169165 unordered_set<string> enabled_log_types;
169166 unordered_set<string> disabled_log_types;
169167
169168protected:
169169 LogConfig(bool enabled, LogLevel level, LogMode mode, optional_ptr<unordered_set<string>> enabled_log_types,
169170 optional_ptr<unordered_set<string>> disable_loggers);
169171};
169172
169173struct LoggingContext {
169174 explicit LoggingContext(LogContextScope scope_p) : scope(scope_p) {
169175 }
169176
169177 LogContextScope scope;
169178
169179 optional_idx thread_id;
169180 optional_idx connection_id;
169181 optional_idx transaction_id;
169182 optional_idx query_id;
169183};
169184
169185struct RegisteredLoggingContext {
169187 LoggingContext context;
169188};
169189
169190}
169191
169192
169193
169194
169195
169196
169197
169198
169199
169200
169201
169202
169203
169204
169205namespace duckdb {
169206
169207struct FileHandle;
169208struct BaseRequest;
169209struct HTTPResponse;
169210class PhysicalOperator;
169211class AttachedDatabase;
169212class RowGroup;
169213struct DataTableInfo;
169214enum class MetricType :
uint8_t;
169215
169218class LogType {
169219public:
169221 LogType(const string &name_p, const LogLevel &level_p)
169222 : name(name_p), level(level_p), is_structured(false), type(LogicalType::VARCHAR) {
169223 }
169225 LogType(const string &name_p, const LogLevel &level_p, LogicalType structured_type)
169226 : name(name_p), level(level_p), is_structured(true), type(std::move(structured_type)) {
169227 if (!type.IsNested()) {
169228 throw InternalException("LogType must be nested if the type is explicitly set");
169229 }
169230 }
169231
169232 string name;
169234
169235 bool is_structured;
169236 LogicalType type;
169237};
169238
169239class DefaultLogType : public LogType {
169240public:
169241 static constexpr const char *NAME = "";
169242 static constexpr LogLevel LEVEL = LogLevel::LOG_INFO;
169243
169244 DefaultLogType() : LogType(NAME, LEVEL) {
169245 }
169246};
169247
169248class QueryLogType : public LogType {
169249public:
169250 static constexpr const char *NAME = "QueryLog";
169251 static constexpr LogLevel LEVEL = LogLevel::LOG_INFO;
169252
169253 QueryLogType() : LogType(NAME, LEVEL) {};
169254
169255 static string ConstructLogMessage(const string &str);
169256};
169257
169258class FileSystemLogType : public LogType {
169259public:
169260 static constexpr const char *NAME = "FileSystem";
169261 static constexpr LogLevel LEVEL = LogLevel::LOG_TRACE;
169262
169264 FileSystemLogType();
169265
169266 static LogicalType GetLogType();
169267
169268 static string ConstructLogMessage(const FileHandle &handle, const string &op, int64_t bytes, idx_t pos);
169269 static string ConstructLogMessage(const FileHandle &handle, const string &op);
169270};
169271
169272class HTTPLogType : public LogType {
169273public:
169274 static constexpr const char *NAME = "HTTP";
169275 static constexpr LogLevel LEVEL = LogLevel::LOG_DEBUG;
169276
169278 HTTPLogType();
169279
169280 static LogicalType GetLogType();
169281
169282 static string ConstructLogMessage(BaseRequest &request, optional_ptr<HTTPResponse> response);
169283
169284
169285 static string ConstructLogMessage(const string &str) {
169286 return str;
169287 }
169288};
169289
169290class PhysicalOperatorLogType : public LogType {
169291public:
169292 static constexpr const char *NAME = "PhysicalOperator";
169293 static constexpr LogLevel LEVEL = LogLevel::LOG_DEBUG;
169294
169296 PhysicalOperatorLogType();
169297
169298 static LogicalType GetLogType();
169299
169300 static string ConstructLogMessage(const PhysicalOperator &op, const string &class_p, const string &event,
169301 const vector<pair<string, string>> &info);
169302};
169303
169304class MetricsLogType : public LogType {
169305public:
169306 static constexpr const char *NAME = "Metrics";
169307 static constexpr LogLevel LEVEL = LogLevel::LOG_INFO;
169308
169310 MetricsLogType();
169311
169312 static LogicalType GetLogType();
169313
169314 static string ConstructLogMessage(const MetricType &type, const Value &value);
169315};
169316
169317class CheckpointLogType : public LogType {
169318public:
169319 static constexpr const char *NAME = "Checkpoint";
169320 static constexpr LogLevel LEVEL = LogLevel::LOG_DEBUG;
169321
169323 CheckpointLogType();
169324
169325 static LogicalType GetLogType();
169326
169328 static string ConstructLogMessage(const AttachedDatabase &db, DataTableInfo &table, idx_t segment_idx,
169329 idx_t merge_count, idx_t target_count, idx_t merge_rows, idx_t row_start);
169331 static string ConstructLogMessage(const AttachedDatabase &db, DataTableInfo &table, idx_t segment_idx,
169332 RowGroup &row_group, idx_t row_group_start);
169333
169334private:
169335 static string CreateLog(const AttachedDatabase &db, DataTableInfo &table, const char *op, vector<Value> map_keys,
169336 vector<Value> map_values);
169337};
169338
169339class TransactionLogType : public LogType {
169340public:
169341 static constexpr const char *NAME = "Transaction";
169342 static constexpr LogLevel LEVEL = LogLevel::LOG_DEBUG;
169343
169345 TransactionLogType();
169346
169347 static LogicalType GetLogType();
169348
169349 static string ConstructLogMessage(const AttachedDatabase &db, const char *log_type,
169350 transaction_t transaction_id = MAX_TRANSACTION_ID);
169351};
169352
169353}
169354
169355
169356
169357
169358namespace duckdb {
169359class TableDescription;
169360class DatabaseInstance;
169361class DataChunk;
169362class LogManager;
169363class ColumnDataCollection;
169364class ThreadContext;
169365class FileOpener;
169366class LogStorage;
169367class ExecutionContext;
169368struct FileHandle;
169369
169371#define DUCKDB_LOG_INTERNAL(SOURCE, TYPE, LEVEL, ...) \
169372 { \
169373 auto &logger_ref_ = Logger::Get(SOURCE); \
169374 if (logger_ref_.ShouldLog(TYPE, LEVEL)) { \
169375 logger_ref_.WriteLog(TYPE, LEVEL, __VA_ARGS__); \
169376 } \
169377 }
169378
169380#define DUCKDB_LOG_TRACE(SOURCE, ...) \
169381 DUCKDB_LOG_INTERNAL(SOURCE, DefaultLogType::NAME, LogLevel::LOG_TRACE, __VA_ARGS__)
169382#define DUCKDB_LOG_DEBUG(SOURCE, ...) \
169383 DUCKDB_LOG_INTERNAL(SOURCE, DefaultLogType::NAME, LogLevel::LOG_DEBUG, __VA_ARGS__)
169384#define DUCKDB_LOG_INFO(SOURCE, ...) DUCKDB_LOG_INTERNAL(SOURCE, DefaultLogType::NAME, LogLevel::LOG_INFO, __VA_ARGS__)
169385#define DUCKDB_LOG_WARNING(SOURCE, ...) \
169386 DUCKDB_LOG_INTERNAL(SOURCE, DefaultLogType::NAME, LogLevel::LOG_WARNING, __VA_ARGS__)
169387#define DUCKDB_LOG_ERROR(SOURCE, ...) \
169388 DUCKDB_LOG_INTERNAL(SOURCE, DefaultLogType::NAME, LogLevel::LOG_ERROR, __VA_ARGS__)
169389#define DUCKDB_LOG_FATAL(SOURCE, ...) \
169390 DUCKDB_LOG_INTERNAL(SOURCE, DefaultLogType::NAME, LogLevel::LOG_FATAL, __VA_ARGS__)
169391
169393#define DUCKDB_LOG(SOURCE, LOG_TYPE_CLASS, ...) \
169394 DUCKDB_LOG_INTERNAL(SOURCE, LOG_TYPE_CLASS::NAME, LOG_TYPE_CLASS::LEVEL, \
169395 LOG_TYPE_CLASS::ConstructLogMessage(__VA_ARGS__))
169396
169398class Logger {
169399public:
169400 DUCKDB_API explicit Logger(LogManager &manager) : manager(manager) {
169401 }
169402
169403 DUCKDB_API virtual ~Logger() = default;
169404
169405
169406 DUCKDB_API virtual bool ShouldLog(const char *log_type, LogLevel log_level) = 0;
169407 DUCKDB_API void WriteLog(const char *log_type, LogLevel log_level, const char *message);
169408
169409
169410 DUCKDB_API void WriteLog(const char *log_type, LogLevel log_level, const string &message);
169411 DUCKDB_API void WriteLog(const char *log_type, LogLevel log_level, const string_t &message);
169412
169413
169414 template <typename... ARGS>
169415 void WriteLog(const char *log_type, LogLevel log_level, const char *format_string, ARGS... params) {
169417 WriteLog(log_type, log_level, formatted_string.c_str());
169418 }
169419
169420 DUCKDB_API virtual void Flush() = 0;
169421
169422
169423
169424
169425 DUCKDB_API static Logger &Get(const ThreadContext &thread_context);
169426 DUCKDB_API static Logger &Get(const ExecutionContext &execution_context);
169427 DUCKDB_API static Logger &Get(const ClientContext &client_context);
169428 DUCKDB_API static Logger &Get(const FileOpener &opener);
169429 DUCKDB_API static Logger &Get(const DatabaseInstance &db);
169430 DUCKDB_API static Logger &Get(const shared_ptr<Logger> &logger);
169431
169432 template <class T>
169433 static void Flush(T &log_context_source) {
169434 Get(log_context_source).Flush();
169435 }
169436
169437 DUCKDB_API virtual bool IsThreadSafe() = 0;
169438 DUCKDB_API virtual bool IsMutable() {
169439 return false;
169440 };
169441 DUCKDB_API virtual void UpdateConfig(LogConfig &new_config) {
169442 throw InternalException("Cannot update the config of this logger!");
169443 }
169444 DUCKDB_API virtual const LogConfig &GetConfig() const = 0;
169445
169446protected:
169447 virtual void WriteLogInternal(const char *log_type, LogLevel log_level, const char *message) = 0;
169448
169449protected:
169450 LogManager &manager;
169451};
169452
169453
169454class ThreadSafeLogger : public Logger {
169455public:
169456 explicit ThreadSafeLogger(LogConfig &config_p, LoggingContext &context_p, LogManager &manager);
169457 explicit ThreadSafeLogger(LogConfig &config_p, RegisteredLoggingContext context_p, LogManager &manager);
169458
169459
169460 bool ShouldLog(const char *log_type, LogLevel log_level) override;
169461 void WriteLogInternal(const char *log_type, LogLevel log_level, const char *message) override;
169462
169463 void Flush() override;
169464 bool IsThreadSafe() override {
169465 return true;
169466 }
169467 const LogConfig &GetConfig() const override {
169468 return config;
169469 }
169470
169471protected:
169472 const LogConfig config;
169473 mutex lock;
169474 const RegisteredLoggingContext context;
169475};
169476
169477
169478
169479class ThreadLocalLogger : public Logger {
169480public:
169481 explicit ThreadLocalLogger(LogConfig &config_p, LoggingContext &context_p, LogManager &manager);
169482 explicit ThreadLocalLogger(LogConfig &config_p, RegisteredLoggingContext context_p, LogManager &manager);
169483
169484
169485 bool ShouldLog(const char *log_type, LogLevel log_level) override;
169486 void WriteLogInternal(const char *log_type, LogLevel log_level, const char *message) override;
169487 void Flush() override;
169488
169489 bool IsThreadSafe() override {
169490 return false;
169491 }
169492 const LogConfig &GetConfig() const override {
169493 return config;
169494 }
169495
169496protected:
169497 const LogConfig config;
169498 const RegisteredLoggingContext context;
169499};
169500
169501
169502class MutableLogger : public Logger {
169503public:
169504 explicit MutableLogger(LogConfig &config_p, LoggingContext &context_p, LogManager &manager);
169505 explicit MutableLogger(LogConfig &config_p, RegisteredLoggingContext context_p, LogManager &manager);
169506
169507
169508 bool ShouldLog(const char *log_type, LogLevel log_level) override;
169509 void WriteLogInternal(const char *log_type, LogLevel log_level, const char *message) override;
169510
169511 void Flush() override;
169512 bool IsThreadSafe() override {
169513 return true;
169514 }
169515 bool IsMutable() override {
169516 return true;
169517 }
169518 const LogConfig &GetConfig() const override {
169519 return config;
169520 }
169521 void UpdateConfig(LogConfig &new_config) override;
169522
169523protected:
169524
169525 atomic<bool> enabled;
169526 atomic<LogMode> mode;
169527 atomic<LogLevel> level;
169528
169529 mutex lock;
169530 LogConfig config;
169531 const RegisteredLoggingContext context;
169532};
169533
169534
169535class NopLogger : public Logger {
169536public:
169537 explicit NopLogger(LogManager &manager) : Logger(manager) {
169538 }
169539 bool ShouldLog(const char *log_type, LogLevel log_level) override {
169540 return false;
169541 }
169542 void WriteLogInternal(const char *log_type, LogLevel log_level, const char *message) override {};
169543 void Flush() override {
169544 }
169545 bool IsThreadSafe() override {
169546 return true;
169547 }
169548 const LogConfig &GetConfig() const override {
169549 throw InternalException("Called GetConfig on NopLogger");
169550 }
169551};
169552
169553}
169554
169555
169556
169557
169558
169559
169560
169561
169562
169563
169564
169565
169566
169567
169568
169569
169570
169571
169572
169573
169574
169575
169576
169577
169578
169579
169580
169581
169582
169583
169584
169585
169586namespace duckdb {
169587class ClientContext;
169588class Logger;
169589
169591class ThreadContext {
169592public:
169593 explicit ThreadContext(ClientContext &context);
169594 ~ThreadContext();
169595
169597 OperatorProfiler profiler;
169598 unique_ptr<Logger> logger;
169599};
169600
169601}
169602
169603
169604namespace duckdb {
169605struct RegisteredLoggingContext;
169606class ColumnDataCollection;
169607struct ColumnDataScanState;
169608class MemoryStream;
169609struct LogStorageConfig;
169610class CSVWriter;
169611struct CSVWriterState;
169612class BufferedFileWriter;
169613struct CSVWriterOptions;
169614struct CSVReaderOptions;
169615
169619 ALL_LOGS,
169620 LOG_ENTRIES,
169621 LOG_CONTEXTS,
169622};
169623
169624class LogStorageScanState {
169625public:
169626 explicit LogStorageScanState(LoggingTargetTable table_p) : table(table_p) {
169627 }
169628 virtual ~LogStorageScanState() = default;
169629
169630 template <class TARGET>
169631 TARGET &Cast() {
169632 DynamicCastCheck<TARGET>(this);
169633 return reinterpret_cast<TARGET &>(*this);
169634 }
169635 template <class TARGET>
169636 const TARGET &Cast() const {
169637 DynamicCastCheck<TARGET>(this);
169638 return reinterpret_cast<const TARGET &>(*this);
169639 }
169640
169642};
169643
169644
169645class LogStorage {
169646public:
169647 DUCKDB_API explicit LogStorage() {
169648 }
169649 DUCKDB_API virtual ~LogStorage() = default;
169650
169651 virtual const string GetStorageName() = 0;
169652
169653 static vector<LogicalType> GetSchema(LoggingTargetTable table);
169654 static vector<string> GetColumnNames(LoggingTargetTable table);
169655
169657 DUCKDB_API virtual void WriteLogEntry(timestamp_t timestamp, LogLevel level, const string &log_type,
169658 const string &log_message, const RegisteredLoggingContext &context) = 0;
169659 DUCKDB_API virtual void WriteLogEntries(DataChunk &chunk, const RegisteredLoggingContext &context) = 0;
169660 DUCKDB_API virtual void FlushAll() = 0;
169661 DUCKDB_API virtual void Flush(LoggingTargetTable table) = 0;
169662 DUCKDB_API virtual void Truncate();
169663 DUCKDB_API virtual bool IsEnabled(LoggingTargetTable table) = 0;
169664
169666 DUCKDB_API virtual bool CanScan(LoggingTargetTable table) {
169667 return false;
169668 }
169669
169670 DUCKDB_API virtual unique_ptr<LogStorageScanState> CreateScanState(LoggingTargetTable table) const;
169671 DUCKDB_API virtual bool Scan(LogStorageScanState &state, DataChunk &result) const;
169672 DUCKDB_API virtual void InitializeScan(LogStorageScanState &state) const;
169673
169674
169675 DUCKDB_API virtual unique_ptr<TableRef> BindReplace(ClientContext &context, TableFunctionBindInput &input,
169676 LoggingTargetTable table);
169677
169679 DUCKDB_API virtual void UpdateConfig(DatabaseInstance &db, case_insensitive_map_t<Value> &config);
169680};
169681
169684class BufferingLogStorage : public LogStorage {
169685public:
169686 explicit BufferingLogStorage(DatabaseInstance &db_p, idx_t buffer_size, bool normalize);
169687 ~BufferingLogStorage() override;
169688
169690
169692 void WriteLogEntry(timestamp_t timestamp, LogLevel level, const string &log_type, const string &log_message,
169693 const RegisteredLoggingContext &context) final;
169695 void WriteLogEntries(DataChunk &chunk, const RegisteredLoggingContext &context) final;
169697 void FlushAll() final;
169699 void Flush(LoggingTargetTable table) final;
169701 void Truncate() override;
169703 void UpdateConfig(DatabaseInstance &db, case_insensitive_map_t<Value> &config) override;
169705 bool IsEnabled(LoggingTargetTable table) override;
169706
169707protected:
169709
169711 virtual void FlushChunk(LoggingTargetTable table, DataChunk &chunk) = 0;
169714 virtual void UpdateConfigInternal(DatabaseInstance &db, case_insensitive_map_t<Value> &config);
169717 virtual void ResetAllBuffers();
169718
169720
169722 void FlushAllInternal();
169724 void FlushInternal(LoggingTargetTable table);
169726 bool IsEnabledInternal(LoggingTargetTable table);
169727
169728 idx_t GetBufferLimit() const;
169729
169732 mutable mutex lock;
169735 bool normalize_contexts = true;
169736
169737private:
169739 void ResetLogBuffers();
169741 void WriteLoggingContext(const RegisteredLoggingContext &context);
169742
169744 unordered_set<idx_t> registered_contexts;
169746 idx_t buffer_limit = 0;
169748 bool only_flush_on_full_buffer = false;
169750 map<LoggingTargetTable, unique_ptr<DataChunk>> buffers;
169753 bool flush_contexts_on_next_entry_flush = false;
169754};
169755
169760class CSVLogStorage : public BufferingLogStorage {
169761public:
169762 explicit CSVLogStorage(DatabaseInstance &db, bool normalize, idx_t buffer_size);
169763 ~CSVLogStorage() override;
169764
169765protected:
169767
169769 void FlushChunk(LoggingTargetTable table, DataChunk &chunk) final;
169771 void ResetAllBuffers() override;
169773 void UpdateConfigInternal(DatabaseInstance &db, case_insensitive_map_t<Value> &config) override;
169774
169776
169778 virtual void BeforeFlush(LoggingTargetTable table, DataChunk &chunk) {};
169779 virtual void AfterFlush(LoggingTargetTable table, DataChunk &chunk) {};
169780
169782
169784 void RegisterWriter(LoggingTargetTable table, unique_ptr<CSVWriter> writer);
169786 CSVWriter &GetWriter(LoggingTargetTable table);
169788 void SetWriterConfigs(CSVWriter &Writer, vector<string> column_names);
169790 CSVWriterOptions &GetCSVWriterOptions();
169792 CSVReaderOptions &GetCSVReaderOptions();
169793
169794private:
169796 void ExecuteCast(LoggingTargetTable table, DataChunk &chunk);
169798 void ResetCastChunk();
169800 void InitializeCastChunk(LoggingTargetTable table);
169801
169803 map<LoggingTargetTable, unique_ptr<DataChunk>> cast_buffers;
169805 map<LoggingTargetTable, unique_ptr<CSVWriter>> writers;
169806
169809 unique_ptr<CSVWriterOptions> writer_options;
169810 unique_ptr<CSVReaderOptions> reader_options;
169811};
169812
169815class StdOutLogStorage : public CSVLogStorage {
169816public:
169817 explicit StdOutLogStorage(DatabaseInstance &db);
169818 ~StdOutLogStorage() override;
169819
169820 const string GetStorageName() override {
169821 return "StdOutLogStorage";
169822 }
169823
169824private:
169825 class StdOutWriteStream : public WriteStream {
169826 void WriteData(const_data_ptr_t buffer, idx_t write_size) override;
169827 };
169828
169829 StdOutWriteStream stdout_stream;
169830};
169831
169835class FileLogStorage : public CSVLogStorage {
169836public:
169837 explicit FileLogStorage(DatabaseInstance &db);
169838 ~FileLogStorage() override;
169839
169840 const string GetStorageName() override {
169841 return "FileLogStorage";
169842 }
169843
169845
169847 void Truncate() override;
169849 unique_ptr<TableRef> BindReplace(ClientContext &context, TableFunctionBindInput &input,
169850 LoggingTargetTable table) override;
169851
169852protected:
169854
169856 void UpdateConfigInternal(DatabaseInstance &db, case_insensitive_map_t<Value> &config) override;
169858 void BeforeFlush(LoggingTargetTable table, DataChunk &chunk) override;
169860 void AfterFlush(LoggingTargetTable table, DataChunk &chunk) override;
169861
169862private:
169864 void InitializeFile(DatabaseInstance &db, LoggingTargetTable table);
169866 static unique_ptr<BufferedFileWriter> InitializeFileWriter(DatabaseInstance &db, const string &path);
169868 void Initialize(LoggingTargetTable table);
169870 unique_ptr<TableRef> BindReplaceInternal(ClientContext &context, TableFunctionBindInput &input, const string &path,
169871 const string &select_clause, const string &csv_columns);
169872
169874 DatabaseInstance &
db;
169875
169877 struct TableWriter {
169879 unique_ptr<BufferedFileWriter> file_writer;
169881 string path;
169883 bool initialized = false;
169884 };
169885
169887 map<LoggingTargetTable, TableWriter> tables;
169888
169890 string base_path;
169891
169892private:
169893 void SetPaths(const string &base_path);
169894};
169895
169897class InMemoryLogStorageScanState : public LogStorageScanState {
169898public:
169899 explicit InMemoryLogStorageScanState(LoggingTargetTable table);
169900 ~InMemoryLogStorageScanState() override;
169901
169902 ColumnDataScanState scan_state;
169903};
169904
169907class InMemoryLogStorage : public BufferingLogStorage {
169908public:
169909 explicit InMemoryLogStorage(DatabaseInstance &db);
169910 ~InMemoryLogStorage() override;
169911
169912 const string GetStorageName() override {
169913 return "InMemoryLogStorage";
169914 }
169915
169917 bool CanScan(LoggingTargetTable table) override;
169918 unique_ptr<LogStorageScanState> CreateScanState(LoggingTargetTable table) const override;
169919 bool Scan(LogStorageScanState &state, DataChunk &result) const override;
169920 void InitializeScan(LogStorageScanState &state) const override;
169921
169922protected:
169924
169926 void FlushChunk(LoggingTargetTable table, DataChunk &chunk) override;
169928 void ResetAllBuffers() override;
169929
169930private:
169932 ColumnDataCollection &GetBuffer(LoggingTargetTable table) const;
169933
169934 map<LoggingTargetTable, unique_ptr<ColumnDataCollection>> log_storage_buffers;
169935};
169936
169937}
169938
169939
169940
169941
169942namespace duckdb {
169943class LogType;
169944
169945
169946
169947
169948
169949
169950class LogManager {
169951 friend class ThreadSafeLogger;
169952 friend class ThreadLocalLogger;
169953 friend class MutableLogger;
169954
169955public:
169956
169957 explicit LogManager(DatabaseInstance &db, LogConfig config = LogConfig());
169958 ~LogManager();
169959 void Initialize();
169960
169961 DUCKDB_API static LogManager &Get(ClientContext &context);
169962 unique_ptr<Logger> CreateLogger(LoggingContext context, bool thread_safe = true, bool mutable_settings = false);
169963
169964 RegisteredLoggingContext RegisterLoggingContext(LoggingContext &context);
169965
169966 DUCKDB_API bool RegisterLogStorage(const string &name, shared_ptr<LogStorage> &storage);
169967
169969 DUCKDB_API Logger &GlobalLogger();
169970 DUCKDB_API shared_ptr<Logger> GlobalLoggerReference();
169971
169973 DUCKDB_API void Flush();
169974
169976 DUCKDB_API shared_ptr<LogStorage> GetLogStorage();
169977 DUCKDB_API bool CanScan(LoggingTargetTable table);
169978
169979 DUCKDB_API void SetConfig(DatabaseInstance &db, const LogConfig &config);
169980 DUCKDB_API void SetEnableLogging(bool enable);
169981 DUCKDB_API void SetLogMode(LogMode mode);
169982 DUCKDB_API void SetLogLevel(LogLevel level);
169983 DUCKDB_API void SetEnabledLogTypes(optional_ptr<unordered_set<string>> enabled_log_types);
169984 DUCKDB_API void SetDisabledLogTypes(optional_ptr<unordered_set<string>> disabled_log_types);
169985 DUCKDB_API void SetLogStorage(DatabaseInstance &db, const string &storage_name);
169986
169987 DUCKDB_API void UpdateLogStorageConfig(DatabaseInstance &db, case_insensitive_map_t<Value> &config_value);
169988
169989 DUCKDB_API void SetEnableStructuredLoggers(vector<string> &enabled_logger_types);
169990
169991 DUCKDB_API void TruncateLogStorage();
169992
169993 DUCKDB_API LogConfig GetConfig();
169994
169995 DUCKDB_API void RegisterLogType(unique_ptr<LogType> type);
169996 DUCKDB_API optional_ptr<const LogType> LookupLogType(const string &type);
169997 DUCKDB_API void RegisterDefaultLogTypes();
169998
169999protected:
170000 RegisteredLoggingContext RegisterLoggingContextInternal(LoggingContext &context);
170001
170002
170003 void WriteLogEntry(timestamp_t, const char *log_type, LogLevel log_level, const char *log_message,
170004 const RegisteredLoggingContext &context);
170005
170006 void FlushCachedLogEntries(DataChunk &chunk, const RegisteredLoggingContext &context);
170007
170008 void SetLogStorageInternal(DatabaseInstance &db, const string &storage_name);
170009
170010 optional_ptr<const LogType> LookupLogTypeInternal(const string &type);
170011
170012 void SetConfigInternal(LogConfig config);
170013
170014protected:
170015 mutex lock;
170016 LogConfig config;
170017
170018 shared_ptr<Logger> global_logger;
170019 shared_ptr<LogStorage> log_storage;
170020 DatabaseInstance &db_instance;
170021
170022 idx_t next_registered_logging_context_index = 0;
170023
170024
170025 case_insensitive_map_t<shared_ptr<LogStorage>> registered_log_storages;
170026 case_insensitive_map_t<unique_ptr<LogType>> registered_log_types;
170027};
170028
170029}
170030
170031
170032
170033
170034
170035
170036
170037
170038namespace duckdb {
170039
170040class ClientContext;
170041class DatabaseInstance;
170042class CastFunctionSet;
170043struct DBConfig;
170044
170045class TypeManager {
170046public:
170047 explicit TypeManager(DBConfig &config);
170048
170049 ~TypeManager();
170050
170052 CastFunctionSet &GetCastFunctions();
170053
170055 LogicalType ParseLogicalType(const string &type_str, ClientContext &context) const;
170056
170058 static TypeManager &Get(DatabaseInstance &db);
170059 static TypeManager &Get(ClientContext &context);
170060
170061private:
170064 LogicalType (*parse_function)(const string &, ClientContext &);
170065
170067 unique_ptr<CastFunctionSet> cast_functions;
170068};
170069
170070}
170071
170072
170073namespace duckdb {
170074
170075class BlockAllocator;
170076class BufferManager;
170077class BufferPool;
170078class CastFunctionSet;
170079class CollationBinding;
170080class ClientContext;
170081class ErrorManager;
170082class CompressionFunction;
170083class TableFunctionRef;
170084class OperatorExtension;
170085class StorageExtension;
170086class ExtensionCallback;
170087class SecretManager;
170088class CompressionInfo;
170089class EncryptionUtil;
170090class HTTPUtil;
170091class DatabaseFilePathManager;
170092class ExtensionCallbackManager;
170093class TypeManager;
170094
170095struct CompressionFunctionSet;
170096struct DatabaseCacheEntry;
170097struct DBConfig;
170098struct SettingLookupResult;
170099
170100class SerializationCompatibility {
170101public:
170102 static SerializationCompatibility FromDatabase(AttachedDatabase &db);
170103 static SerializationCompatibility FromIndex(idx_t serialization_version);
170104 static SerializationCompatibility FromString(const string &input);
170105 static SerializationCompatibility Default();
170106 static SerializationCompatibility Latest();
170107
170108public:
170109 bool Compare(idx_t property_version) const;
170110
170111public:
170113 string duckdb_version;
170115 idx_t serialization_version;
170117 bool manually_set;
170118
170119protected:
170120 SerializationCompatibility() = default;
170121};
170122
170126struct DBConfigOptions {
170128 string database_path;
170130 string database_type;
170132 AccessMode access_mode = AccessMode::AUTOMATIC;
170134 idx_t checkpoint_wal_size = 1 << 24;
170136 bool use_direct_io = false;
170138 bool load_extensions = true;
170140 idx_t maximum_memory = DConstants::INVALID_INDEX;
170142 idx_t maximum_swap_space = DConstants::INVALID_INDEX;
170144 idx_t maximum_threads = DConstants::INVALID_INDEX;
170146 bool use_temporary_directory = true;
170148 string temporary_directory;
170151 bool trim_free_blocks = false;
170153 bool buffer_manager_track_eviction_timestamps = false;
170155 bool force_checkpoint = false;
170157 bool checkpoint_on_shutdown = true;
170159 SerializationCompatibility serialization_compatibility = SerializationCompatibility::Default();
170162 bool initialize_default_database = true;
170164 bool force_mbedtls = false;
170166 set<OptimizerType> disabled_optimizers;
170168 LogicalType force_variant_shredding = LogicalType::INVALID;
170170 case_insensitive_map_t<Value> set_variable_defaults;
170172 vector<string> extension_directories;
170174 DebugInitialize debug_initialize = DebugInitialize::NO_INITIALIZE;
170176 case_insensitive_map_t<Value> user_options;
170178 case_insensitive_map_t<Value> unrecognized_options;
170180 static bool debug_print_bindings;
170182 idx_t allocator_flush_threshold = 134217728ULL;
170184 idx_t allocator_bulk_deallocation_flush_threshold = 536870912ULL;
170186 bool variant_legacy_encoding = false;
170188 string custom_user_agent;
170190 idx_t default_block_header_size = DEFAULT_BLOCK_HEADER_STORAGE_SIZE;
170192 bool abort_on_wal_failure = false;
170194 unordered_set<string> allowed_paths;
170196 set<string> allowed_directories;
170198 case_insensitive_set_t allowed_configs;
170200 LogConfig log_config = LogConfig();
170202 idx_t block_allocator_size = 0;
170203
170204 bool operator==(
const DBConfigOptions &other)
const;
170205};
170206
170207struct DBConfig {
170208 friend class DatabaseInstance;
170209 friend class StorageManager;
170210
170211public:
170212 DUCKDB_API DBConfig();
170213 explicit DUCKDB_API DBConfig(bool read_only);
170214 DUCKDB_API DBConfig(const case_insensitive_map_t<Value> &config_dict, bool read_only);
170215 DUCKDB_API ~DBConfig();
170216
170218 vector<ReplacementScan> replacement_scans;
170219
170222 unique_ptr<FileSystem> file_system;
170224 unique_ptr<SecretManager> secret_manager;
170226 unique_ptr<Allocator> allocator;
170228 unique_ptr<BlockAllocator> block_allocator;
170230 DBConfigOptions options;
170232 unique_ptr<ErrorManager> error_manager;
170234 shared_ptr<Allocator> default_allocator;
170236 shared_ptr<BufferPool> buffer_pool;
170238 shared_ptr<BufferManager> buffer_manager;
170240 shared_ptr<EncryptionUtil> encryption_util;
170242 shared_ptr<DatabaseCacheEntry> db_cache_entry;
170244 shared_ptr<DatabaseFilePathManager> path_manager;
170246 GlobalUserSettings user_settings;
170247
170248public:
170249 DUCKDB_API static DBConfig &GetConfig(ClientContext &context);
170250 DUCKDB_API static DBConfig &GetConfig(DatabaseInstance &db);
170251 DUCKDB_API static DBConfig &Get(AttachedDatabase &db);
170252 DUCKDB_API static const DBConfig &GetConfig(const ClientContext &context);
170253 DUCKDB_API static const DBConfig &GetConfig(const DatabaseInstance &db);
170254 DUCKDB_API static vector<ConfigurationOption> GetOptions();
170255 DUCKDB_API static vector<ConfigurationAlias> GetAliases();
170256 DUCKDB_API
static idx_t GetOptionCount();
170257 DUCKDB_API
static idx_t GetAliasCount();
170258 DUCKDB_API static vector<string> GetOptionNames();
170259 DUCKDB_API static bool IsInMemoryDatabase(const char *database_path);
170260
170261 DUCKDB_API void AddExtensionOption(const string &name, string description, LogicalType parameter,
170262 const Value &default_value = Value(), set_option_callback_t function = nullptr,
170263 SetScope default_scope = SetScope::SESSION);
170264 DUCKDB_API bool HasExtensionOption(const string &name) const;
170265 DUCKDB_API case_insensitive_map_t<ExtensionOption> GetExtensionSettings() const;
170266 DUCKDB_API
bool TryGetExtensionOption(
const String &name, ExtensionOption &result)
const;
170268 DUCKDB_API static optional_ptr<const ConfigurationOption> GetOptionByIndex(idx_t index);
170270 DUCKDB_API static optional_ptr<const ConfigurationAlias> GetAliasByIndex(idx_t index);
170272 DUCKDB_API
static optional_ptr<const ConfigurationOption> GetOptionByName(
const String &name);
170273 DUCKDB_API void SetOption(const ConfigurationOption &option, const Value &value);
170274 DUCKDB_API void SetOption(optional_ptr<DatabaseInstance> db, const ConfigurationOption &option, const Value &value);
170275 DUCKDB_API void SetOption(const string &name, Value value);
170276 DUCKDB_API void SetOption(idx_t setting_index, Value value);
170277 DUCKDB_API void SetOptionByName(const string &name, const Value &value);
170278 DUCKDB_API void SetOptionsByName(const case_insensitive_map_t<Value> &values);
170279 DUCKDB_API void ResetOption(optional_ptr<DatabaseInstance> db, const ConfigurationOption &option);
170280 DUCKDB_API void ResetOption(const ExtensionOption &extension_option);
170281 DUCKDB_API void ResetGenericOption(idx_t setting_index);
170282 DUCKDB_API optional_idx TryGetSettingIndex(
const String &name,
170283 optional_ptr<const ConfigurationOption> &option) const;
170284 static LogicalType ParseLogicalType(const string &type);
170285
170286 DUCKDB_API
void CheckLock(
const String &name);
170287
170288 DUCKDB_API
static idx_t ParseMemoryLimit(
const string &
arg);
170289
170291 DUCKDB_API vector<reference<const CompressionFunction>>
170292 GetCompressionFunctions(const PhysicalType physical_type) const;
170295 DUCKDB_API reference<const CompressionFunction> GetCompressionFunction(CompressionType type,
170296 const PhysicalType physical_type) const;
170297 DUCKDB_API optional_ptr<const CompressionFunction>
170298 TryGetCompressionFunction(CompressionType type, const PhysicalType physical_type) const;
170300 DUCKDB_API void SetDisabledCompressionMethods(const vector<CompressionType> &disabled_compression_methods);
170302 DUCKDB_API vector<CompressionType> GetDisabledCompressionMethods() const;
170303
170305 DUCKDB_API optional_ptr<EncodingFunction> GetEncodeFunction(const string &name) const;
170306 DUCKDB_API void RegisterEncodeFunction(const EncodingFunction &function) const;
170308 DUCKDB_API vector<reference<EncodingFunction>> GetLoadedEncodedFunctions() const;
170310 DUCKDB_API ArrowTypeExtension GetArrowExtension(ArrowExtensionMetadata info) const;
170311 DUCKDB_API ArrowTypeExtension GetArrowExtension(const LogicalType &type) const;
170312 DUCKDB_API bool HasArrowExtension(const LogicalType &type) const;
170313 DUCKDB_API bool HasArrowExtension(ArrowExtensionMetadata info) const;
170314 DUCKDB_API void RegisterArrowExtension(const ArrowTypeExtension &extension) const;
170315
170318
170319 DUCKDB_API CastFunctionSet &GetCastFunctions();
170320 DUCKDB_API TypeManager &GetTypeManager();
170321 DUCKDB_API CollationBinding &GetCollationBinding();
170322 DUCKDB_API IndexTypeSet &GetIndexTypes();
170323 static idx_t GetSystemMaxThreads(FileSystem &fs);
170324 static idx_t GetSystemAvailableMemory(FileSystem &fs);
170325 static optional_idx ParseMemoryLimitSlurm(
const string &
arg);
170326 void SetDefaultMaxMemory();
170327 void SetDefaultTempDirectory();
170328
170329 OrderType ResolveOrder(ClientContext &context, OrderType order_type) const;
170330 OrderByNullType ResolveNullOrder(ClientContext &context, OrderType order_type, OrderByNullType null_type) const;
170331 const string UserAgent() const;
170332
170334 SettingLookupResult TryGetCurrentSetting(const string &key, Value &result) const;
170336 SettingLookupResult TryGetCurrentUserSetting(idx_t setting_index, Value &result) const;
170338 static SettingLookupResult TryGetDefaultValue(optional_ptr<const ConfigurationOption> option, Value &result);
170339
170340 bool CanAccessFile(const string &path, FileType type);
170341 void AddAllowedConfig(const string &config_name);
170342 void AddAllowedDirectory(const string &path);
170343 void AddAllowedPath(const string &path);
170344 string SanitizeAllowedPath(const string &path) const;
170345 ExtensionCallbackManager &GetCallbackManager();
170346 const ExtensionCallbackManager &GetCallbackManager() const;
170347 void SetHTTPUtil(const shared_ptr<HTTPUtil> &new_http_util);
170348 HTTPUtil &GetHTTPUtil() const;
170349
170350private:
170351 mutable mutex config_lock;
170352 unique_ptr<CompressionFunctionSet> compression_functions;
170353 unique_ptr<EncodingFunctionSet> encoding_functions;
170354 unique_ptr<ArrowTypeExtensionSet> arrow_extensions;
170355 unique_ptr<TypeManager> type_manager;
170356 unique_ptr<CollationBinding> collation_bindings;
170357 unique_ptr<IndexTypeSet> index_types;
170358 unique_ptr<ExtensionCallbackManager> callback_manager;
170359 bool is_user_config = true;
170361 shared_ptr<HTTPUtil> http_util;
170362 vector<shared_ptr<HTTPUtil>> old_http_utils;
170363 mutex http_util_lock;
170364};
170365
170366}
170367
170368
170369
170370
170371
170372
170373
170374
170375
170376
170377
170378
170379
170380
170381
170382namespace duckdb {
170383class DatabaseInstance;
170384class MetaTransaction;
170385
170386class ValidChecker {
170387public:
170388 explicit ValidChecker(DatabaseInstance &db);
170389
170390 DUCKDB_API static ValidChecker &Get(DatabaseInstance &db);
170391 DUCKDB_API static ValidChecker &Get(MetaTransaction &transaction);
170392
170393 DUCKDB_API void Invalidate(string error);
170394 DUCKDB_API bool IsInvalidated();
170395 DUCKDB_API string InvalidatedMessage();
170396
170397 template <class T>
170398 static bool IsInvalidated(T &o) {
170399 return Get(o).IsInvalidated();
170400 }
170401 template <class T>
170402 static void Invalidate(T &o, string error) {
170403 Get(o).Invalidate(std::move(error));
170404 }
170405
170406 template <class T>
170407 static string InvalidatedMessage(T &o) {
170408 return Get(o).InvalidatedMessage();
170409 }
170410
170411private:
170412 mutex invalidate_lock;
170414 atomic<bool> is_invalidated;
170416 string invalidated_msg;
170418 DatabaseInstance &
db;
170419};
170420
170421}
170422
170423
170424
170425
170426
170427
170428
170429
170430
170431
170432
170433
170434
170435
170436
170437
170438
170439
170440
170441
170442
170443
170444
170445
170446
170447
170448
170449
170450
170451
170452
170453
170454namespace duckdb {
170455class Catalog;
170456class DatabaseInstance;
170457class StorageManager;
170458class TransactionManager;
170459class StorageExtension;
170460class DatabaseManager;
170461
170462struct AttachInfo;
170463struct StoredDatabasePath;
170464
170465enum class AttachedDatabaseType {
170466 READ_WRITE_DATABASE,
170467 READ_ONLY_DATABASE,
170468 SYSTEM_DATABASE,
170469 TEMP_DATABASE,
170470};
170471
170472enum class AttachVisibility { SHOWN, HIDDEN };
170473
170478
170482
170483class DatabaseFilePathManager;
170484
170485struct StoredDatabasePath {
170486 StoredDatabasePath(DatabaseManager &db_manager, DatabaseFilePathManager &manager, string path, const string &name);
170487 ~StoredDatabasePath();
170488
170489 DatabaseManager &db_manager;
170490 DatabaseFilePathManager &manager;
170491 string path;
170492
170493 void OnDetach();
170494};
170495
170498struct AttachOptions {
170500 explicit AttachOptions(const DBConfigOptions &options);
170502 AttachOptions(const unordered_map<string, Value> &options, const AccessMode default_access_mode);
170503
170505 AccessMode access_mode;
170509 string db_type;
170511 unordered_map<string, Value> options;
170513 QualifiedName default_table;
170515 bool is_main_database = false;
170517 AttachVisibility visibility = AttachVisibility::SHOWN;
170519 unique_ptr<StoredDatabasePath> stored_database_path;
170520};
170521
170523class AttachedDatabase : public CatalogEntry, public enable_shared_from_this<AttachedDatabase> {
170524public:
170526 explicit AttachedDatabase(DatabaseInstance &db, AttachedDatabaseType type = AttachedDatabaseType::SYSTEM_DATABASE);
170528 AttachedDatabase(DatabaseInstance &db, Catalog &catalog, string name, string file_path, AttachOptions &options);
170530 AttachedDatabase(DatabaseInstance &db, Catalog &catalog, StorageExtension &ext, ClientContext &context, string name,
170531 AttachInfo &info, AttachOptions &options);
170532 ~AttachedDatabase() override;
170533
170535 void Initialize(optional_ptr<ClientContext> context = nullptr);
170536 void FinalizeLoad(optional_ptr<ClientContext> context);
170538 void Close(const DatabaseCloseAction action);
170539
170540 Catalog &ParentCatalog() override;
170541 const Catalog &ParentCatalog() const override;
170542 bool HasStorageManager() const;
170543 StorageManager &GetStorageManager();
170544 const StorageManager &GetStorageManager() const;
170545 Catalog &GetCatalog();
170546 TransactionManager &GetTransactionManager();
170547 DatabaseInstance &GetDatabase() {
170549 }
170550
170551 optional_ptr<StorageExtension> GetStorageExtension() {
170552 return storage_extension;
170553 }
170554
170555 const string &GetName() const {
170556 return name;
170557 }
170558 void SetName(const string &new_name) {
170559 name = new_name;
170560 }
170561 bool IsSystem() const;
170562 bool IsTemporary() const;
170563 bool IsReadOnly() const;
170564 bool IsInitialDatabase() const;
170565 void SetInitialDatabase();
170566 void SetReadOnlyDatabase();
170567 void OnDetach(ClientContext &context);
170569 return recovery_mode;
170570 }
170571 AttachVisibility GetVisibility() const {
170572 return visibility;
170573 }
170574 const unordered_map<string, Value> &GetAttachOptions() const {
170575 return attach_options;
170576 }
170577 string StoredPath() const;
170578
170579 static bool NameIsReserved(const string &name);
170580 static string ExtractDatabaseName(const string &dbpath, FileSystem &fs);
170581
170582
170583 static void InvokeCloseIfLastReference(shared_ptr<AttachedDatabase> &attached_database);
170584
170585private:
170586 DatabaseInstance &
db;
170587 unique_ptr<StoredDatabasePath> stored_database_path;
170588 unique_ptr<StorageManager> storage;
170589 unique_ptr<Catalog> catalog;
170590 unique_ptr<TransactionManager> transaction_manager;
170591 AttachedDatabaseType type;
170592 optional_ptr<Catalog> parent_catalog;
170593 optional_ptr<StorageExtension> storage_extension;
170595 AttachVisibility visibility = AttachVisibility::SHOWN;
170596 bool is_initial_database = false;
170597 bool is_closed = false;
170598 shared_ptr<mutex> close_lock;
170599 unordered_map<string, Value> attach_options;
170600
170601private:
170603 void Cleanup();
170604};
170605
170606}
170607
170608
170609namespace duckdb {
170610class AttachedDatabase;
170611class ClientContext;
170612struct DatabaseModificationType;
170613class Transaction;
170614
170615enum class TransactionState { UNCOMMITTED, COMMITTED, ROLLED_BACK };
170616
170617struct TransactionReference {
170618 explicit TransactionReference(Transaction &transaction_p)
170619 : state(TransactionState::UNCOMMITTED), transaction(transaction_p) {
170620 }
170621
170622 TransactionState state;
170623 Transaction &transaction;
170624};
170625
170627class MetaTransaction {
170628public:
170629 DUCKDB_API MetaTransaction(ClientContext &context, timestamp_t start_timestamp,
170630 transaction_t global_transaction_id);
170631
170632 ClientContext &context;
170634 timestamp_t start_timestamp;
170638 ValidChecker transaction_validity;
170640 atomic<transaction_t> active_query;
170641
170642public:
170643 DUCKDB_API static MetaTransaction &Get(ClientContext &context);
170644 timestamp_t GetCurrentTransactionStartTimestamp() const {
170645 return start_timestamp;
170646 }
170647
170648 Transaction &GetTransaction(AttachedDatabase &db);
170649 optional_ptr<Transaction> TryGetTransaction(AttachedDatabase &db);
170650 void RemoveTransaction(AttachedDatabase &db);
170651
170652 ErrorData Commit();
170653 void Rollback();
170654
170655 void Finalize();
170656
170657 idx_t GetActiveQuery();
170658 void SetActiveQuery(transaction_t query_number);
170659
170660 void SetReadOnly();
170661 bool IsReadOnly() const;
170662 void ModifyDatabase(AttachedDatabase &db, DatabaseModificationType modification);
170663 optional_ptr<AttachedDatabase> ModifiedDatabase() {
170664 return modified_database;
170665 }
170666 const vector<reference<AttachedDatabase>> &OpenedTransactions() const {
170667 return all_transactions;
170668 }
170669 optional_ptr<AttachedDatabase> GetReferencedDatabase(const string &name);
170670 shared_ptr<AttachedDatabase> GetReferencedDatabaseOwning(const string &name);
170671 AttachedDatabase &UseDatabase(shared_ptr<AttachedDatabase> &database);
170672 void DetachDatabase(AttachedDatabase &database);
170673
170674private:
170676 mutex lock;
170678 reference_map_t<AttachedDatabase, TransactionReference> transactions;
170680 vector<reference<AttachedDatabase>> all_transactions;
170682 optional_ptr<AttachedDatabase> modified_database;
170684 bool is_read_only;
170686 mutex referenced_database_lock;
170688 reference_map_t<AttachedDatabase, shared_ptr<AttachedDatabase>> referenced_databases;
170690 case_insensitive_map_t<reference<AttachedDatabase>> used_databases;
170691};
170692
170693}
170694
170695
170696
170697
170698
170699
170700
170701
170702
170703
170704
170705
170706
170707
170708
170709
170710
170711
170712namespace duckdb {
170713
170714class AttachedDatabase;
170715class ClientContext;
170716class Catalog;
170717struct ClientLockWrapper;
170718class DatabaseInstance;
170719class Transaction;
170720
170723class TransactionManager {
170724public:
170725 explicit TransactionManager(AttachedDatabase &db);
170726 virtual ~TransactionManager();
170727
170729 virtual Transaction &StartTransaction(ClientContext &context) = 0;
170731 virtual ErrorData CommitTransaction(ClientContext &context, Transaction &transaction) = 0;
170733 virtual void RollbackTransaction(Transaction &transaction) = 0;
170734
170735 virtual void Checkpoint(ClientContext &context, bool force = false) = 0;
170736
170737 static TransactionManager &Get(AttachedDatabase &db);
170738
170739 virtual bool IsDuckTransactionManager() {
170740 return false;
170741 }
170742
170743 AttachedDatabase &GetDB() {
170745 }
170746
170747protected:
170749 AttachedDatabase &
db;
170750
170751public:
170752 template <class TARGET>
170753 TARGET &Cast() {
170754 DynamicCastCheck<TARGET>(this);
170755 return reinterpret_cast<TARGET &>(*this);
170756 }
170757 template <class TARGET>
170758 const TARGET &Cast() const {
170759 D_ASSERT(dynamic_cast<const TARGET *>(this));
170760 return reinterpret_cast<const TARGET &>(*this);
170761 }
170762};
170763
170764}
170765
170766
170767
170768
170769
170770
170771
170772
170773
170774
170775
170776
170777
170778
170779
170780
170781
170782
170783
170784
170785
170786
170787
170788
170789
170790
170791
170792
170793
170794
170795
170796namespace duckdb {
170797
170798struct AttachInfo : public ParseInfo {
170799public:
170800 static constexpr const ParseInfoType
TYPE = ParseInfoType::ATTACH_INFO;
170801
170802public:
170803 AttachInfo() : ParseInfo(
TYPE) {
170804 }
170805
170807 string name;
170809 string path;
170811 case_insensitive_map_t<unique_ptr<ParsedExpression>> parsed_options;
170813 unordered_map<string, Value> options;
170815 OnCreateConflict on_conflict = OnCreateConflict::ERROR_ON_CONFLICT;
170816
170817public:
170819 unique_ptr<AttachInfo> Copy() const;
170820 string ToString() const;
170821
170822 void Serialize(Serializer &serializer) const override;
170823 static unique_ptr<ParseInfo> Deserialize(Deserializer &deserializer);
170824};
170825
170826}
170827
170828
170829
170830
170831
170832
170833
170834
170835
170836
170837
170838
170839
170840
170841
170842
170843
170844
170845namespace duckdb {
170846struct AttachInfo;
170847struct AttachOptions;
170848class DatabaseManager;
170849
170850enum class InsertDatabasePathResult { SUCCESS, ALREADY_EXISTS };
170851
170852struct DatabasePathInfo {
170853 DatabasePathInfo(DatabaseManager &manager, string name_p, AccessMode access_mode);
170854
170855 string name;
170856 AccessMode access_mode;
170857 reference_set_t<DatabaseManager> attached_databases;
170858 idx_t reference_count = 1;
170859};
170860
170862class DatabaseFilePathManager {
170863public:
170864 idx_t ApproxDatabaseCount()
const;
170865 InsertDatabasePathResult InsertDatabasePath(DatabaseManager &manager, const string &path, const string &name,
170866 OnCreateConflict on_conflict, AttachOptions &options);
170868 void EraseDatabasePath(const string &path);
170870 void DetachDatabase(DatabaseManager &manager, const string &path);
170871
170872private:
170874 mutable mutex db_paths_lock;
170878#if defined(_WIN32) || defined(__APPLE__)
170879 case_insensitive_map_t<DatabasePathInfo> db_paths;
170880#else
170881 unordered_map<string, DatabasePathInfo> db_paths;
170882#endif
170883};
170884
170885}
170886
170887
170888namespace duckdb {
170889class AttachedDatabase;
170890class Catalog;
170891class CatalogEntryRetriever;
170892class CatalogSet;
170893class ClientContext;
170894class DatabaseInstance;
170895class TaskScheduler;
170896struct AttachOptions;
170897struct AlterInfo;
170898
170900class DatabaseManager {
170901 friend class Catalog;
170902
170903public:
170904 explicit DatabaseManager(DatabaseInstance &db);
170905 ~DatabaseManager();
170906
170907public:
170908 static DatabaseManager &Get(DatabaseInstance &db);
170909 static DatabaseManager &Get(ClientContext &db);
170910 static DatabaseManager &Get(AttachedDatabase &db);
170911
170912 DatabaseInstance &GetInstance() {
170914 }
170916 void InitializeSystemCatalog();
170918 void FinalizeStartup();
170920 optional_ptr<AttachedDatabase> GetDatabase(ClientContext &context, const string &name);
170921 shared_ptr<AttachedDatabase> GetDatabase(const string &name);
170923 shared_ptr<AttachedDatabase> AttachDatabase(ClientContext &context, AttachInfo &info, AttachOptions &options);
170924
170926 void DetachDatabase(ClientContext &context, const string &name, OnEntryNotFound if_not_found);
170928 void Alter(ClientContext &context, AlterInfo &info);
170930 shared_ptr<AttachedDatabase> DetachInternal(const string &name);
170932 Catalog &GetSystemCatalog();
170933
170934 static const string &GetDefaultDatabase(ClientContext &context);
170935 void SetDefaultDatabase(ClientContext &context, const string &new_value);
170936
170938 InsertDatabasePathResult InsertDatabasePath(const AttachInfo &info, AttachOptions &options);
170939
170943 void GetDatabaseType(ClientContext &context, AttachInfo &info, const DBConfig &config, AttachOptions &options);
170946 vector<shared_ptr<AttachedDatabase>> GetDatabases(ClientContext &context,
170947 const optional_idx max_db_count = optional_idx());
170949 vector<shared_ptr<AttachedDatabase>> GetDatabases();
170951 idx_t ApproxDatabaseCount();
170954 void ResetDatabases();
170955
170957 return current_query_number++;
170958 }
170960 return current_query_number;
170961 }
170963 return current_transaction_id++;
170964 }
170966 return current_transaction_id;
170967 }
170969 return next_oid++;
170970 }
170971 bool HasDefaultDatabase() {
170972 return !default_database.empty();
170973 }
170975 vector<string> GetAttachedDatabasePaths();
170976
170977 shared_ptr<AttachedDatabase> GetDatabaseInternal(const lock_guard<mutex> &, const string &name);
170978
170979private:
170980 optional_ptr<AttachedDatabase> FinalizeAttach(ClientContext &context, AttachInfo &info,
170981 shared_ptr<AttachedDatabase> database);
170982
170983private:
170984 DatabaseInstance &
db;
170986 shared_ptr<AttachedDatabase> system;
170988 mutex databases_lock;
170990 case_insensitive_map_t<shared_ptr<AttachedDatabase>> databases;
170992 atomic<idx_t> next_oid;
170994 atomic<transaction_t> current_query_number;
170996 atomic<transaction_t> current_transaction_id;
170998 string default_database;
171000 shared_ptr<DatabaseFilePathManager> path_manager;
171001
171002private:
171004 void RenameDatabase(ClientContext &context, const string &old_name, const string &new_name,
171005 OnEntryNotFound if_not_found);
171006};
171007
171008}
171009
171010
171011#include <mutex>
171012
171013namespace duckdb {
171014class ClientContext;
171015class ErrorData;
171016class MetaTransaction;
171017class PreparedStatementData;
171018class SQLStatement;
171019struct PendingQueryParameters;
171020class RegisteredStateManager;
171021
171022enum class RebindQueryInfo { DO_NOT_REBIND, ATTEMPT_TO_REBIND };
171023
171024struct PreparedStatementCallbackInfo {
171025 PreparedStatementCallbackInfo(PreparedStatementData &prepared_statement, const PendingQueryParameters ¶meters)
171026 : prepared_statement(prepared_statement), parameters(parameters) {
171027 }
171028
171029 PreparedStatementData &prepared_statement;
171030 const PendingQueryParameters ¶meters;
171031};
171032
171033struct BindPreparedStatementCallbackInfo {
171034 PreparedStatementData &prepared_statement;
171035 optional_ptr<case_insensitive_map_t<BoundParameterData>> parameters;
171036};
171037
171040class ClientContextState {
171041public:
171042 virtual ~ClientContextState() = default;
171043 virtual void QueryBegin(ClientContext &context) {
171044 }
171045 virtual void QueryEnd() {
171046 }
171047 virtual void QueryEnd(ClientContext &context) {
171048 QueryEnd();
171049 }
171050 virtual void QueryEnd(ClientContext &context, optional_ptr<ErrorData> error) {
171051 QueryEnd(context);
171052 }
171053 virtual void TransactionBegin(MetaTransaction &transaction, ClientContext &context) {
171054 }
171055 virtual void TransactionCommit(MetaTransaction &transaction, ClientContext &context) {
171056 }
171057 virtual void TransactionRollback(MetaTransaction &transaction, ClientContext &context) {
171058 }
171059 virtual void TransactionRollback(MetaTransaction &transaction, ClientContext &context,
171060 optional_ptr<ErrorData> error) {
171061 TransactionRollback(transaction, context);
171062 }
171063 virtual bool CanRequestRebind() {
171064 return false;
171065 }
171066 virtual RebindQueryInfo OnPlanningError(ClientContext &context, SQLStatement &statement, ErrorData &error) {
171067 return RebindQueryInfo::DO_NOT_REBIND;
171068 }
171069 virtual RebindQueryInfo OnFinalizePrepare(ClientContext &context, PreparedStatementData &prepared_statement,
171070 PreparedStatementMode mode) {
171071 return RebindQueryInfo::DO_NOT_REBIND;
171072 }
171073 virtual RebindQueryInfo OnExecutePrepared(ClientContext &context, PreparedStatementCallbackInfo &info,
171074 RebindQueryInfo current_rebind) {
171075 return RebindQueryInfo::DO_NOT_REBIND;
171076 }
171077 virtual RebindQueryInfo OnRebindPreparedStatement(ClientContext &context, BindPreparedStatementCallbackInfo &info,
171078 RebindQueryInfo current_rebind) {
171079 return RebindQueryInfo::DO_NOT_REBIND;
171080 }
171081 virtual void WriteProfilingInformation(std::ostream &ss) {
171082 }
171083 virtual void OnTaskStart(ClientContext &context) {
171084 }
171085 virtual void OnTaskStop(ClientContext &context) {
171086 }
171087
171088public:
171089 template <class TARGET>
171090 TARGET &Cast() {
171091 DynamicCastCheck<TARGET>(this);
171092 return reinterpret_cast<TARGET &>(*this);
171093 }
171094 template <class TARGET>
171095 const TARGET &Cast() const {
171096 DynamicCastCheck<TARGET>(this);
171097 return reinterpret_cast<const TARGET &>(*this);
171098 }
171099};
171100
171101class RegisteredStateManager {
171102public:
171103 template <class T, typename... ARGS>
171104 shared_ptr<T> GetOrCreate(const string &key, ARGS &&... args) {
171105 lock_guard<mutex> l(lock);
171106 auto lookup = registered_state.find(key);
171107 if (lookup != registered_state.end()) {
171108 return shared_ptr_cast<ClientContextState, T>(lookup->second);
171109 }
171110 auto cache = make_shared_ptr<T>(std::forward<ARGS>(args)...);
171111 registered_state[key] = cache;
171112 return cache;
171113 }
171114
171115 template <class T>
171116 shared_ptr<T> Get(const string &key) {
171117 lock_guard<mutex> l(lock);
171118 auto lookup = registered_state.find(key);
171119 if (lookup == registered_state.end()) {
171120 return nullptr;
171121 }
171122 return shared_ptr_cast<ClientContextState, T>(lookup->second);
171123 }
171124
171125 void Insert(const string &key, shared_ptr<ClientContextState> state_p) {
171126 lock_guard<mutex> l(lock);
171127 registered_state.insert(make_pair(key, std::move(state_p)));
171128 }
171129
171130 void Remove(const string &key) {
171131 lock_guard<mutex> l(lock);
171132 registered_state.erase(key);
171133 }
171134
171135 vector<shared_ptr<ClientContextState>>
States() {
171136 lock_guard<mutex> l(lock);
171137 vector<shared_ptr<ClientContextState>> states;
171138 for (auto &entry : registered_state) {
171139 states.push_back(entry.second);
171140 }
171141 return states;
171142 }
171143
171144private:
171145 mutex lock;
171146 unordered_map<string, shared_ptr<ClientContextState>> registered_state;
171147};
171148
171149}
171150
171151
171152
171153
171154
171155
171156
171157
171158
171159
171160
171161
171162
171163
171164
171165
171166
171167
171168
171169
171170
171171
171172
171173
171174
171175
171176
171177
171178
171179
171180
171181
171182
171183#include <queue>
171184
171185namespace duckdb {
171186
171187template <class DATA_TYPE, class CONTAINER = std::deque<DATA_TYPE>, bool SAFE = true>
171188class queue : public std::queue<DATA_TYPE, CONTAINER> {
171189public:
171190 using original = std::queue<DATA_TYPE, CONTAINER>;
171191 using original::original;
171192 using container_type = typename original::container_type;
171193 using value_type =
typename original::value_type;
171194 using size_type = typename container_type::size_type;
171195 using reference = typename container_type::reference;
171196 using const_reference = typename container_type::const_reference;
171197
171198public:
171199
171200
171201 queue() = default;
171202 queue(original &&other) : original(std::move(other)) {
171203 }
171204 template <bool INTERNAL_SAFE>
171205 queue(queue<DATA_TYPE, CONTAINER, INTERNAL_SAFE> &&other) : original(std::move(other)) {
171206 }
171207
171208 inline void clear() noexcept {
171209 original::c.clear();
171210 }
171211
171212 reference front() {
171213 if (MemorySafety<SAFE>::ENABLED && original::empty()) {
171214 throw InternalException("'front' called on an empty queue!");
171215 }
171216 return original::front();
171217 }
171218
171219 const_reference front() const {
171220 if (MemorySafety<SAFE>::ENABLED && original::empty()) {
171221 throw InternalException("'front' called on an empty queue!");
171222 }
171223 return original::front();
171224 }
171225
171226 reference back() {
171227 if (MemorySafety<SAFE>::ENABLED && original::empty()) {
171228 throw InternalException("'back' called on an empty queue!");
171229 }
171230 return original::back();
171231 }
171232
171233 const_reference back() const {
171234 if (MemorySafety<SAFE>::ENABLED && original::empty()) {
171235 throw InternalException("'back' called on an empty queue!");
171236 }
171237 return original::back();
171238 }
171239
171240 void pop() {
171241 if (MemorySafety<SAFE>::ENABLED && original::empty()) {
171242 throw InternalException("'pop' called on an empty queue!");
171243 }
171244 original::pop();
171245 }
171246};
171247
171248template <typename T, typename Container = std::deque<T>>
171249using unsafe_queue = queue<T, Container, false>;
171250
171251}
171252
171253
171254
171255
171256
171257
171258
171259
171260
171261
171262
171263
171264
171265namespace duckdb {
171266
171267enum class StreamExecutionResult :
uint8_t {
171268 CHUNK_READY,
171269 CHUNK_NOT_READY,
171270 EXECUTION_ERROR,
171271 EXECUTION_CANCELLED,
171272 BLOCKED,
171273 NO_TASKS_AVAILABLE,
171274 EXECUTION_FINISHED
171275};
171276
171277}
171278
171279
171280
171281
171282
171283
171284
171285
171286
171287
171288
171289
171290
171291
171292
171293
171294
171295
171296
171297
171298
171299
171300
171301
171302
171303
171304
171305
171306
171307
171308
171309namespace duckdb {
171310
171311class StreamQueryResult;
171312class ClientContextLock;
171313
171314class BufferedData {
171315protected:
171316 enum class Type { SIMPLE, BATCHED };
171317
171318public:
171319 BufferedData(Type type, ClientContext &context);
171320 virtual ~BufferedData();
171321
171322public:
171323 StreamExecutionResult ReplenishBuffer(StreamQueryResult &result, ClientContextLock &context_lock);
171324 virtual StreamExecutionResult ExecuteTaskInternal(StreamQueryResult &result, ClientContextLock &context_lock) = 0;
171325 virtual unique_ptr<DataChunk> Scan() = 0;
171326 virtual void UnblockSinks() = 0;
171327 shared_ptr<ClientContext> GetContext() {
171328 return context.lock();
171329 }
171330 bool Closed() const {
171331 if (context.expired()) {
171332 return true;
171333 }
171334 auto c = context.lock();
171335 return c == nullptr;
171336 }
171337 void Close() {
171338 context.reset();
171339 }
171340
171341public:
171342 template <class TARGET>
171343 TARGET &Cast() {
171344 if (TARGET::TYPE != type) {
171345 throw InternalException("Failed to cast buffered data to type - buffered data type mismatch");
171346 }
171347 return reinterpret_cast<TARGET &>(*this);
171348 }
171349
171350 template <class TARGET>
171351 const TARGET &Cast() const {
171352 if (TARGET::TYPE != type) {
171353 throw InternalException("Failed to cast buffered data to type - buffered data type mismatch");
171354 }
171355 return reinterpret_cast<const TARGET &>(*this);
171356 }
171357
171358protected:
171359 Type type;
171361 weak_ptr<ClientContext> context;
171363 idx_t total_buffer_size;
171365 mutex glock;
171366};
171367
171368}
171369
171370
171371
171372
171373
171374
171375namespace duckdb {
171376
171377class StreamQueryResult;
171378class ClientContextLock;
171379
171380class SimpleBufferedData : public BufferedData {
171381public:
171382 static constexpr const BufferedData::Type
TYPE = BufferedData::Type::SIMPLE;
171383
171384public:
171385 explicit SimpleBufferedData(ClientContext &context);
171386 ~SimpleBufferedData() override;
171387
171388public:
171389 void Append(const DataChunk &chunk);
171390 void BlockSink(const InterruptState &blocked_sink);
171391 bool BufferIsFull();
171392 void UnblockSinks() override;
171393 StreamExecutionResult ExecuteTaskInternal(StreamQueryResult &result, ClientContextLock &context_lock) override;
171394 unique_ptr<DataChunk> Scan() override;
171395 inline idx_t BufferSize()
const {
171396 return buffer_size;
171397 }
171398
171399private:
171401 queue<InterruptState> blocked_sinks;
171403 queue<unique_ptr<DataChunk>> buffered_chunks;
171405 atomic<idx_t> buffered_count;
171407 idx_t buffer_size;
171408};
171409
171410}
171411
171412
171413namespace duckdb {
171414
171415class ClientContext;
171416class ClientContextLock;
171417class Executor;
171418class MaterializedQueryResult;
171419class PreparedStatementData;
171420
171421class StreamQueryResult : public QueryResult {
171422 friend class ClientContext;
171423
171424public:
171425 static constexpr const QueryResultType
TYPE = QueryResultType::STREAM_RESULT;
171426
171427public:
171430 DUCKDB_API StreamQueryResult(StatementType statement_type, StatementProperties properties,
171431 vector<LogicalType> types, vector<string> names, ClientProperties client_properties,
171432 shared_ptr<BufferedData> buffered_data);
171433 DUCKDB_API explicit StreamQueryResult(ErrorData error);
171434 DUCKDB_API ~StreamQueryResult() override;
171435
171436public:
171437 static bool IsChunkReady(StreamExecutionResult result);
171439 DUCKDB_API void WaitForTask();
171441 DUCKDB_API StreamExecutionResult ExecuteTask();
171443 DUCKDB_API string ToString() override;
171445 DUCKDB_API unique_ptr<MaterializedQueryResult> Materialize();
171446
171447 DUCKDB_API bool IsOpen();
171448
171450 DUCKDB_API void Close();
171451
171453 shared_ptr<ClientContext> context;
171454
171455protected:
171456 DUCKDB_API unique_ptr<DataChunk> FetchInternal() override;
171457
171458private:
171459 StreamExecutionResult ExecuteTaskInternal(ClientContextLock &lock);
171460 unique_ptr<DataChunk> FetchNextInternal(ClientContextLock &lock);
171461 unique_ptr<ClientContextLock> LockContext();
171462 void CheckExecutableInternal(ClientContextLock &lock);
171463 bool IsOpenInternal(ClientContextLock &lock);
171464
171465private:
171466 shared_ptr<BufferedData> buffered_data;
171467};
171468
171469}
171470
171471
171472
171473
171474
171475
171476
171477
171478
171479
171480
171481
171482
171483namespace duckdb {
171484
171485class TableDescription {
171486public:
171487 TableDescription(const string &database_name, const string &schema_name, const string &table_name)
171488 : database(database_name), schema(schema_name), table(table_name) {};
171489
171490 TableDescription() = delete;
171491
171492public:
171494 string database;
171496 string schema;
171498 string table;
171500 bool readonly;
171502 vector<ColumnDefinition> columns;
171503
171504public:
171505 idx_t PhysicalColumnCount()
const {
171507 for (auto &column : columns) {
171508 if (column.Generated()) {
171509 continue;
171510 }
171511 count++;
171512 }
171513 D_ASSERT(count != 0);
171514 return count;
171515 }
171516};
171517
171518}
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
171548namespace duckdb {
171549
171550enum class TransactionType :
uint8_t { INVALID, BEGIN_TRANSACTION, COMMIT, ROLLBACK };
171551
171552enum class TransactionModifierType :
uint8_t {
171553 TRANSACTION_DEFAULT_MODIFIER,
171554 TRANSACTION_READ_ONLY,
171555 TRANSACTION_READ_WRITE
171556};
171557
171558enum class TransactionInvalidationPolicy :
uint8_t { STANDARD_POLICY, ALL_ERRORS_INVALIDATE_TRANSACTION };
171559
171560struct TransactionInfo : public ParseInfo {
171561public:
171562 static constexpr const ParseInfoType
TYPE = ParseInfoType::TRANSACTION_INFO;
171563
171564public:
171565 explicit TransactionInfo(
171566 TransactionType type,
171567 TransactionInvalidationPolicy invalidation_policy = TransactionInvalidationPolicy::STANDARD_POLICY,
171568 bool auto_rollback = false);
171569
171571 TransactionType type;
171573 TransactionModifierType modifier;
171575 TransactionInvalidationPolicy invalidation_policy;
171577 bool auto_rollback;
171578
171579public:
171580 void Serialize(Serializer &serializer) const override;
171581 static unique_ptr<ParseInfo> Deserialize(Deserializer &deserializer);
171582
171583 string ToString() const;
171584 unique_ptr<TransactionInfo> Copy() const;
171585
171586private:
171587 TransactionInfo();
171588};
171589
171590}
171591
171592
171593namespace duckdb {
171594
171595class ClientContext;
171596class MetaTransaction;
171597class Transaction;
171598class TransactionManager;
171599
171602class TransactionContext {
171603public:
171604 explicit TransactionContext(ClientContext &context);
171605 ~TransactionContext();
171606
171607 MetaTransaction &ActiveTransaction() {
171608 if (!current_transaction) {
171609 throw InternalException("TransactionContext::ActiveTransaction called without active transaction");
171610 }
171611 return *current_transaction;
171612 }
171613
171614 bool HasActiveTransaction() const {
171615 return current_transaction.get();
171616 }
171617
171618 void BeginTransaction();
171619 void Commit();
171620 void Rollback(optional_ptr<ErrorData>);
171621 void ClearTransaction();
171622
171623 void SetAutoCommit(bool value);
171624 bool IsAutoCommit() const {
171625 return auto_commit;
171626 }
171627
171628 void SetReadOnly();
171629
171630 idx_t GetActiveQuery();
171631 void ResetActiveQuery();
171632 void SetActiveQuery(transaction_t query_number);
171633
171634 void SetInvalidationPolicy(TransactionInvalidationPolicy new_invalidation_policy) {
171635 invalidation_policy = new_invalidation_policy;
171636 };
171637 TransactionInvalidationPolicy GetInvalidationPolicy() {
171638 return invalidation_policy;
171639 };
171640 void SetAutoRollback(bool new_auto_rollback) {
171641 auto_rollback = new_auto_rollback;
171642 };
171643 bool GetAutoRollback() {
171644 return auto_rollback;
171645 };
171646
171647private:
171648 ClientContext &context;
171649 bool auto_commit;
171650 TransactionInvalidationPolicy invalidation_policy;
171651 bool auto_rollback;
171652
171653 unique_ptr<MetaTransaction> current_transaction;
171654
171655 TransactionContext(const TransactionContext &) = delete;
171656};
171657
171658}
171659
171660
171661
171662namespace duckdb {
171663
171664class Appender;
171665class Catalog;
171666class CatalogSearchPath;
171667class ColumnDataCollection;
171668class DatabaseInstance;
171669class FileOpener;
171670class LogicalOperator;
171671class PreparedStatementData;
171672class Relation;
171673class BufferedFileWriter;
171674class QueryProfiler;
171675class ClientContextLock;
171676struct CreateScalarFunctionInfo;
171677class ScalarFunctionCatalogEntry;
171678struct ActiveQueryContext;
171679struct ParserOptions;
171680class SimpleBufferedData;
171681class BufferedData;
171682struct ClientData;
171683class ClientContextState;
171684class RegisteredStateManager;
171685
171686struct PendingQueryParameters {
171688 optional_ptr<case_insensitive_map_t<BoundParameterData>> parameters;
171690 QueryParameters query_parameters;
171691};
171692
171695class ClientContext : public enable_shared_from_this<ClientContext> {
171696 friend class PendingQueryResult;
171697 friend class BufferedData;
171698 friend class SimpleBufferedData;
171699 friend class BatchedBufferedData;
171700 friend class StreamQueryResult;
171701 friend class ConnectionManager;
171702
171703public:
171704 DUCKDB_API explicit ClientContext(shared_ptr<DatabaseInstance> db);
171705 DUCKDB_API ~ClientContext();
171706
171708 shared_ptr<DatabaseInstance>
db;
171710 atomic<bool> interrupted;
171712 unique_ptr<RegisteredStateManager> registered_state;
171714 shared_ptr<Logger> logger;
171716 ClientConfig config;
171718 unique_ptr<ClientData> client_data;
171720 TransactionContext transaction;
171721
171722public:
171723 MetaTransaction &ActiveTransaction() {
171724 return transaction.ActiveTransaction();
171725 }
171726
171728 DUCKDB_API void Interrupt();
171729 DUCKDB_API bool IsInterrupted() const;
171730 DUCKDB_API void ClearInterrupt();
171731 DUCKDB_API void CancelTransaction();
171732
171734 DUCKDB_API void EnableProfiling();
171736 DUCKDB_API void DisableProfiling();
171737
171741 DUCKDB_API unique_ptr<QueryResult> Query(const string &query, QueryParameters query_parameters);
171742 DUCKDB_API unique_ptr<QueryResult> Query(unique_ptr<SQLStatement> statement, QueryParameters query_parameters);
171743
171746 DUCKDB_API unique_ptr<PendingQueryResult> PendingQuery(const string &query, QueryParameters query_parameters);
171748 DUCKDB_API unique_ptr<PendingQueryResult> PendingQuery(unique_ptr<SQLStatement> statement,
171749 QueryParameters query_parameters);
171750
171752 DUCKDB_API unique_ptr<PendingQueryResult> PendingQuery(unique_ptr<SQLStatement> statement,
171753 case_insensitive_map_t<BoundParameterData> &values,
171754 QueryParameters query_parameters);
171755 DUCKDB_API unique_ptr<PendingQueryResult> PendingQuery(const string &query,
171756 case_insensitive_map_t<BoundParameterData> &values,
171757 QueryParameters query_parameters);
171758 DUCKDB_API unique_ptr<PendingQueryResult> PendingQuery(const string &query, PendingQueryParameters parameters);
171759
171761 DUCKDB_API void Destroy();
171762
171764 DUCKDB_API unique_ptr<TableDescription> TableInfo(const string &database_name, const string &schema_name,
171765 const string &table_name);
171767 DUCKDB_API unique_ptr<TableDescription> TableInfo(const string &schema_name, const string &table_name);
171769 DUCKDB_API void Append(unique_ptr<SQLStatement> stmt);
171771 DUCKDB_API void Append(TableDescription &description, ColumnDataCollection &collection);
171772
171775 DUCKDB_API void TryBindRelation(Relation &relation, vector<ColumnDefinition> &result_columns);
171776
171778 DUCKDB_API void InternalTryBindRelation(Relation &relation, vector<ColumnDefinition> &result_columns);
171779
171781 DUCKDB_API unique_ptr<PendingQueryResult> PendingQuery(const shared_ptr<Relation> &relation,
171782 QueryParameters query_parameters);
171783 DUCKDB_API unique_ptr<QueryResult> Execute(const shared_ptr<Relation> &relation);
171784
171786 DUCKDB_API unique_ptr<PreparedStatement> Prepare(const string &query);
171788 DUCKDB_API unique_ptr<PreparedStatement> Prepare(unique_ptr<SQLStatement> statement);
171789
171793 DUCKDB_API unique_ptr<PendingQueryResult> PendingQuery(const string &query,
171794 shared_ptr<PreparedStatementData> &prepared,
171795 const PendingQueryParameters ¶meters);
171796
171800 DUCKDB_API unique_ptr<QueryResult>
171801 Execute(const string &query, shared_ptr<PreparedStatementData> &prepared,
171802 case_insensitive_map_t<BoundParameterData> &values,
171803 QueryParameters query_parameters = QueryResultOutputType::ALLOW_STREAMING);
171804 DUCKDB_API unique_ptr<QueryResult> Execute(const string &query, shared_ptr<PreparedStatementData> &prepared,
171805 const PendingQueryParameters ¶meters);
171806
171808 DUCKDB_API QueryProgress GetQueryProgress();
171809
171811 DUCKDB_API void RegisterFunction(CreateFunctionInfo &info);
171812
171814 DUCKDB_API vector<unique_ptr<SQLStatement>> ParseStatements(const string &query);
171815
171817 DUCKDB_API unique_ptr<LogicalOperator> ExtractPlan(const string &query);
171818 DUCKDB_API void PreprocessStatements(vector<unique_ptr<SQLStatement>> &statements);
171819
171822 DUCKDB_API void RunFunctionInTransaction(const std::function<void(void)> &fun,
171823 bool requires_valid_transaction = true);
171825 DUCKDB_API void RunFunctionInTransactionInternal(ClientContextLock &lock, const std::function<void(void)> &fun,
171826 bool requires_valid_transaction = true);
171827
171829 DUCKDB_API SettingLookupResult TryGetCurrentSetting(const string &key, Value &result) const;
171831 DUCKDB_API SettingLookupResult TryGetCurrentUserSetting(idx_t setting_index, Value &result) const;
171832
171834 DUCKDB_API ParserOptions GetParserOptions() const;
171835
171837 DUCKDB_API bool IsActiveResult(ClientContextLock &lock, BaseQueryResult &result);
171838
171840 Executor &GetExecutor();
171841
171843 Logger &GetLogger() const;
171844
171846 const string &GetCurrentQuery();
171847
171849
171853 DUCKDB_API unordered_set<string> GetTableNames(const string &query, const bool qualified = false);
171854
171855 DUCKDB_API ClientProperties GetClientProperties();
171856
171858 DUCKDB_API bool ExecutionIsFinished();
171859
171861 DUCKDB_API void ProcessError(ErrorData &error, const string &query) const;
171862
171863 DUCKDB_API LogicalType ParseLogicalType(const string &type);
171864
171865private:
171867 vector<unique_ptr<SQLStatement>> ParseStatements(ClientContextLock &lock, const string &query);
171869 unique_ptr<PendingQueryResult> PendingQueryInternal(ClientContextLock &lock, unique_ptr<SQLStatement> statement,
171870 const PendingQueryParameters ¶meters, bool verify = true);
171871 unique_ptr<QueryResult> ExecutePendingQueryInternal(ClientContextLock &lock, PendingQueryResult &query);
171872
171874 vector<unique_ptr<SQLStatement>> ParseStatementsInternal(ClientContextLock &lock, const string &query);
171877 ErrorData VerifyQuery(ClientContextLock &lock, const string &query, unique_ptr<SQLStatement> statement,
171878 PendingQueryParameters parameters);
171879
171880 void InitialCleanup(ClientContextLock &lock);
171882 void CleanupInternal(ClientContextLock &lock, BaseQueryResult *result = nullptr,
171883 bool invalidate_transaction = false);
171884 unique_ptr<PendingQueryResult> PendingStatementOrPreparedStatement(ClientContextLock &lock, const string &query,
171885 unique_ptr<SQLStatement> statement,
171886 shared_ptr<PreparedStatementData> &prepared,
171887 const PendingQueryParameters ¶meters);
171888 unique_ptr<PendingQueryResult> PendingPreparedStatement(ClientContextLock &lock, const string &query,
171889 shared_ptr<PreparedStatementData> statement_p,
171890 const PendingQueryParameters ¶meters);
171891 unique_ptr<PendingQueryResult> PendingPreparedStatementInternal(ClientContextLock &lock,
171892 shared_ptr<PreparedStatementData> statement_data_p,
171893 const PendingQueryParameters ¶meters);
171894 void CheckIfPreparedStatementIsExecutable(PreparedStatementData &statement);
171895
171897 shared_ptr<PreparedStatementData>
171898 CreatePreparedStatement(ClientContextLock &lock, const string &query, unique_ptr<SQLStatement> statement,
171899 PendingQueryParameters parameters,
171900 PreparedStatementMode mode = PreparedStatementMode::PREPARE_ONLY);
171901 unique_ptr<PendingQueryResult> PendingStatementInternal(ClientContextLock &lock, const string &query,
171902 unique_ptr<SQLStatement> statement,
171903 const PendingQueryParameters ¶meters);
171904 unique_ptr<QueryResult> RunStatementInternal(ClientContextLock &lock, const string &query,
171905 unique_ptr<SQLStatement> statement,
171906 const PendingQueryParameters ¶meters, bool verify = true);
171907 unique_ptr<PreparedStatement> PrepareInternal(ClientContextLock &lock, unique_ptr<SQLStatement> statement);
171908 void LogQueryInternal(ClientContextLock &lock, const string &query);
171909
171910 unique_ptr<QueryResult> FetchResultInternal(ClientContextLock &lock, PendingQueryResult &pending);
171911
171912 unique_ptr<ClientContextLock> LockContext();
171913
171914 void BeginQueryInternal(ClientContextLock &lock, const string &query);
171915 ErrorData EndQueryInternal(ClientContextLock &lock, bool success, bool invalidate_transaction,
171916 optional_ptr<ErrorData> previous_error);
171917
171919 void WaitForTask(ClientContextLock &lock, BaseQueryResult &result);
171920 PendingExecutionResult ExecuteTaskInternal(ClientContextLock &lock, BaseQueryResult &result, bool dry_run = false);
171921
171922 unique_ptr<PendingQueryResult> PendingStatementOrPreparedStatementInternal(
171923 ClientContextLock &lock, const string &query, unique_ptr<SQLStatement> statement,
171924 shared_ptr<PreparedStatementData> &prepared, const PendingQueryParameters ¶meters);
171925
171926 unique_ptr<PendingQueryResult> PendingQueryPreparedInternal(ClientContextLock &lock, const string &query,
171927 shared_ptr<PreparedStatementData> &prepared,
171928 const PendingQueryParameters ¶meters);
171929
171930 unique_ptr<PendingQueryResult> PendingQueryInternal(ClientContextLock &, const shared_ptr<Relation> &relation,
171931 QueryParameters query_parameters);
171932
171933 void RebindPreparedStatement(ClientContextLock &lock, const string &query,
171934 shared_ptr<PreparedStatementData> &prepared, const PendingQueryParameters ¶meters);
171935
171936 template <class T>
171937 unique_ptr<T> ErrorResult(ErrorData error, const string &query = string());
171938
171939 shared_ptr<PreparedStatementData> CreatePreparedStatementInternal(ClientContextLock &lock, const string &query,
171940 unique_ptr<SQLStatement> statement,
171941 PendingQueryParameters parameters);
171942
171943 bool ErrorInvalidatesTransaction(ExceptionType type);
171944
171945private:
171947 mutex context_lock;
171949 unique_ptr<ActiveQueryContext> active_query;
171951 QueryProgress query_progress;
171954};
171955
171956class ClientContextLock {
171957public:
171958 explicit ClientContextLock(mutex &context_lock) : client_guard(context_lock) {
171959 }
171960
171961 ~ClientContextLock() {
171962 }
171963
171964private:
171965 lock_guard<mutex> client_guard;
171966};
171967
171970class QueryContext {
171971public:
171972 QueryContext() : context(nullptr) {
171973 }
171974 QueryContext(optional_ptr<ClientContext> context) : context(context) {
171975 }
171976 QueryContext(ClientContext &context) : context(&context) {
171977 }
171978
171979public:
171980 bool Valid() const {
171981 return context != nullptr;
171982 }
171983 optional_ptr<ClientContext> GetClientContext() const {
171984 return context;
171985 }
171986
171987private:
171988 optional_ptr<ClientContext> context;
171989};
171990
171991}
171992
171993
171994
171995
171996
171997
171998
171999
172000
172001
172002
172003
172004
172005
172006namespace duckdb {
172007
172008class ClientContext;
172009
172010class Relation;
172011
172012class ClientContextWrapper {
172013public:
172014 virtual ~ClientContextWrapper() = default;
172015 explicit ClientContextWrapper(const shared_ptr<ClientContext> &context);
172016 shared_ptr<ClientContext> GetContext();
172017 shared_ptr<ClientContext> TryGetContext();
172018 virtual void TryBindRelation(Relation &relation, vector<ColumnDefinition> &columns);
172019
172020private:
172021 weak_ptr<ClientContext> client_context;
172022};
172023
172024}
172025
172026
172027
172028
172029
172030
172031
172032
172033
172034
172035
172036
172037
172038
172039
172040
172041
172042
172043
172044
172045
172046
172047
172048
172049
172050
172051
172052
172053
172054
172055
172056
172057
172058
172059
172060
172061
172062namespace duckdb {
172063
172064enum class OutputStream :
uint8_t { STREAM_STDOUT = 1, STREAM_STDERR = 2 };
172065
172066typedef void (*line_printer_f)(OutputStream stream, const string &str);
172067
172069class Printer {
172070public:
172072 DUCKDB_API static void Print(OutputStream stream, const string &str);
172074 DUCKDB_API static void Print(const string &str);
172076 template <typename... ARGS>
172077 static void PrintF(OutputStream stream, const string &str, ARGS... params) {
172079 }
172081 template <typename... ARGS>
172082 static void PrintF(const string &str, ARGS... params) {
172083 Printer::PrintF(OutputStream::STREAM_STDERR, str, std::forward<ARGS>(params)...);
172084 }
172086 DUCKDB_API static void RawPrint(OutputStream stream, const string &str);
172088 DUCKDB_API static void Flush(OutputStream stream);
172090 DUCKDB_API static bool IsTerminal(OutputStream stream);
172092 DUCKDB_API
static idx_t TerminalWidth();
172093
172094
172095 static line_printer_f line_printer;
172096
172097private:
172098 static void DefaultLinePrint(OutputStream stream, const string &str);
172099};
172100}
172101
172102
172103
172104namespace duckdb {
172105
172107class SQLStatement {
172108public:
172109 static constexpr const StatementType
TYPE = StatementType::INVALID_STATEMENT;
172110
172111public:
172112 explicit SQLStatement(StatementType type) : type(type) {
172113 }
172114 virtual ~SQLStatement() {
172115 }
172116
172118 StatementType type;
172120 idx_t stmt_location = 0;
172122 idx_t stmt_length = 0;
172124 case_insensitive_map_t<idx_t> named_param_map;
172126 string query;
172127
172128protected:
172129 SQLStatement(const SQLStatement &other) = default;
172130
172131public:
172132 virtual string ToString() const = 0;
172134 DUCKDB_API virtual unique_ptr<SQLStatement> Copy() const = 0;
172135
172136public:
172137public:
172138 template <class TARGET>
172139 TARGET &Cast() {
172140 if (type != TARGET::TYPE && TARGET::TYPE != StatementType::INVALID_STATEMENT) {
172141 throw InternalException("Failed to cast statement to type - statement type mismatch");
172142 }
172143 return reinterpret_cast<TARGET &>(*this);
172144 }
172145
172146 template <class TARGET>
172147 const TARGET &Cast() const {
172148 if (type != TARGET::TYPE && TARGET::TYPE != StatementType::INVALID_STATEMENT) {
172149 throw InternalException("Failed to cast statement to type - statement type mismatch");
172150 }
172151 return reinterpret_cast<const TARGET &>(*this);
172152 }
172153};
172154}
172155
172156
172157
172158namespace duckdb {
172159
172160enum class ExplainType :
uint8_t { EXPLAIN_STANDARD, EXPLAIN_ANALYZE };
172161
172162class ExplainStatement : public SQLStatement {
172163public:
172164 static constexpr const StatementType
TYPE = StatementType::EXPLAIN_STATEMENT;
172165
172166public:
172167 explicit ExplainStatement(unique_ptr<SQLStatement> stmt, ExplainType explain_type = ExplainType::EXPLAIN_STANDARD,
172168 ExplainFormat explain_format = ExplainFormat::DEFAULT);
172169
172170 unique_ptr<SQLStatement> stmt;
172171 ExplainType explain_type;
172172 ExplainFormat explain_format = ExplainFormat::DEFAULT;
172173
172174protected:
172175 ExplainStatement(const ExplainStatement &other);
172176
172177public:
172178 unique_ptr<SQLStatement> Copy() const override;
172179 string OptionsToString() const;
172180 string ToString() const override;
172181};
172182
172183}
172184
172185
172186
172187
172188
172189
172190
172191namespace duckdb {
172192struct BoundStatement;
172193
172194class Binder;
172195class LogicalOperator;
172196class QueryNode;
172197class TableRef;
172198
172199static string CreateRelationAlias(RelationType type, const string &alias) {
172200 if (!alias.empty()) {
172201 return alias;
172202 }
172203 return StringUtil::Format(
"%s_%s", EnumUtil::ToString(type), StringUtil::GenerateRandomName());
172204}
172205
172206class RelationContextWrapper : public ClientContextWrapper {
172207public:
172208 ~RelationContextWrapper() override = default;
172209 explicit RelationContextWrapper(const shared_ptr<ClientContext> &context) : ClientContextWrapper(context) {};
172210
172211 explicit RelationContextWrapper(const ClientContextWrapper &context) : ClientContextWrapper(context) {};
172212
172213 void TryBindRelation(Relation &relation, vector<ColumnDefinition> &columns) override {
172214 GetContext()->TryBindRelation(relation, columns);
172215 }
172216
172217private:
172218 weak_ptr<ClientContext> client_context;
172219};
172220
172221class Relation : public enable_shared_from_this<Relation> {
172222public:
172223 Relation(const shared_ptr<ClientContext> &context_p, const RelationType type) : type(type) {
172224 context = make_shared_ptr<ClientContextWrapper>(context_p);
172225 }
172226 Relation(const shared_ptr<ClientContextWrapper> &context, RelationType type, const string &alias_p = "")
172227 : context(context), type(type), alias(CreateRelationAlias(type, alias_p)) {
172228 }
172229
172230 Relation(const shared_ptr<RelationContextWrapper> &context, RelationType type, const string &alias_p = "")
172231 : context(context), type(type), alias(CreateRelationAlias(type, alias_p)) {
172232 }
172233
172234 virtual ~Relation() = default;
172235
172236 shared_ptr<ClientContextWrapper> context;
172237 RelationType type;
172238 const string alias;
172239 vector<shared_ptr<ExternalDependency>> external_dependencies;
172240
172241public:
172242 DUCKDB_API virtual const vector<ColumnDefinition> &Columns() = 0;
172243 DUCKDB_API virtual unique_ptr<QueryNode> GetQueryNode() = 0;
172244 DUCKDB_API virtual string GetQuery();
172245 DUCKDB_API virtual BoundStatement Bind(Binder &binder);
172246 DUCKDB_API virtual string GetAlias();
172247
172248 DUCKDB_API unique_ptr<QueryResult> ExecuteOrThrow();
172249 DUCKDB_API unique_ptr<QueryResult> Execute();
172250 DUCKDB_API string ToString();
172251 DUCKDB_API virtual string ToString(idx_t depth) = 0;
172252
172253 DUCKDB_API void Print();
172254 DUCKDB_API void Head(idx_t limit = 10);
172255
172256 DUCKDB_API shared_ptr<Relation> CreateView(const string &name, bool replace = true, bool temporary = false);
172257 DUCKDB_API shared_ptr<Relation> CreateView(const string &schema_name, const string &name, bool replace = true,
172258 bool temporary = false);
172259 DUCKDB_API unique_ptr<QueryResult> Query(const string &sql) const;
172260 DUCKDB_API unique_ptr<QueryResult> Query(const string &name, const string &sql);
172261
172263 DUCKDB_API unique_ptr<QueryResult> Explain(ExplainType type = ExplainType::EXPLAIN_STANDARD,
172264 ExplainFormat explain_format = ExplainFormat::DEFAULT);
172265
172266 DUCKDB_API virtual unique_ptr<TableRef> GetTableRef();
172267 virtual bool IsReadOnly() {
172268 return true;
172269 }
172270 DUCKDB_API void TryBindRelation(vector<ColumnDefinition> &columns);
172271
172272public:
172273
172274 DUCKDB_API shared_ptr<Relation> Project(const string &select_list);
172275 DUCKDB_API shared_ptr<Relation> Project(const string &expression, const string &alias);
172276 DUCKDB_API shared_ptr<Relation> Project(const string &select_list, const vector<string> &aliases);
172277 DUCKDB_API shared_ptr<Relation> Project(const vector<string> &expressions);
172278 DUCKDB_API shared_ptr<Relation> Project(const vector<string> &expressions, const vector<string> &aliases);
172279 DUCKDB_API shared_ptr<Relation> Project(vector<unique_ptr<ParsedExpression>> expressions,
172280 const vector<string> &aliases);
172281
172282
172283 DUCKDB_API shared_ptr<Relation> Filter(const string &expression);
172284 DUCKDB_API shared_ptr<Relation> Filter(unique_ptr<ParsedExpression> expression);
172285 DUCKDB_API shared_ptr<Relation> Filter(const vector<string> &expressions);
172286
172287
172288 DUCKDB_API shared_ptr<Relation> Limit(int64_t n, int64_t offset = 0);
172289
172290
172291 DUCKDB_API shared_ptr<Relation> Order(const string &expression);
172292 DUCKDB_API shared_ptr<Relation> Order(const vector<string> &expressions);
172293 DUCKDB_API shared_ptr<Relation> Order(vector<OrderByNode> expressions);
172294
172295
172296 DUCKDB_API shared_ptr<Relation> Join(const shared_ptr<Relation> &other, const string &condition,
172297 JoinType type = JoinType::INNER, JoinRefType ref_type = JoinRefType::REGULAR);
172298 shared_ptr<Relation> Join(const shared_ptr<Relation> &other, vector<unique_ptr<ParsedExpression>> condition,
172299 JoinType type = JoinType::INNER, JoinRefType ref_type = JoinRefType::REGULAR);
172300
172301
172302 DUCKDB_API shared_ptr<Relation> CrossProduct(const shared_ptr<Relation> &other,
172303 JoinRefType join_ref_type = JoinRefType::CROSS);
172304
172305
172306 DUCKDB_API shared_ptr<Relation> Union(const shared_ptr<Relation> &other);
172307 DUCKDB_API shared_ptr<Relation> Except(const shared_ptr<Relation> &other);
172308 DUCKDB_API shared_ptr<Relation> Intersect(const shared_ptr<Relation> &other);
172309
172310
172311 DUCKDB_API shared_ptr<Relation> Distinct();
172312
172313
172314 DUCKDB_API shared_ptr<Relation> Aggregate(const string &aggregate_list);
172315 DUCKDB_API shared_ptr<Relation> Aggregate(const vector<string> &aggregates);
172316 DUCKDB_API shared_ptr<Relation> Aggregate(vector<unique_ptr<ParsedExpression>> expressions);
172317 DUCKDB_API shared_ptr<Relation> Aggregate(const string &aggregate_list, const string &group_list);
172318 DUCKDB_API shared_ptr<Relation> Aggregate(const vector<string> &aggregates, const vector<string> &groups);
172319 DUCKDB_API shared_ptr<Relation> Aggregate(vector<unique_ptr<ParsedExpression>> expressions,
172320 const string &group_list);
172321
172322
172323 DUCKDB_API shared_ptr<Relation> Alias(const string &alias);
172324
172326 DUCKDB_API shared_ptr<Relation> InsertRel(const string &schema_name, const string &table_name);
172327 DUCKDB_API shared_ptr<Relation> InsertRel(const string &catalog_name, const string &schema_name,
172328 const string &table_name);
172329 DUCKDB_API void Insert(const string &table_name);
172330 DUCKDB_API void Insert(const string &schema_name, const string &table_name);
172331 DUCKDB_API void Insert(const string &catalog_name, const string &schema_name, const string &table_name);
172333 DUCKDB_API virtual void Insert(const vector<vector<Value>> &values);
172334 DUCKDB_API virtual void Insert(vector<vector<unique_ptr<ParsedExpression>>> &&expressions);
172336 DUCKDB_API shared_ptr<Relation> CreateRel(const string &schema_name, const string &table_name,
172337 bool temporary = false,
172338 OnCreateConflict on_conflict = OnCreateConflict::ERROR_ON_CONFLICT);
172339 DUCKDB_API shared_ptr<Relation> CreateRel(const string &catalog_name, const string &schema_name,
172340 const string &table_name, bool temporary = false,
172341 OnCreateConflict on_conflict = OnCreateConflict::ERROR_ON_CONFLICT);
172342 DUCKDB_API
void Create(
const string &table_name,
bool temporary =
false,
172343 OnCreateConflict on_conflict = OnCreateConflict::ERROR_ON_CONFLICT);
172344 DUCKDB_API
void Create(
const string &schema_name,
const string &table_name,
bool temporary =
false,
172345 OnCreateConflict on_conflict = OnCreateConflict::ERROR_ON_CONFLICT);
172346 DUCKDB_API
void Create(
const string &catalog_name,
const string &schema_name,
const string &table_name,
172347 bool temporary = false, OnCreateConflict on_conflict = OnCreateConflict::ERROR_ON_CONFLICT);
172348
172350 DUCKDB_API shared_ptr<Relation>
172351 WriteCSVRel(const string &csv_file,
172352 case_insensitive_map_t<vector<Value>> options = case_insensitive_map_t<vector<Value>>());
172353 DUCKDB_API void WriteCSV(const string &csv_file,
172354 case_insensitive_map_t<vector<Value>> options = case_insensitive_map_t<vector<Value>>());
172356 DUCKDB_API shared_ptr<Relation>
172357 WriteParquetRel(const string &parquet_file,
172358 case_insensitive_map_t<vector<Value>> options = case_insensitive_map_t<vector<Value>>());
172359 DUCKDB_API void
172360 WriteParquet(const string &parquet_file,
172361 case_insensitive_map_t<vector<Value>> options = case_insensitive_map_t<vector<Value>>());
172362
172364 DUCKDB_API virtual void Update(const string &update, const string &condition = string());
172365 DUCKDB_API virtual void Update(vector<string> column_names, vector<unique_ptr<ParsedExpression>> &&update,
172366 unique_ptr<ParsedExpression> condition = nullptr);
172368 DUCKDB_API virtual void Delete(const string &condition = string());
172371 DUCKDB_API shared_ptr<Relation> TableFunction(const std::string &fname, const vector<Value> &values);
172372 DUCKDB_API shared_ptr<Relation> TableFunction(const std::string &fname, const vector<Value> &values,
172373 const named_parameter_map_t &named_parameters);
172374
172375public:
172377 virtual bool InheritsColumnBindings() {
172378 return false;
172379 }
172380 virtual Relation *ChildRelation() {
172381 return nullptr;
172382 }
172383 void AddExternalDependency(shared_ptr<ExternalDependency> dependency);
172384 DUCKDB_API vector<shared_ptr<ExternalDependency>> GetAllDependencies();
172385
172386protected:
172387 DUCKDB_API static string RenderWhitespace(idx_t depth);
172388
172389public:
172390 template <class TARGET>
172391 TARGET &Cast() {
172392 DynamicCastCheck<TARGET>(this);
172393 return reinterpret_cast<TARGET &>(*this);
172394 }
172395 template <class TARGET>
172396 const TARGET &Cast() const {
172397 DynamicCastCheck<TARGET>(this);
172398 return reinterpret_cast<const TARGET &>(*this);
172399 }
172400};
172401
172402}
172403
172404
172405
172406
172407
172408
172409namespace duckdb {
172410
172411class ColumnDataCollection;
172412class ClientContext;
172413
172414class DatabaseInstance;
172415class DuckDB;
172416class LogicalOperator;
172417class SelectStatement;
172418struct CSVReaderOptions;
172419
172420typedef void (*warning_callback_t)(std::string);
172421
172424class Connection {
172425public:
172426 DUCKDB_API explicit Connection(DuckDB &database);
172427 DUCKDB_API explicit Connection(DatabaseInstance &database);
172428
172429 Connection(const Connection &other) = delete;
172430 Connection &
operator=(
const Connection &) =
delete;
172432 DUCKDB_API Connection(Connection &&other) noexcept;
172433 DUCKDB_API Connection &
operator=(Connection &&) noexcept;
172434 DUCKDB_API ~Connection();
172435
172436 shared_ptr<ClientContext> context;
172437
172438public:
172440 DUCKDB_API
string GetProfilingInformation(ProfilerPrintFormat
format = ProfilerPrintFormat::QUERY_TREE);
172441
172443 DUCKDB_API optional_ptr<ProfilingNode> GetProfilingTree();
172444
172446 DUCKDB_API void Interrupt();
172447
172449 DUCKDB_API double GetQueryProgress();
172450
172452 DUCKDB_API void EnableProfiling();
172454 DUCKDB_API void DisableProfiling();
172455
172457 DUCKDB_API void EnableQueryVerification();
172458 DUCKDB_API void DisableQueryVerification();
172460 DUCKDB_API void ForceParallelism();
172461
172466 DUCKDB_API unique_ptr<QueryResult>
172467 SendQuery(const string &query, QueryParameters query_parameters = QueryResultOutputType::ALLOW_STREAMING);
172468 DUCKDB_API unique_ptr<QueryResult>
172469 SendQuery(unique_ptr<SQLStatement> statement,
172470 QueryParameters query_parameters = QueryResultOutputType::ALLOW_STREAMING);
172473 DUCKDB_API unique_ptr<MaterializedQueryResult> Query(const string &query);
172476 DUCKDB_API unique_ptr<MaterializedQueryResult>
172477 Query(unique_ptr<SQLStatement> statement, QueryResultMemoryType memory_type = QueryResultMemoryType::IN_MEMORY);
172478
172479 template <typename... ARGS>
172480 unique_ptr<QueryResult> Query(const string &query, ARGS... args) {
172481 vector<Value> values;
172482 return QueryParamsRecursive(query, values, args...);
172483 }
172484
172487 DUCKDB_API unique_ptr<PendingQueryResult>
172488 PendingQuery(const string &query, QueryParameters query_parameters = QueryResultOutputType::FORCE_MATERIALIZED);
172490 DUCKDB_API unique_ptr<PendingQueryResult>
172491 PendingQuery(unique_ptr<SQLStatement> statement,
172492 QueryParameters query_parameters = QueryResultOutputType::FORCE_MATERIALIZED);
172493 DUCKDB_API unique_ptr<PendingQueryResult>
172494 PendingQuery(unique_ptr<SQLStatement> statement, case_insensitive_map_t<BoundParameterData> &named_values,
172495 QueryParameters query_parameters = QueryResultOutputType::FORCE_MATERIALIZED);
172496 DUCKDB_API unique_ptr<PendingQueryResult>
172497 PendingQuery(const string &query, case_insensitive_map_t<BoundParameterData> &named_values,
172498 QueryParameters query_parameters = QueryResultOutputType::FORCE_MATERIALIZED);
172499 DUCKDB_API unique_ptr<PendingQueryResult>
172500 PendingQuery(const string &query, vector<Value> &values,
172501 QueryParameters query_parameters = QueryResultOutputType::FORCE_MATERIALIZED);
172502 DUCKDB_API unique_ptr<PendingQueryResult> PendingQuery(const string &query, PendingQueryParameters parameters);
172503 DUCKDB_API unique_ptr<PendingQueryResult>
172504 PendingQuery(unique_ptr<SQLStatement> statement, vector<Value> &values,
172505 QueryParameters query_parameters = QueryResultOutputType::FORCE_MATERIALIZED);
172506
172508 DUCKDB_API unique_ptr<PreparedStatement> Prepare(const string &query);
172510 DUCKDB_API unique_ptr<PreparedStatement> Prepare(unique_ptr<SQLStatement> statement);
172511
172513 DUCKDB_API unique_ptr<TableDescription> TableInfo(const string &database_name, const string &schema_name,
172514 const string &table_name);
172516 DUCKDB_API unique_ptr<TableDescription> TableInfo(const string &schema_name, const string &table_name);
172519 DUCKDB_API unique_ptr<TableDescription> TableInfo(const string &table_name);
172520
172522 DUCKDB_API vector<unique_ptr<SQLStatement>> ExtractStatements(const string &query);
172524 DUCKDB_API unique_ptr<LogicalOperator> ExtractPlan(const string &query);
172525
172527 DUCKDB_API void Append(TableDescription &description, ColumnDataCollection &collection);
172528
172530 DUCKDB_API shared_ptr<Relation> Table(const string &tname);
172531 DUCKDB_API shared_ptr<Relation> Table(const string &schema_name, const string &table_name);
172532 DUCKDB_API shared_ptr<Relation> Table(const string &catalog_name, const string &schema_name,
172533 const string &table_name);
172535 DUCKDB_API shared_ptr<Relation> View(const string &tname);
172536 DUCKDB_API shared_ptr<Relation> View(const string &schema_name, const string &table_name);
172538 DUCKDB_API shared_ptr<Relation> TableFunction(const string &tname);
172539 DUCKDB_API shared_ptr<Relation> TableFunction(const string &tname, const vector<Value> &values,
172540 const named_parameter_map_t &named_parameters);
172541 DUCKDB_API shared_ptr<Relation> TableFunction(const string &tname, const vector<Value> &values);
172543 DUCKDB_API shared_ptr<Relation> Values(const vector<vector<Value>> &values);
172544 DUCKDB_API shared_ptr<Relation> Values(vector<vector<unique_ptr<ParsedExpression>>> &&values);
172545 DUCKDB_API shared_ptr<Relation> Values(const vector<vector<Value>> &values, const vector<string> &column_names,
172546 const string &alias = "values");
172547 DUCKDB_API shared_ptr<Relation> Values(const string &values);
172548 DUCKDB_API shared_ptr<Relation> Values(const string &values, const vector<string> &column_names,
172549 const string &alias = "values");
172550
172552 DUCKDB_API shared_ptr<Relation> ReadCSV(const string &csv_file);
172553 DUCKDB_API shared_ptr<Relation> ReadCSV(const vector<string> &csv_input, named_parameter_map_t &&options);
172554 DUCKDB_API shared_ptr<Relation> ReadCSV(const string &csv_input, named_parameter_map_t &&options);
172555 DUCKDB_API shared_ptr<Relation> ReadCSV(const string &csv_file, const vector<string> &columns);
172556
172558 DUCKDB_API shared_ptr<Relation> ReadParquet(const string &parquet_file, bool binary_as_string);
172560 DUCKDB_API shared_ptr<Relation> RelationFromQuery(const string &query, const string &alias = "queryrelation",
172561 const string &error = "Expected a single SELECT statement");
172562 DUCKDB_API shared_ptr<Relation> RelationFromQuery(unique_ptr<SelectStatement> select_stmt,
172563 const string &alias = "queryrelation", const string &query = "");
172564
172565 DUCKDB_API void BeginTransaction();
172566 DUCKDB_API void Commit();
172567 DUCKDB_API void Rollback();
172568 DUCKDB_API void SetAutoCommit(bool auto_commit);
172569 DUCKDB_API bool IsAutoCommit();
172570 DUCKDB_API bool HasActiveTransaction();
172571
172575 DUCKDB_API unordered_set<string> GetTableNames(const string &query, const bool qualified = false);
172576
172577
172578 template <typename TR, typename... ARGS>
172579 void CreateScalarFunction(const string &name, TR (*udf_func)(ARGS...)) {
172580 scalar_function_t function = UDFWrapper::CreateScalarFunction<TR, ARGS...>(name, udf_func);
172581 UDFWrapper::RegisterFunction<TR, ARGS...>(name, function, *context);
172582 }
172583
172584 template <typename TR, typename... ARGS>
172585 void CreateScalarFunction(const string &name, vector<LogicalType> args, LogicalType ret_type,
172586 TR (*udf_func)(ARGS...)) {
172587 scalar_function_t function = UDFWrapper::CreateScalarFunction<TR, ARGS...>(name, args, ret_type, udf_func);
172588 UDFWrapper::RegisterFunction(name, args, ret_type, function, *context);
172589 }
172590
172591 template <typename TR, typename... ARGS>
172592 void CreateVectorizedFunction(const string &name, scalar_function_t udf_func,
172593 LogicalType varargs = LogicalType::INVALID) {
172594 UDFWrapper::RegisterFunction<TR, ARGS...>(name, udf_func, *context, std::move(varargs));
172595 }
172596
172597 void CreateVectorizedFunction(const string &name, vector<LogicalType> args, LogicalType ret_type,
172598 scalar_function_t udf_func, LogicalType varargs = LogicalType::INVALID) {
172599 UDFWrapper::RegisterFunction(name, std::move(args), std::move(ret_type), std::move(udf_func), *context,
172600 std::move(varargs));
172601 }
172602
172603
172604 template <typename UDF_OP, typename STATE, typename TR, typename TA>
172605 void CreateAggregateFunction(const string &name) {
172606 AggregateFunction function = UDFWrapper::CreateAggregateFunction<UDF_OP, STATE, TR, TA>(name);
172607 UDFWrapper::RegisterAggrFunction(function, *context);
172608 }
172609
172610 template <typename UDF_OP, typename STATE, typename TR, typename TA, typename TB>
172611 void CreateAggregateFunction(const string &name) {
172612 AggregateFunction function = UDFWrapper::CreateAggregateFunction<UDF_OP, STATE, TR, TA, TB>(name);
172613 UDFWrapper::RegisterAggrFunction(function, *context);
172614 }
172615
172616 template <typename UDF_OP, typename STATE, typename TR, typename TA>
172617 void CreateAggregateFunction(const string &name, LogicalType ret_type, LogicalType input_type_a) {
172618 AggregateFunction function =
172619 UDFWrapper::CreateAggregateFunction<UDF_OP, STATE, TR, TA>(name, ret_type, input_type_a);
172620 UDFWrapper::RegisterAggrFunction(function, *context);
172621 }
172622
172623 template <typename UDF_OP, typename STATE, typename TR, typename TA, typename TB>
172624 void CreateAggregateFunction(const string &name, LogicalType ret_type, LogicalType input_type_a,
172625 LogicalType input_type_b) {
172626 AggregateFunction function =
172627 UDFWrapper::CreateAggregateFunction<UDF_OP, STATE, TR, TA, TB>(name, ret_type, input_type_a, input_type_b);
172628 UDFWrapper::RegisterAggrFunction(function, *context);
172629 }
172630
172631 void CreateAggregateFunction(const string &name, const vector<LogicalType> &arguments,
172632 const LogicalType &return_type, aggregate_size_t state_size,
172633 aggregate_initialize_t initialize, aggregate_update_t update,
172634 aggregate_combine_t combine, aggregate_finalize_t finalize,
172635 aggregate_simple_update_t simple_update = nullptr,
172636 bind_aggregate_function_t bind = nullptr,
172637 aggregate_destructor_t destructor = nullptr) {
172638 AggregateFunction function =
172639 UDFWrapper::CreateAggregateFunction(name, arguments, return_type, state_size, initialize, update, combine,
172640 finalize, simple_update, bind, destructor);
172641 UDFWrapper::RegisterAggrFunction(function, *context);
172642 }
172643
172644
172645protected:
172648
172649private:
172650 unique_ptr<QueryResult> QueryParamsRecursive(const string &query, vector<Value> &values);
172651
172652 template <typename T, typename... ARGS>
172653 unique_ptr<QueryResult> QueryParamsRecursive(const string &query, vector<Value> &values, T value, ARGS... args) {
172654 values.push_back(Value::CreateValue<T>(value));
172655 return QueryParamsRecursive(query, values, args...);
172656 }
172657};
172658
172659}
172660
172661
172662
172663
172664
172665
172666
172667
172668
172669
172670
172671
172672
172673
172674
172675
172676
172677
172678
172679typedef struct {
172680
172681 duckdb_state (*
duckdb_open)(
const char *path, duckdb_database *out_database);
172682 duckdb_state (*
duckdb_open_ext)(
const char *path, duckdb_database *out_database, duckdb_config config,
172683 char **out_error);
172685 duckdb_state (*
duckdb_connect)(duckdb_database database, duckdb_connection *out_connection);
172689 const char *(*duckdb_library_version)();
172693 duckdb_state (*
duckdb_set_config)(duckdb_config config,
const char *name,
const char *option);
172695 duckdb_state (*
duckdb_query)(duckdb_connection connection,
const char *query, duckdb_result *out_result);
172697 const char *(*duckdb_column_name)(duckdb_result *result,
idx_t col);
172703 const char *(*duckdb_result_error)(duckdb_result *result);
172706 void *(*duckdb_malloc)(
size_t size);
172711 const char *(*duckdb_string_t_data)(duckdb_string_t *string);
172728 duckdb_state (*
duckdb_prepare)(duckdb_connection connection,
const char *query,
172729 duckdb_prepared_statement *out_prepared_statement);
172731 const char *(*duckdb_prepare_error)(duckdb_prepared_statement prepared_statement);
172733 const char *(*duckdb_parameter_name)(duckdb_prepared_statement prepared_statement,
idx_t index);
172738 duckdb_state (*
duckdb_bind_value)(duckdb_prepared_statement prepared_statement,
idx_t param_idx, duckdb_value val);
172740 const char *name);
172747 duckdb_hugeint val);
172749 duckdb_uhugeint val);
172751 duckdb_decimal val);
172756 duckdb_state (*
duckdb_bind_float)(duckdb_prepared_statement prepared_statement,
idx_t param_idx,
float val);
172757 duckdb_state (*
duckdb_bind_double)(duckdb_prepared_statement prepared_statement,
idx_t param_idx,
double val);
172758 duckdb_state (*
duckdb_bind_date)(duckdb_prepared_statement prepared_statement,
idx_t param_idx, duckdb_date val);
172759 duckdb_state (*
duckdb_bind_time)(duckdb_prepared_statement prepared_statement,
idx_t param_idx, duckdb_time val);
172761 duckdb_timestamp val);
172763 duckdb_timestamp val);
172765 duckdb_interval val);
172766 duckdb_state (*
duckdb_bind_varchar)(duckdb_prepared_statement prepared_statement,
idx_t param_idx,
const char *val);
172768 const char *val,
idx_t length);
172769 duckdb_state (*
duckdb_bind_blob)(duckdb_prepared_statement prepared_statement,
idx_t param_idx,
const void *data,
172772 duckdb_state (*
duckdb_execute_prepared)(duckdb_prepared_statement prepared_statement, duckdb_result *out_result);
172774 duckdb_extracted_statements *out_extracted_statements);
172776 duckdb_extracted_statements extracted_statements,
idx_t index,
172777 duckdb_prepared_statement *out_prepared_statement);
172778 const char *(*duckdb_extract_statements_error)(duckdb_extracted_statements extracted_statements);
172781 duckdb_pending_result *out_result);
172783 const char *(*duckdb_pending_error)(duckdb_pending_result pending_result);
172786 duckdb_state (*
duckdb_execute_pending)(duckdb_pending_result pending_result, duckdb_result *out_result);
172838 char *(*duckdb_get_varchar)(duckdb_value value);
172853 char *(*duckdb_logical_type_get_alias)(duckdb_logical_type type);
172859 idx_t member_count);
172861 idx_t member_count);
172870 char *(*duckdb_enum_dictionary_value)(duckdb_logical_type type,
idx_t index);
172877 char *(*duckdb_struct_type_child_name)(duckdb_logical_type type,
idx_t index);
172880 char *(*duckdb_union_type_member_name)(duckdb_logical_type type,
idx_t index);
172884 duckdb_create_type_info info);
172893 void *(*duckdb_vector_get_data)(duckdb_vector vector);
172894 uint64_t *(*duckdb_vector_get_validity)(duckdb_vector vector);
172917 duckdb_delete_callback_t destroy);
172919 duckdb_scalar_function_t function);
172921 void *(*duckdb_scalar_function_get_extra_info)(duckdb_function_info info);
172931 duckdb_logical_type type);
172933 duckdb_logical_type type);
172935 duckdb_aggregate_state_size state_size,
172936 duckdb_aggregate_init_t state_init,
172937 duckdb_aggregate_update_t update,
172938 duckdb_aggregate_combine_t
combine,
172939 duckdb_aggregate_finalize_t finalize);
172941 duckdb_aggregate_destroy_t destroy);
172943 duckdb_aggregate_function aggregate_function);
172946 duckdb_delete_callback_t destroy);
172947 void *(*duckdb_aggregate_function_get_extra_info)(duckdb_function_info info);
172952 duckdb_aggregate_function function);
172959 duckdb_logical_type type);
172961 duckdb_delete_callback_t destroy);
172965 duckdb_table_function_init_t init);
172969 void *(*duckdb_bind_get_extra_info)(duckdb_bind_info info);
172977 void *(*duckdb_init_get_extra_info)(duckdb_init_info info);
172978 void *(*duckdb_init_get_bind_data)(duckdb_init_info info);
172984 void *(*duckdb_function_get_extra_info)(duckdb_function_info info);
172985 void *(*duckdb_function_get_bind_data)(duckdb_function_info info);
172986 void *(*duckdb_function_get_init_data)(duckdb_function_info info);
172987 void *(*duckdb_function_get_local_init_data)(duckdb_function_info info);
172990 duckdb_delete_callback_t delete_callback);
172997 duckdb_state (*
duckdb_appender_create)(duckdb_connection connection,
const char *schema,
const char *table,
172998 duckdb_appender *out_appender);
173000 const char *table, duckdb_appender *out_appender);
173003 const char *(*duckdb_appender_error)(duckdb_appender appender);
173011 duckdb_table_description *out);
173013 const char *schema, const char *table,
173014 duckdb_table_description *out);
173016 const char *(*duckdb_table_description_error)(duckdb_table_description table_description);
173018 char *(*duckdb_table_description_get_column_name)(duckdb_table_description table_description,
idx_t index);
173034 duckdb_delete_callback_t destroy);
173035 void *(*duckdb_cast_function_get_extra_info)(duckdb_function_info info);
173039 duckdb_vector output);
173080
173081
173083 void *(*duckdb_column_data)(duckdb_result *result,
idx_t col);
173084 bool *(*duckdb_nullmask_data)(duckdb_result *result,
idx_t col);
173106 char *(*duckdb_value_varchar)(duckdb_result *result,
idx_t col,
idx_t row);
173108 char *(*duckdb_value_varchar_internal)(duckdb_result *result,
idx_t col,
idx_t row);
173113 duckdb_result *out_result);
173115 duckdb_pending_result *out_result);
173116 duckdb_state (*
duckdb_query_arrow)(duckdb_connection connection,
const char *query, duckdb_arrow *out_result);
173124 const char *(*duckdb_query_arrow_error)(duckdb_arrow result);
173128 duckdb_arrow *out_result);
173129 duckdb_state (*
duckdb_arrow_scan)(duckdb_connection connection,
const char *table_name, duckdb_arrow_stream arrow);
173131 duckdb_arrow_schema arrow_schema, duckdb_arrow_array arrow_array,
173132 duckdb_arrow_stream *out_stream);
173134
173135
173138 duckdb_database *out_database, duckdb_config config,
173139 char **out_error);
173141
173142
173147 duckdb_logical_type *types, const char *table_name,
173148 const char **column_names, duckdb_appender *out_appender);
173150
173151
173152 duckdb_error_data (*
duckdb_to_arrow_schema)(duckdb_arrow_options arrow_options, duckdb_logical_type *types,
173153 const char **names,
idx_t column_count,
struct ArrowSchema *out_schema);
173155 struct ArrowArray *out_arrow_array);
173157 duckdb_arrow_converted_schema *out_types);
173159 duckdb_arrow_converted_schema converted_schema,
173160 duckdb_data_chunk *out_chunk);
173162
173163
173165 const char *(*duckdb_catalog_get_type_name)(duckdb_catalog catalog);
173167 duckdb_catalog_entry_type entry_type, const char *schema_name,
173168 const char *entry_name);
173171 const char *(*duckdb_catalog_entry_get_name)(duckdb_catalog_entry entry);
173173
173174
173181 duckdb_config_option_scope default_scope);
173185 duckdb_config_option_scope *out_scope);
173186
173187
173191 duckdb_delete_callback_t destructor);
173196 void *(*duckdb_copy_function_bind_get_extra_info)(duckdb_copy_function_bind_info info);
173203 duckdb_delete_callback_t destructor);
173205 duckdb_copy_function_global_init_t init);
173207 void *(*duckdb_copy_function_global_init_get_extra_info)(duckdb_copy_function_global_init_info info);
173209 duckdb_copy_function_global_init_info info);
173210 void *(*duckdb_copy_function_global_init_get_bind_data)(duckdb_copy_function_global_init_info info);
173212 void *global_state, duckdb_delete_callback_t destructor);
173213 const char *(*duckdb_copy_function_global_init_get_file_path)(duckdb_copy_function_global_init_info info);
173216 void *(*duckdb_copy_function_sink_get_extra_info)(duckdb_copy_function_sink_info info);
173218 void *(*duckdb_copy_function_sink_get_bind_data)(duckdb_copy_function_sink_info info);
173219 void *(*duckdb_copy_function_sink_get_global_state)(duckdb_copy_function_sink_info info);
173221 duckdb_copy_function_finalize_t finalize);
173223 void *(*duckdb_copy_function_finalize_get_extra_info)(duckdb_copy_function_finalize_info info);
173225 void *(*duckdb_copy_function_finalize_get_bind_data)(duckdb_copy_function_finalize_info info);
173226 void *(*duckdb_copy_function_finalize_get_global_state)(duckdb_copy_function_finalize_info info);
173228 duckdb_table_function table_function);
173230 const char *(*duckdb_table_function_bind_get_result_column_name)(duckdb_bind_info info,
idx_t col_idx);
173232
173233
173237 const char *(*duckdb_error_data_message)(duckdb_error_data error_data);
173239
173240
173245 duckdb_value *out_value);
173246
173247
173251 duckdb_file_open_options options, duckdb_file_handle *out_file);
173255 bool value);
173266
173267
173268 char *(*duckdb_geometry_type_get_crs)(duckdb_logical_type type);
173269
173270
173274 duckdb_logger_write_log_entry_t function);
173276 duckdb_delete_callback_t delete_callback);
173279
173280
173284 duckdb_value (*
duckdb_get_table_names)(duckdb_connection connection,
const char *query,
bool qualified);
173287
173288
173290 const char *(*duckdb_prepared_statement_column_name)(duckdb_prepared_statement prepared_statement,
idx_t col_idx);
173294
173295
173297
173298
173303 duckdb_delete_callback_t destroy);
173304 void *(*duckdb_scalar_function_get_bind_data)(duckdb_function_info info);
173305 void *(*duckdb_scalar_function_bind_get_extra_info)(duckdb_bind_info info);
173309
173310
173311 void *(*duckdb_scalar_function_get_state)(duckdb_function_info info);
173316 void *(*duckdb_scalar_function_init_get_bind_data)(duckdb_init_info info);
173317 void *(*duckdb_scalar_function_init_get_extra_info)(duckdb_init_info info);
173318
173319
173320 char *(*duckdb_value_to_string)(duckdb_value value);
173322
173323
173327
173328
173330
173331
173332 duckdb_value (*
duckdb_create_map_value)(duckdb_logical_type map_type, duckdb_value *keys, duckdb_value *values,
173333 idx_t entry_count);
173337
173338
173343 void (*duckdb_vector_reference_vector)(duckdb_vector to_vector, duckdb_vector from_vector);
173346 sel_t *(*duckdb_selection_vector_get_data_ptr)(duckdb_selection_vector sel);
173351} duckdb_ext_api_v1;
173352
173353
173354
173355
173356inline duckdb_ext_api_v1 CreateAPIv1() {
173357 duckdb_ext_api_v1 result;
173898 result.duckdb_vector_reference_vector = duckdb_vector_reference_vector;
173904 return result;
173905}
173906
173907#define DUCKDB_EXTENSION_API_VERSION_MAJOR 1
173908#define DUCKDB_EXTENSION_API_VERSION_MINOR 2
173909#define DUCKDB_EXTENSION_API_VERSION_PATCH 0
173910#define DUCKDB_EXTENSION_API_VERSION_STRING "v1.2.0"
173911
173912
173913
173914
173915
173916
173917
173918
173919
173920
173921
173922
173923
173924
173925
173926namespace duckdb {
173927class ExtensionLoader;
173928
173930class Extension {
173931public:
173932 DUCKDB_API virtual ~Extension();
173933
173934 DUCKDB_API virtual void Load(ExtensionLoader &db) = 0;
173935 DUCKDB_API virtual std::string Name() = 0;
173936 DUCKDB_API virtual std::string Version() const {
173937 return "";
173938 }
173939 DUCKDB_API static const char *DefaultVersion();
173940};
173941
173943 UNKNOWN = 0,
173950};
173951
173953struct ParsedExtensionMetaData {
173954 static constexpr const idx_t FOOTER_SIZE = 512;
173955 static constexpr const idx_t SIGNATURE_SIZE = 256;
173956 static constexpr const char *EXPECTED_MAGIC_VALUE = {
173957 "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"};
173958
173959 string magic_value;
173960
173962
173963 string platform;
173964
173965
173966 string duckdb_version;
173967
173968
173969 string duckdb_capi_version;
173970 string extension_version;
173971 string signature;
173972 string extension_abi_metadata;
173973
173974 bool AppearsValid() {
173975 return magic_value == EXPECTED_MAGIC_VALUE;
173976 }
173977
173978
173979 string GetInvalidMetadataError();
173980};
173981
173982struct VersioningUtils {
173984 static bool ParseSemver(string &semver, idx_t &major_out, idx_t &minor_out, idx_t &patch_out);
173985
173987 static bool IsSupportedCAPIVersion(string &capi_version_string);
173988 static bool IsSupportedCAPIVersion(idx_t major, idx_t minor, idx_t patch);
173989};
173990
173991}
173992
173993
173994
173995
173996
173997
173998
173999
174000
174001
174002
174003
174004
174005
174006
174007
174008
174009
174010
174011
174012
174013
174014
174015
174016
174017namespace duckdb {
174018struct MapCastInfo;
174019struct MapCastNode;
174020struct DBConfig;
174021
174022typedef BoundCastInfo (*bind_cast_function_t)(BindCastInput &input, const LogicalType &source,
174023 const LogicalType &target);
174024typedef int64_t (*implicit_cast_cost_t)(
const LogicalType &from,
const LogicalType &to);
174025
174026struct GetCastFunctionInput {
174027 explicit GetCastFunctionInput(optional_ptr<ClientContext> context = nullptr) : context(context) {
174028 }
174029 explicit GetCastFunctionInput(ClientContext &context) : context(&context) {
174030 }
174031
174032 optional_ptr<ClientContext> context;
174033 optional_idx query_location;
174034};
174035
174036struct BindCastFunction {
174037 BindCastFunction(bind_cast_function_t function,
174038 unique_ptr<BindCastInfo> info = nullptr);
174039
174040 bind_cast_function_t function;
174041 unique_ptr<BindCastInfo> info;
174042};
174043
174044class CastFunctionSet {
174045public:
174046 CastFunctionSet();
174047 explicit CastFunctionSet(DBConfig &config);
174048
174049public:
174050 DUCKDB_API static CastFunctionSet &Get(ClientContext &context);
174051 DUCKDB_API static CastFunctionSet &Get(DatabaseInstance &db);
174052
174055 DUCKDB_API BoundCastInfo GetCastFunction(const LogicalType &source, const LogicalType &target,
174056 GetCastFunctionInput &input);
174059 DUCKDB_API
int64_t ImplicitCastCost(optional_ptr<ClientContext> context,
const LogicalType &source,
174060 const LogicalType &target);
174061 DUCKDB_API
static int64_t ImplicitCastCost(ClientContext &context,
const LogicalType &source,
174062 const LogicalType &target);
174063 DUCKDB_API
static int64_t ImplicitCastCost(DatabaseInstance &db,
const LogicalType &source,
174064 const LogicalType &target);
174066 DUCKDB_API void RegisterCastFunction(const LogicalType &source, const LogicalType &target, BoundCastInfo function,
174067 int64_t implicit_cast_cost = -1);
174068 DUCKDB_API void RegisterCastFunction(const LogicalType &source, const LogicalType &target,
174069 bind_cast_function_t bind, int64_t implicit_cast_cost = -1);
174070
174071private:
174072 optional_ptr<DBConfig> config;
174073 vector<BindCastFunction> bind_functions;
174075 optional_ptr<MapCastInfo> map_info;
174076
174077private:
174078 void RegisterCastFunction(const LogicalType &source, const LogicalType &target, MapCastNode node);
174079};
174080
174081}
174082
174083
174084
174085
174086
174087
174088
174089
174090
174091
174092
174093
174094
174095
174096
174097
174098
174099
174100
174101
174102
174103
174104
174105
174106
174107
174108
174109
174110
174111
174112
174113
174114
174115
174116
174117
174118
174119
174120
174121namespace duckdb {
174122
174123enum class PragmaType :
uint8_t { PRAGMA_STATEMENT, PRAGMA_CALL };
174124
174125struct PragmaInfo : public ParseInfo {
174126public:
174127 static constexpr const ParseInfoType
TYPE = ParseInfoType::PRAGMA_INFO;
174128
174129public:
174130 PragmaInfo() : ParseInfo(
TYPE) {
174131 }
174132
174134 string name;
174136 vector<unique_ptr<ParsedExpression>> parameters;
174138 case_insensitive_map_t<unique_ptr<ParsedExpression>> named_parameters;
174139
174140public:
174141 unique_ptr<PragmaInfo> Copy() const;
174142 string ToString() const;
174143
174144 void Serialize(Serializer &serializer) const override;
174145 static unique_ptr<ParseInfo> Deserialize(Deserializer &deserializer);
174146};
174147
174148}
174149
174150
174151
174152namespace duckdb {
174153class ClientContext;
174154
174156typedef string (*pragma_query_t)(ClientContext &context, const FunctionParameters ¶meters);
174158typedef void (*pragma_function_t)(ClientContext &context, const FunctionParameters ¶meters);
174159
174168class PragmaFunction : public SimpleNamedParameterFunction {
174169public:
174170
174171 DUCKDB_API static PragmaFunction PragmaCall(const string &name, pragma_query_t query, vector<LogicalType> arguments,
174172 LogicalType varargs = LogicalType::INVALID);
174173 DUCKDB_API static PragmaFunction PragmaCall(const string &name, pragma_function_t function,
174174 vector<LogicalType> arguments,
174175 LogicalType varargs = LogicalType::INVALID);
174176
174177 DUCKDB_API static PragmaFunction PragmaStatement(const string &name, pragma_query_t query);
174178 DUCKDB_API static PragmaFunction PragmaStatement(const string &name, pragma_function_t function);
174179
174180 DUCKDB_API string ToString() const override;
174181
174182public:
174183 PragmaType type;
174184
174187 named_parameter_type_map_t named_parameters;
174188
174189private:
174190 PragmaFunction(string name, PragmaType pragma_type, pragma_query_t query, pragma_function_t function,
174191 vector<LogicalType> arguments, LogicalType varargs);
174192};
174193
174194}
174195
174196
174197namespace duckdb {
174198
174199template <class T>
174200class FunctionSet {
174201public:
174202 explicit FunctionSet(string name) : name(std::move(name)) {
174203 }
174204
174206 string name;
174208 vector<T> functions;
174209
174210public:
174211 void AddFunction(T function) {
174212 functions.push_back(std::move(function));
174213 }
174215 return functions.size();
174216 }
174217 T GetFunctionByOffset(idx_t offset) {
174218 D_ASSERT(offset < functions.size());
174219 return functions[offset];
174220 }
174221 T &GetFunctionReferenceByOffset(idx_t offset) {
174222 D_ASSERT(offset < functions.size());
174223 return functions[offset];
174224 }
174225 bool MergeFunctionSet(FunctionSet<T> new_functions, bool override = false) {
174226 D_ASSERT(!new_functions.functions.empty());
174227 for (auto &new_func : new_functions.functions) {
174228 bool overwritten = false;
174229 for (auto &func : functions) {
174230 if (new_func.Equal(func)) {
174231
174232 if (override) {
174233
174234 overwritten = true;
174235 func = new_func;
174236 } else {
174237
174238 return false;
174239 }
174240 break;
174241 }
174242 }
174243 if (!overwritten) {
174244 functions.push_back(new_func);
174245 }
174246 }
174247 return true;
174248 }
174249};
174250
174251class ScalarFunctionSet : public FunctionSet<ScalarFunction> {
174252public:
174253 DUCKDB_API explicit ScalarFunctionSet();
174254 DUCKDB_API explicit ScalarFunctionSet(string name);
174255 DUCKDB_API explicit ScalarFunctionSet(ScalarFunction fun);
174256
174257 DUCKDB_API ScalarFunction GetFunctionByArguments(ClientContext &context, const vector<LogicalType> &arguments);
174258};
174259
174260class AggregateFunctionSet : public FunctionSet<AggregateFunction> {
174261public:
174262 DUCKDB_API explicit AggregateFunctionSet();
174263 DUCKDB_API explicit AggregateFunctionSet(string name);
174264 DUCKDB_API explicit AggregateFunctionSet(AggregateFunction fun);
174265
174266 DUCKDB_API AggregateFunction GetFunctionByArguments(ClientContext &context, const vector<LogicalType> &arguments);
174267};
174268
174269class TableFunctionSet : public FunctionSet<TableFunction> {
174270public:
174271 DUCKDB_API explicit TableFunctionSet(string name);
174272 DUCKDB_API explicit TableFunctionSet(TableFunction fun);
174273
174274 TableFunction GetFunctionByArguments(ClientContext &context, const vector<LogicalType> &arguments);
174275};
174276
174277class PragmaFunctionSet : public FunctionSet<PragmaFunction> {
174278public:
174279 DUCKDB_API explicit PragmaFunctionSet(string name);
174280 DUCKDB_API explicit PragmaFunctionSet(PragmaFunction fun);
174281};
174282
174283}
174284
174285
174286
174287
174288
174289
174290
174291
174292
174293
174294
174295
174296
174297
174298
174299
174300
174301
174302
174303
174304
174305
174306
174307
174308
174309
174310
174311
174312
174313
174314
174315
174316
174317
174318
174319
174320
174321
174322
174323
174324
174325
174326
174327
174328
174329#include <stack>
174330
174331namespace duckdb {
174332using std::stack;
174333}
174334
174335
174336
174337
174338
174339
174340
174341
174342
174343
174344
174345
174346
174347
174348
174349
174350namespace duckdb {
174351
174352class ParameterExpression;
174353class BoundParameterExpression;
174354
174355using bound_parameter_map_t = case_insensitive_map_t<shared_ptr<BoundParameterData>>;
174356
174357struct BoundParameterMap {
174358public:
174359 explicit BoundParameterMap(case_insensitive_map_t<BoundParameterData> ¶meter_data);
174360
174361public:
174362 LogicalType GetReturnType(const string &identifier);
174363
174364 bound_parameter_map_t *GetParametersPtr();
174365
174366 const bound_parameter_map_t &GetParameters();
174367
174368 const case_insensitive_map_t<BoundParameterData> &GetParameterData();
174369
174370 unique_ptr<BoundParameterExpression> BindParameterExpression(ParameterExpression &expr);
174371
174373 bool rebind = false;
174374
174375private:
174376 shared_ptr<BoundParameterData> CreateOrGetData(const string &identifier);
174377 void CreateNewParameter(const string &id, const shared_ptr<BoundParameterData> ¶m_data);
174378
174379private:
174380 bound_parameter_map_t parameters;
174381
174382 case_insensitive_map_t<BoundParameterData> ¶meter_data;
174383};
174384
174385}
174386
174387
174388
174389
174390
174391
174392namespace duckdb {
174393class ClientContext;
174394class Catalog;
174395class DatabaseInstance;
174396class CompressionInfo;
174397enum class ExpressionType :
uint8_t;
174398
174399struct SerializationData {
174400 struct CustomData {
174401 virtual ~CustomData() = default;
174402 };
174403
174404 stack<reference<ClientContext>> contexts;
174405 stack<reference<DatabaseInstance>> databases;
174406 stack<reference<Catalog>> catalogs;
174407 stack<idx_t> enums;
174408 stack<reference<bound_parameter_map_t>> parameter_data;
174409 stack<const_reference<LogicalType>> types;
174410 stack<const_reference<CompressionInfo>> compression_infos;
174411 duckdb::unordered_map<std::string, duckdb::stack<duckdb::reference<CustomData>>> customs;
174412
174413 template <class T>
174414 void Set(T entry) = delete;
174415
174416 template <class T>
174417 T Get() = delete;
174418
174419 template <class T>
174420 optional_ptr<T> TryGet() = delete;
174421
174422 template <class T>
174423 void Unset() = delete;
174424
174425 template <class T>
174426 inline void AssertNotEmpty(const stack<T> &e) {
174427 if (e.empty()) {
174428 throw InternalException("SerializationData - unexpected empty stack");
174429 }
174430 }
174431
174432 template <typename T>
174433 typename std::enable_if<std::is_base_of<CustomData, T>::value, T &>::type GetCustom() const {
174434 std::string type = T::GetType();
174435 auto iter = customs.find(type);
174436 if (iter == customs.end()) {
174437 throw duckdb::InternalException("SeserializationData - no stack for %s", type);
174438 }
174439 auto &stack = iter->second;
174440 if (stack.empty()) {
174441 throw duckdb::InternalException("SerializationData - unexpected empty stack for %s", type);
174442 }
174443 return dynamic_cast<T &
>(stack.top().
get());
174444 }
174445
174446 template <typename T>
174447 typename std::enable_if<std::is_base_of<CustomData, T>::value, void>::type SetCustom(T &data) {
174448 std::string type = T::GetType();
174449 auto iter = customs.find(type);
174450 if (iter == customs.end()) {
174451 iter = customs.emplace(type, duckdb::stack<duckdb::reference<CustomData>> {}).first;
174452 }
174453 auto &stack = iter->second;
174454 stack.push(data);
174455 }
174456};
174457
174458template <>
174459inline void SerializationData::Set(ExpressionType type) {
174460 enums.push(
idx_t(type));
174461}
174462
174463template <>
174464inline ExpressionType SerializationData::Get() {
174465 AssertNotEmpty(enums);
174466 return ExpressionType(enums.top());
174467}
174468
174469template <>
174470inline void SerializationData::Unset<ExpressionType>() {
174471 AssertNotEmpty(enums);
174472 enums.pop();
174473}
174474
174475template <>
174476inline void SerializationData::Set(LogicalOperatorType type) {
174477 enums.push(
idx_t(type));
174478}
174479
174480template <>
174481inline LogicalOperatorType SerializationData::Get() {
174482 AssertNotEmpty(enums);
174483 return LogicalOperatorType(enums.top());
174484}
174485
174486template <>
174487inline void SerializationData::Unset<LogicalOperatorType>() {
174488 AssertNotEmpty(enums);
174489 enums.pop();
174490}
174491
174492template <>
174493inline void SerializationData::Set(CompressionType type) {
174494 enums.push(
idx_t(type));
174495}
174496
174497template <>
174498inline CompressionType SerializationData::Get() {
174499 AssertNotEmpty(enums);
174500 return CompressionType(enums.top());
174501}
174502
174503template <>
174504inline void SerializationData::Unset<CompressionType>() {
174505 AssertNotEmpty(enums);
174506 enums.pop();
174507}
174508
174509template <>
174510inline void SerializationData::Set(CatalogType type) {
174511 enums.push(
idx_t(type));
174512}
174513
174514template <>
174515inline CatalogType SerializationData::Get() {
174516 AssertNotEmpty(enums);
174517 return CatalogType(enums.top());
174518}
174519
174520template <>
174521inline void SerializationData::Unset<CatalogType>() {
174522 AssertNotEmpty(enums);
174523 enums.pop();
174524}
174525
174526template <>
174527inline void SerializationData::Set(ClientContext &context) {
174528 contexts.emplace(context);
174529}
174530
174531template <>
174532inline ClientContext &SerializationData::Get() {
174533 AssertNotEmpty(contexts);
174534 return contexts.top();
174535}
174536
174537template <>
174538inline void SerializationData::Unset<ClientContext>() {
174539 AssertNotEmpty(contexts);
174540 contexts.pop();
174541}
174542
174543template <>
174544inline void SerializationData::Set(Catalog &catalog) {
174545 catalogs.emplace(catalog);
174546}
174547
174548template <>
174549inline Catalog &SerializationData::Get() {
174550 AssertNotEmpty(catalogs);
174551 return catalogs.top();
174552}
174553
174554template <>
174555inline optional_ptr<Catalog> SerializationData::TryGet() {
174556 return catalogs.empty() ? nullptr : &catalogs.top().get();
174557}
174558
174559template <>
174560inline void SerializationData::Unset<Catalog>() {
174561 AssertNotEmpty(catalogs);
174562 catalogs.pop();
174563}
174564template <>
174565inline void SerializationData::Set(DatabaseInstance &db) {
174566 databases.emplace(db);
174567}
174568
174569template <>
174570inline DatabaseInstance &SerializationData::Get() {
174571 AssertNotEmpty(databases);
174572 return databases.top();
174573}
174574
174575template <>
174576inline void SerializationData::Unset<DatabaseInstance>() {
174577 AssertNotEmpty(databases);
174578 databases.pop();
174579}
174580
174581template <>
174582inline void SerializationData::Set(bound_parameter_map_t &context) {
174583 parameter_data.emplace(context);
174584}
174585
174586template <>
174587inline bound_parameter_map_t &SerializationData::Get() {
174588 AssertNotEmpty(parameter_data);
174589 return parameter_data.top();
174590}
174591
174592template <>
174593inline void SerializationData::Unset<bound_parameter_map_t>() {
174594 AssertNotEmpty(parameter_data);
174595 parameter_data.pop();
174596}
174597
174598template <>
174599inline void SerializationData::Set(LogicalType &type) {
174600 types.emplace(type);
174601}
174602
174603template <>
174604inline void SerializationData::Unset<LogicalType>() {
174605 AssertNotEmpty(types);
174606 types.pop();
174607}
174608
174609template <>
174610inline void SerializationData::Set(const LogicalType &type) {
174611 types.emplace(type);
174612}
174613
174614template <>
174615inline const LogicalType &SerializationData::Get() {
174616 AssertNotEmpty(types);
174617 return types.top();
174618}
174619
174620template <>
174621inline void SerializationData::Unset<const LogicalType>() {
174622 AssertNotEmpty(types);
174623 types.pop();
174624}
174625
174626template <>
174627inline void SerializationData::Set(const CompressionInfo &compression_info) {
174628 compression_infos.emplace(compression_info);
174629}
174630
174631template <>
174632inline const CompressionInfo &SerializationData::Get() {
174633 AssertNotEmpty(compression_infos);
174634 return compression_infos.top();
174635}
174636
174637template <>
174638inline void SerializationData::Unset<const CompressionInfo>() {
174639 AssertNotEmpty(compression_infos);
174640 compression_infos.pop();
174641}
174642
174643}
174644
174645
174646#include <type_traits>
174647#include <cstdint>
174648#include <atomic>
174649
174650
174651
174652
174653
174654
174655
174656
174657
174658
174659
174660
174661
174662
174663
174664
174665
174666
174667
174668
174669
174670
174671
174672
174673namespace duckdb {
174674
174675template <class T>
174676class optionally_owned_ptr {
174677public:
174678 optionally_owned_ptr() {
174679 }
174680 optionally_owned_ptr(T *ptr_p) : ptr(ptr_p) {
174681 }
174682 optionally_owned_ptr(T &ref) : ptr(&ref) {
174683 }
174684 optionally_owned_ptr(unique_ptr<T> &&owned_p)
174685 : owned(std::move(owned_p)), ptr(owned) {
174686 }
174687 optionally_owned_ptr(shared_ptr<T> owned_p)
174688 : owned_shared(std::move(owned_p)), ptr(*owned_shared) {
174689 }
174690
174691 optionally_owned_ptr(optionally_owned_ptr &&other) noexcept
174692 : owned(std::move(other.owned)), owned_shared(std::move(other.owned_shared)), ptr(other.ptr) {
174693 other.ptr = nullptr;
174694 }
174695
174696 optionally_owned_ptr(const optionally_owned_ptr &other) = delete;
174697
174698 operator bool() const {
174699 return ptr;
174700 }
174702 return *ptr;
174703 }
174705 return *ptr;
174706 }
174707 T *operator->() {
174708 return ptr.get();
174709 }
174710 const T *operator->() const {
174711 return ptr.get();
174712 }
174714 return ptr.get();
174715 }
174716 const T *
get()
const {
174717 return ptr.get();
174718 }
174719 bool is_owned() const {
174720 return owned != nullptr || owned_shared != nullptr;
174721 }
174722 const unique_ptr<T> &get_owned_unique() const {
174723 return owned;
174724 }
174725 const shared_ptr<T> &get_owned_shared() const {
174726 return owned_shared;
174727 }
174728
174729 T *get_mutable() const {
174730 return ptr.get();
174731 }
174732
174733 optionally_owned_ptr<T> &
operator=(T &ref) {
174734 owned = nullptr;
174735 owned_shared = nullptr;
174736 ptr = optional_ptr<T>(ref);
174737 return *this;
174738 }
174739 optionally_owned_ptr<T> &
operator=(T *ref) {
174740 owned = nullptr;
174741 owned_shared = nullptr;
174742 ptr = optional_ptr<T>(ref);
174743 return *this;
174744 }
174745
174746 bool operator==(
const optionally_owned_ptr<T> &rhs)
const {
174747 if (owned != rhs.owned) {
174748 return false;
174749 }
174750 if (owned_shared != rhs.owned_shared) {
174751 return false;
174752 }
174753 return ptr == rhs.ptr;
174754 }
174755
174756 bool operator!=(
const optionally_owned_ptr<T> &rhs)
const {
174757 return !(*this == rhs);
174758 }
174759
174760private:
174761 unique_ptr<T> owned;
174762 shared_ptr<T> owned_shared;
174763 optional_ptr<T> ptr;
174764};
174765
174766}
174767
174768
174769
174770
174771namespace duckdb {
174772
174773class Serializer;
174774class Deserializer;
174775
174777const field_id_t MESSAGE_TERMINATOR_FIELD_ID = 0xFFFF;
174778
174779
174780template <class...>
174781using void_t = void;
174782
174783
174784
174785template <typename T, typename = T>
174786struct has_serialize : std::false_type {};
174787
174788template <typename T>
174789struct has_serialize<
174790 T, typename std::enable_if<
174791 std::is_same<decltype(std::declval<T>().Serialize(std::declval<Serializer &>())), void>::value, T>::type>
174792 : std::true_type {};
174793
174794template <typename T, typename = T>
174795struct has_deserialize : std::false_type {};
174796
174797
174798template <typename T>
174799struct has_deserialize<
174800 T, typename std::enable_if<std::is_same<decltype(T::Deserialize), unique_ptr<T>(Deserializer &)>::value, T>::type>
174801 : std::true_type {};
174802
174803
174804template <typename T>
174805struct has_deserialize<
174806 T, typename std::enable_if<std::is_same<decltype(T::Deserialize), shared_ptr<T>(Deserializer &)>::value, T>::type>
174807 : std::true_type {};
174808
174809
174810template <typename T>
174811struct has_deserialize<
174812 T,
174813 typename std::enable_if<std::is_same<decltype(T::Deserialize), std::shared_ptr<T>(Deserializer &)>::value, T>::type>
174814 : std::true_type {};
174815
174816
174817template <typename T>
174818struct has_deserialize<
174819 T, typename std::enable_if<std::is_same<decltype(T::Deserialize), T(Deserializer &)>::value, T>::type>
174820 : std::true_type {};
174821
174822
174823template <typename T>
174824struct is_vector : std::false_type {};
174825template <typename T>
174826struct is_vector<typename duckdb::vector<T>> : std::true_type {
174827 typedef T ELEMENT_TYPE;
174828};
174829
174830template <typename T>
174831struct is_unsafe_vector : std::false_type {};
174832template <typename T>
174833struct is_unsafe_vector<typename duckdb::unsafe_vector<T>> : std::true_type {
174834 typedef T ELEMENT_TYPE;
174835};
174836
174837
174838template <typename T>
174839struct is_unordered_map : std::false_type {};
174840template <typename... Args>
174841struct is_unordered_map<typename duckdb::unordered_map<Args...>> : std::true_type {
174842 typedef typename std::tuple_element<0, std::tuple<Args...>>::type KEY_TYPE;
174843 typedef typename std::tuple_element<1, std::tuple<Args...>>::type VALUE_TYPE;
174844 typedef typename std::tuple_element<2, std::tuple<Args...>>::type HASH_TYPE;
174845 typedef typename std::tuple_element<3, std::tuple<Args...>>::type EQUAL_TYPE;
174846};
174847
174848template <typename T>
174849struct is_map : std::false_type {};
174850template <typename... Args>
174851struct is_map<typename duckdb::map<Args...>> : std::true_type {
174852 typedef typename std::tuple_element<0, std::tuple<Args...>>::type KEY_TYPE;
174853 typedef typename std::tuple_element<1, std::tuple<Args...>>::type VALUE_TYPE;
174854 typedef typename std::tuple_element<2, std::tuple<Args...>>::type HASH_TYPE;
174855 typedef typename std::tuple_element<3, std::tuple<Args...>>::type EQUAL_TYPE;
174856};
174857
174858template <typename T>
174859struct is_insertion_preserving_map : std::false_type {};
174860template <typename... Args>
174861struct is_insertion_preserving_map<typename duckdb::InsertionOrderPreservingMap<Args...>> : std::true_type {
174862 typedef typename std::tuple_element<0, std::tuple<Args...>>::type VALUE_TYPE;
174863};
174864
174865template <typename T>
174866struct is_queue : std::false_type {};
174867template <typename T>
174868struct is_queue<typename std::priority_queue<T>> : std::true_type {
174869 typedef T ELEMENT_TYPE;
174870};
174871
174872template <typename T>
174873struct is_unique_ptr : std::false_type {};
174874template <typename T>
174875struct is_unique_ptr<unique_ptr<T>> : std::true_type {
174876 typedef T ELEMENT_TYPE;
174877};
174878
174879template <typename T>
174880struct is_shared_ptr : std::false_type {};
174881template <typename T>
174882struct is_shared_ptr<shared_ptr<T>> : std::true_type {
174883 typedef T ELEMENT_TYPE;
174884};
174885template <typename T>
174886struct is_shared_ptr<std::shared_ptr<T>> : std::true_type {
174887 typedef T ELEMENT_TYPE;
174888};
174889
174890template <typename T>
174891struct is_optional_ptr : std::false_type {};
174892template <typename T>
174893struct is_optional_ptr<optional_ptr<T>> : std::true_type {
174894 typedef T ELEMENT_TYPE;
174895};
174896
174897template <typename T>
174898struct is_optionally_owned_ptr : std::false_type {};
174899template <typename T>
174900struct is_optionally_owned_ptr<optionally_owned_ptr<T>> : std::true_type {
174901 typedef T ELEMENT_TYPE;
174902};
174903
174904template <typename T>
174905struct is_pair : std::false_type {};
174906template <typename T, typename U>
174907struct is_pair<std::pair<T, U>> : std::true_type {
174908 typedef T FIRST_TYPE;
174909 typedef U SECOND_TYPE;
174910};
174911
174912template <typename T>
174913struct is_unordered_set : std::false_type {};
174914template <typename... Args>
174915struct is_unordered_set<duckdb::unordered_set<Args...>> : std::true_type {
174916 typedef typename std::tuple_element<0, std::tuple<Args...>>::type ELEMENT_TYPE;
174917 typedef typename std::tuple_element<1, std::tuple<Args...>>::type HASH_TYPE;
174918 typedef typename std::tuple_element<2, std::tuple<Args...>>::type EQUAL_TYPE;
174919};
174920
174921template <typename T>
174922struct is_set : std::false_type {};
174923template <typename... Args>
174924struct is_set<duckdb::set<Args...>> : std::true_type {
174925 typedef typename std::tuple_element<0, std::tuple<Args...>>::type ELEMENT_TYPE;
174926 typedef typename std::tuple_element<1, std::tuple<Args...>>::type HASH_TYPE;
174927 typedef typename std::tuple_element<2, std::tuple<Args...>>::type EQUAL_TYPE;
174928};
174929
174930template <typename T>
174931struct is_atomic : std::false_type {};
174932
174933template <typename T>
174934struct is_atomic<std::atomic<T>> : std::true_type {
174936};
174937
174938
174939
174940struct SerializationDefaultValue {
174941 template <typename T = void>
174942 static inline typename std::enable_if<is_atomic<T>::value, T>::type GetDefault() {
174943 using INNER = typename is_atomic<T>::TYPE;
174944 return static_cast<T>(GetDefault<INNER>());
174945 }
174946
174947 template <typename T = void>
174948 static inline bool IsDefault(const typename std::enable_if<is_atomic<T>::value, T>::type &value) {
174949 using INNER = typename is_atomic<T>::TYPE;
174950 return value == GetDefault<INNER>();
174951 }
174952
174953 template <typename T = void>
174954 static inline typename std::enable_if<std::is_arithmetic<T>::value, T>::type GetDefault() {
174955 return static_cast<T>(0);
174956 }
174957
174958 template <typename T = void>
174959 static inline bool IsDefault(const typename std::enable_if<std::is_arithmetic<T>::value, T>::type &value) {
174960 return value == static_cast<T>(0);
174961 }
174962
174963 template <typename T = void>
174964 static inline typename std::enable_if<is_unique_ptr<T>::value, T>::type GetDefault() {
174965 return T();
174966 }
174967
174968 template <typename T = void>
174969 static inline bool IsDefault(const typename std::enable_if<is_unique_ptr<T>::value, T>::type &value) {
174970 return !value;
174971 }
174972
174973 template <typename T = void>
174974 static inline typename std::enable_if<is_optional_ptr<T>::value, T>::type GetDefault() {
174975 return T();
174976 }
174977
174978 template <typename T = void>
174979 static inline bool IsDefault(const typename std::enable_if<is_optional_ptr<T>::value, T>::type &value) {
174980 return !value;
174981 }
174982
174983 template <typename T = void>
174984 static inline typename std::enable_if<is_optionally_owned_ptr<T>::value, T>::type GetDefault() {
174985 return T();
174986 }
174987
174988 template <typename T = void>
174989 static inline bool IsDefault(const typename std::enable_if<is_optionally_owned_ptr<T>::value, T>::type &value) {
174990 return !value;
174991 }
174992
174993 template <typename T = void>
174994 static inline typename std::enable_if<is_shared_ptr<T>::value, T>::type GetDefault() {
174995 return T();
174996 }
174997
174998 template <typename T = void>
174999 static inline bool IsDefault(const typename std::enable_if<is_shared_ptr<T>::value, T>::type &value) {
175000 return !value;
175001 }
175002
175003 template <typename T = void>
175004 static inline typename std::enable_if<is_vector<T>::value, T>::type GetDefault() {
175005 return T();
175006 }
175007
175008 template <typename T = void>
175009 static inline bool IsDefault(const typename std::enable_if<is_vector<T>::value, T>::type &value) {
175010 return value.empty();
175011 }
175012
175013 template <typename T = void>
175014 static inline typename std::enable_if<is_queue<T>::value, T>::type GetDefault() {
175015 return T();
175016 }
175017
175018 template <typename T = void>
175019 static inline bool IsDefault(const typename std::enable_if<is_queue<T>::value, T>::type &value) {
175020 return value.empty();
175021 }
175022
175023 template <typename T = void>
175024 static inline typename std::enable_if<is_unsafe_vector<T>::value, T>::type GetDefault() {
175025 return T();
175026 }
175027
175028 template <typename T = void>
175029 static inline bool IsDefault(const typename std::enable_if<is_unsafe_vector<T>::value, T>::type &value) {
175030 return value.empty();
175031 }
175032
175033 template <typename T = void>
175034 static inline typename std::enable_if<is_unordered_set<T>::value, T>::type GetDefault() {
175035 return T();
175036 }
175037
175038 template <typename T = void>
175039 static inline bool IsDefault(const typename std::enable_if<is_unordered_set<T>::value, T>::type &value) {
175040 return value.empty();
175041 }
175042
175043 template <typename T = void>
175044 static inline typename std::enable_if<is_unordered_map<T>::value, T>::type GetDefault() {
175045 return T();
175046 }
175047
175048 template <typename T = void>
175049 static inline bool IsDefault(const typename std::enable_if<is_unordered_map<T>::value, T>::type &value) {
175050 return value.empty();
175051 }
175052
175053 template <typename T = void>
175054 static inline typename std::enable_if<is_map<T>::value, T>::type GetDefault() {
175055 return T();
175056 }
175057
175058 template <typename T = void>
175059 static inline bool IsDefault(const typename std::enable_if<is_map<T>::value, T>::type &value) {
175060 return value.empty();
175061 }
175062
175063 template <typename T = void>
175064 static inline typename std::enable_if<is_insertion_preserving_map<T>::value, T>::type GetDefault() {
175065 return T();
175066 }
175067
175068 template <typename T = void>
175069 static inline bool IsDefault(const typename std::enable_if<is_insertion_preserving_map<T>::value, T>::type &value) {
175070 return value.empty();
175071 }
175072
175073 template <typename T = void>
175074 static inline typename std::enable_if<std::is_same<T, string>::value, T>::type GetDefault() {
175075 return T();
175076 }
175077
175078 template <typename T = void>
175079 static inline bool IsDefault(const typename std::enable_if<std::is_same<T, string>::value, T>::type &value) {
175080 return value.empty();
175081 }
175082
175083 template <typename T = void>
175084 static inline typename std::enable_if<std::is_same<T, optional_idx>::value, T>::type GetDefault() {
175085 return optional_idx();
175086 }
175087
175088 template <typename T = void>
175089 static inline bool IsDefault(const typename std::enable_if<std::is_same<T, optional_idx>::value, T>::type &value) {
175090 return !value.IsValid();
175091 }
175092};
175093
175094}
175095
175096
175097
175098
175099
175100
175101
175102
175103
175104
175105
175106
175107
175108
175109
175110
175111
175112
175113
175114
175115
175116
175117
175118
175119
175120
175121
175122
175123
175124
175125
175126
175127
175128
175129
175130
175131
175132
175133
175134
175135
175136
175137
175138
175139
175140
175141
175142
175143
175144
175145
175146
175147
175148
175149
175150
175151namespace duckdb {
175152
175153struct DBConfig;
175154
175156struct CSVEncoderBuffer {
175157 CSVEncoderBuffer() : encoded_buffer_size(0) {};
175158 void Initialize(idx_t encoded_buffer_size);
175159
175160 char *
Ptr()
const;
175161
175162 idx_t GetCapacity()
const;
175163
175164 idx_t GetSize()
const;
175165
175166 void SetSize(const idx_t buffer_size);
175167
175168 bool HasDataToRead() const;
175169
175170 void Reset();
175171 idx_t cur_pos = 0;
175173 idx_t actual_encoded_buffer_size = 0;
175175 bool last_buffer = false;
175176
175177private:
175179 duckdb::unique_ptr<char[]> encoded_buffer;
175181 idx_t encoded_buffer_size;
175182};
175183
175184class CSVEncoder {
175185public:
175187 CSVEncoder(ClientContext &context, const string &encoding_name, idx_t buffer_size);
175189 idx_t Encode(FileHandle &file_handle_input,
char *output_buffer,
const idx_t decoded_buffer_size);
175190 string encoding_name;
175191
175192private:
175193 QueryContext context;
175194
175196 CSVEncoderBuffer encoded_buffer;
175198 CSVEncoderBuffer remaining_bytes_buffer;
175200 optional_ptr<EncodingFunction> encoding_function;
175202 char pass_on_byte;
175203 bool has_pass_on_byte = false;
175204};
175205}
175206
175207
175208
175209namespace duckdb {
175210class Allocator;
175211class FileSystem;
175212struct CSVReaderOptions;
175213
175214class CSVFileHandle {
175215public:
175216 CSVFileHandle(ClientContext &context, unique_ptr<FileHandle> file_handle_p, const OpenFileInfo &file,
175217 const CSVReaderOptions &options);
175218
175219 mutex main_mutex;
175220
175221 bool CanSeek() const;
175222 void Seek(idx_t position) const;
175223 bool OnDiskFile() const;
175224 bool IsPipe() const;
175225
175226 void Reset();
175227
175228 idx_t FileSize()
const;
175229
175230 bool FinishedReading() const;
175231
175232 idx_t Read(
void *buffer, idx_t nr_bytes);
175233
175234 string ReadLine();
175235
175236 string GetFilePath();
175237
175238 static unique_ptr<FileHandle> OpenFileHandle(FileSystem &fs, Allocator &allocator, const OpenFileInfo &file,
175239 FileCompressionType compression);
175240 static unique_ptr<CSVFileHandle> OpenFile(ClientContext &context, const OpenFileInfo &file,
175241 const CSVReaderOptions &options);
175242 FileCompressionType compression_type;
175243
175244 double GetProgress() const;
175245
175246private:
175247 QueryContext context;
175248 unique_ptr<FileHandle> file_handle;
175249 CSVEncoder encoder;
175250 const OpenFileInfo file;
175251 bool can_seek = false;
175252 bool on_disk_file = false;
175253 bool is_pipe = false;
175254 idx_t uncompressed_bytes_read = 0;
175255
175256 idx_t file_size = 0;
175257
175258 idx_t requested_bytes = 0;
175260 bool finished = false;
175261};
175262
175263}
175264
175265
175266
175267
175268
175269
175270
175271
175272
175273
175274
175275
175276
175277
175278
175279
175280
175281
175282
175283
175284
175285
175286
175287namespace duckdb {
175288
175289enum class MemoryTag :
uint8_t {
175290 BASE_TABLE = 0,
175291 HASH_TABLE = 1,
175292 PARQUET_READER = 2,
175293 CSV_READER = 3,
175294 ORDER_BY = 4,
175295 ART_INDEX = 5,
175296 COLUMN_DATA = 6,
175297 METADATA = 7,
175298 OVERFLOW_STRINGS = 8,
175299 IN_MEMORY_TABLE = 9,
175300 ALLOCATOR = 10,
175301 EXTENSION = 11,
175302 TRANSACTION = 12,
175303 EXTERNAL_FILE_CACHE = 13,
175304 WINDOW = 14,
175305 OBJECT_CACHE = 15,
175306
175307 UNKNOWN = 16,
175308};
175309
175310static constexpr const idx_t MEMORY_TAG_COUNT =
static_cast<idx_t>(MemoryTag::UNKNOWN);
175311
175312}
175313
175314
175315
175316
175317
175318
175319
175320
175321
175322
175323
175324
175325
175326
175327
175328
175329
175330
175331
175332
175333namespace duckdb {
175334
175335class BlockHandle;
175336class BufferHandle;
175337class BufferManager;
175338class ClientContext;
175339class DatabaseInstance;
175340class MetadataManager;
175341
175342enum class ConvertToPersistentMode { DESTRUCTIVE, THREAD_SAFE };
175343
175346class BlockManager {
175347public:
175348 BlockManager() = delete;
175349 BlockManager(BufferManager &buffer_manager, const optional_idx block_alloc_size_p,
175350 const optional_idx block_header_size_p);
175351 virtual ~BlockManager() = default;
175352
175354 BufferManager &buffer_manager;
175355
175356public:
175357 BufferManager &GetBufferManager() const {
175358 return buffer_manager;
175359 }
175361 virtual unique_ptr<Block> ConvertBlock(block_id_t block_id, FileBuffer &source_buffer) = 0;
175362 virtual unique_ptr<Block> CreateBlock(block_id_t block_id, FileBuffer *source_buffer) = 0;
175364 virtual block_id_t GetFreeBlockId() = 0;
175365 virtual block_id_t PeekFreeBlockId() = 0;
175367
175368 virtual block_id_t GetFreeBlockIdForCheckpoint() = 0;
175369
175371 virtual bool IsRootBlock(MetaBlockPointer root) = 0;
175373 virtual void MarkBlockAsCheckpointed(block_id_t block_id) = 0;
175375 virtual void MarkBlockAsUsed(block_id_t block_id) = 0;
175378 virtual void MarkBlockAsModified(block_id_t block_id) = 0;
175381 virtual void IncreaseBlockReferenceCount(block_id_t block_id) = 0;
175383 virtual idx_t GetMetaBlock() = 0;
175385 virtual void Read(QueryContext context, Block &block) = 0;
175386
175388 virtual void ReadBlocks(FileBuffer &buffer, block_id_t start_block, idx_t block_count) = 0;
175390 virtual void Write(FileBuffer &block, block_id_t block_id) = 0;
175391 virtual void Write(QueryContext context, FileBuffer &block, block_id_t block_id);
175393 void Write(Block &block) {
175394 Write(block, block.id);
175395 }
175397 virtual void WriteHeader(QueryContext context, DatabaseHeader header) = 0;
175398
175400 virtual idx_t TotalBlocks() = 0;
175402 virtual idx_t FreeBlocks() = 0;
175404 virtual bool IsRemote() {
175405 return false;
175406 }
175408 virtual bool InMemory() = 0;
175410 virtual bool Prefetch() {
175411 return false;
175412 }
175413
175415 virtual void FileSync() = 0;
175417 virtual void Truncate();
175418
175420 shared_ptr<BlockHandle> RegisterBlock(block_id_t block_id);
175425 shared_ptr<BlockHandle> ConvertToPersistent(QueryContext context, block_id_t block_id,
175426 shared_ptr<BlockHandle> old_block, BufferHandle old_handle,
175427 ConvertToPersistentMode mode = ConvertToPersistentMode::DESTRUCTIVE);
175428 shared_ptr<BlockHandle> ConvertToPersistent(QueryContext context, block_id_t block_id,
175429 shared_ptr<BlockHandle> old_block,
175430 ConvertToPersistentMode mode = ConvertToPersistentMode::DESTRUCTIVE);
175431
175432 void UnregisterPersistentBlock(BlockHandle &block);
175434 virtual void UnregisterBlock(block_id_t id);
175435
175437 MetadataManager &GetMetadataManager();
175438
175440 idx_t GetBlockAllocSize()
const {
175441 return block_alloc_size.GetIndex();
175442 }
175444 inline optional_idx GetOptionalBlockAllocSize() const {
175445 return block_alloc_size;
175446 }
175448 inline optional_idx GetOptionalBlockHeaderSize() const {
175449 return block_header_size;
175450 }
175452 idx_t GetBlockHeaderSize()
const {
175453 if (!block_header_size.IsValid()) {
175454 return Storage::DEFAULT_BLOCK_HEADER_SIZE;
175455 }
175456 return block_header_size.GetIndex();
175457 }
175459 idx_t GetBlockSize()
const {
175460 return block_alloc_size.GetIndex() - block_header_size.GetIndex();
175461 }
175465 void SetBlockAllocSize(const optional_idx block_alloc_size_p) {
175466 if (block_alloc_size.IsValid()) {
175467 throw InternalException("the block allocation size must be set once");
175468 }
175469 block_alloc_size = block_alloc_size_p.GetIndex();
175470 }
175474 void SetBlockHeaderSize(const optional_idx block_header_size_p) {
175475 if (block_header_size.IsValid()) {
175476 throw InternalException("block header size already set, must be set once");
175477 }
175478 block_header_size = block_header_size_p.GetIndex();
175479 }
175481 virtual void VerifyBlocks(const unordered_map<block_id_t, idx_t> &block_usage_count) {
175482 }
175483
175484protected:
175485 bool BlockIsRegistered(block_id_t block_id);
175486 shared_ptr<BlockHandle> TryGetBlock(block_id_t block_id);
175487
175488public:
175489 template <class TARGET>
175490 TARGET &Cast() {
175491 DynamicCastCheck<TARGET>(this);
175492 return reinterpret_cast<TARGET &>(*this);
175493 }
175494 template <class TARGET>
175495 const TARGET &Cast() const {
175496 DynamicCastCheck<TARGET>(this);
175497 return reinterpret_cast<const TARGET &>(*this);
175498 }
175499
175500protected:
175503 bool in_destruction = false;
175504
175505private:
175507 mutex blocks_lock;
175509 unordered_map<block_id_t, weak_ptr<BlockHandle>> blocks;
175511 unique_ptr<MetadataManager> metadata_manager;
175515 optional_idx block_alloc_size;
175519 optional_idx block_header_size;
175520};
175521
175522struct BlockIdVisitor {
175523 virtual ~BlockIdVisitor() = default;
175524
175525 virtual void Visit(block_id_t block_id) = 0;
175526};
175527
175528}
175529
175530
175531
175532
175533
175534
175535
175536
175537
175538
175539
175540
175541
175542
175543
175544namespace duckdb {
175545
175546struct MemoryInformation {
175547 MemoryTag tag;
175549 idx_t evicted_data;
175550};
175551
175552struct TemporaryFileInformation {
175553 string path;
175555};
175556
175557struct CachedFileInformation {
175558 string path;
175561 bool loaded;
175562};
175563
175564}
175565
175566
175567
175568namespace duckdb {
175569class BlockMemory;
175570class Allocator;
175571class BufferPool;
175572class TemporaryMemoryManager;
175573
175574class BufferManager {
175575 friend class BufferHandle;
175576 friend class BlockHandle;
175577 friend class BlockManager;
175578
175579public:
175580 BufferManager() {
175581 }
175582 virtual ~BufferManager() {
175583 }
175584
175585public:
175586 DUCKDB_API static BufferManager &GetBufferManager(DatabaseInstance &db);
175587 DUCKDB_API static const BufferManager &GetBufferManager(const DatabaseInstance &db);
175588 DUCKDB_API static BufferManager &GetBufferManager(ClientContext &context);
175589 DUCKDB_API static const BufferManager &GetBufferManager(const ClientContext &context);
175590 DUCKDB_API static BufferManager &GetBufferManager(AttachedDatabase &db);
175591 DUCKDB_API
static idx_t GetAllocSize(
const idx_t alloc_size);
175592
175593public:
175595 virtual shared_ptr<BlockHandle> AllocateTemporaryMemory(MemoryTag tag, idx_t block_size,
175596 bool can_destroy = true) = 0;
175600 virtual shared_ptr<BlockHandle> AllocateMemory(MemoryTag tag, BlockManager *block_manager,
175601 bool can_destroy = true) = 0;
175603 virtual BufferHandle Allocate(MemoryTag tag, idx_t block_size, bool can_destroy = true) = 0;
175605 virtual BufferHandle Allocate(MemoryTag tag, BlockManager *block_manager, bool can_destroy = true) = 0;
175607 virtual BufferHandle Pin(shared_ptr<BlockHandle> &handle) = 0;
175608 virtual BufferHandle Pin(const QueryContext &context, shared_ptr<BlockHandle> &handle) = 0;
175611 virtual void Prefetch(vector<shared_ptr<BlockHandle>> &handles) = 0;
175613 virtual void Unpin(shared_ptr<BlockHandle> &handle) = 0;
175614
175616 virtual idx_t GetUsedMemory()
const = 0;
175618 virtual idx_t GetMaxMemory()
const = 0;
175620 virtual idx_t GetUsedSwap()
const = 0;
175622 virtual optional_idx GetMaxSwap() const = 0;
175624 virtual idx_t GetBlockAllocSize()
const = 0;
175626 virtual idx_t GetBlockSize()
const = 0;
175628 virtual idx_t GetQueryMaxMemory()
const = 0;
175629
175631 virtual shared_ptr<BlockHandle> RegisterTransientMemory(const idx_t size, BlockManager &block_manager);
175633 virtual shared_ptr<BlockHandle> RegisterSmallMemory(const idx_t size);
175635 virtual shared_ptr<BlockHandle> RegisterSmallMemory(MemoryTag tag, const idx_t size);
175636
175638 virtual DUCKDB_API Allocator &GetBufferAllocator();
175640 virtual DUCKDB_API void ReserveMemory(idx_t size);
175642 virtual DUCKDB_API void FreeReservedMemory(idx_t size);
175644 virtual vector<MemoryInformation> GetMemoryUsageInfo() const = 0;
175647 virtual void SetMemoryLimit(idx_t limit = (idx_t)-1);
175649 virtual void SetSwapLimit(optional_idx limit = optional_idx());
175650
175652 virtual BlockManager &GetTemporaryBlockManager() = 0;
175654 virtual vector<TemporaryFileInformation> GetTemporaryFiles();
175656 virtual const string &GetTemporaryDirectory() const;
175658 virtual void SetTemporaryDirectory(const string &new_dir);
175660 virtual bool HasTemporaryDirectory() const;
175662 virtual bool HasFilesInTemporaryDirectory() const;
175663
175665 virtual unique_ptr<FileBuffer> ConstructManagedBuffer(idx_t size, idx_t block_header_size,
175666 unique_ptr<FileBuffer> &&source,
175667 FileBufferType type = FileBufferType::MANAGED_BUFFER);
175669 virtual BufferPool &GetBufferPool() const;
175671 virtual const DatabaseInstance &GetDatabase() const = 0;
175673 virtual DatabaseInstance &GetDatabase() = 0;
175675 virtual TemporaryMemoryManager &GetTemporaryMemoryManager();
175676
175678 virtual void PurgeQueue(const BlockHandle &handle) = 0;
175680 virtual void AddToEvictionQueue(shared_ptr<BlockHandle> &handle);
175682 virtual void WriteTemporaryBuffer(MemoryTag tag, block_id_t block_id, FileBuffer &buffer);
175684 virtual unique_ptr<FileBuffer> ReadTemporaryBuffer(QueryContext context, MemoryTag tag, BlockHandle &block,
175685 unique_ptr<FileBuffer> buffer);
175687 virtual void DeleteTemporaryFile(BlockMemory &memory);
175688};
175689
175690}
175691
175692
175693
175694
175695
175696
175697
175698
175699
175700
175701
175702
175703
175704
175705
175706
175707
175708
175709
175710
175711
175712
175713
175714
175715
175716namespace duckdb {
175717
175719 BLOCK = 0,
175722};
175723
175724}
175725
175726
175727
175728
175729
175730
175731
175732
175733
175734
175735
175736
175737
175738
175739
175740
175741
175742
175743namespace duckdb {
175744
175745enum class BlockState :
uint8_t { BLOCK_UNLOADED = 0, BLOCK_LOADED = 1 };
175746
175747
175748class BufferPool;
175749
175750struct BufferPoolReservation {
175751 MemoryTag tag;
175753 BufferPool &pool;
175754
175755 BufferPoolReservation(MemoryTag tag, BufferPool &pool);
175756 BufferPoolReservation(const BufferPoolReservation &) = delete;
175757 BufferPoolReservation &
operator=(
const BufferPoolReservation &) =
delete;
175758
175759 BufferPoolReservation(BufferPoolReservation &&) noexcept;
175760 BufferPoolReservation &operator=(BufferPoolReservation &&) noexcept;
175761
175762 virtual ~BufferPoolReservation();
175763
175764 void Resize(idx_t new_size);
175765 void Merge(BufferPoolReservation src);
175766};
175767
175768struct TempBufferPoolReservation : BufferPoolReservation {
175769 TempBufferPoolReservation(MemoryTag tag, BufferPool &pool, idx_t size) : BufferPoolReservation(tag, pool) {
175770 Resize(size);
175771 }
175772 TempBufferPoolReservation(TempBufferPoolReservation &&) = default;
175773 ~TempBufferPoolReservation() override {
175774 Resize(0);
175775 }
175776};
175777
175778}
175779
175780
175781
175782namespace duckdb {
175783
175784
175785class BlockManager;
175786class BufferHandle;
175787class BufferManager;
175788class DatabaseInstance;
175789class BlockHandle;
175790
175791using BlockLock = unique_lock<mutex>;
175792
175793class BlockMemory : public enable_shared_from_this<BlockMemory> {
175794public:
175795 BlockMemory(BufferManager &buffer_manager, block_id_t block_id_p, MemoryTag tag_p, idx_t block_alloc_size);
175796 BlockMemory(BufferManager &buffer_manager, block_id_t block_id_p, MemoryTag tag_p, unique_ptr<FileBuffer> buffer_p,
175797 DestroyBufferUpon destroy_buffer_upon_p, idx_t size_p, BufferPoolReservation &&reservation);
175798 ~BlockMemory();
175799
175800public:
175802 const BufferManager &GetBufferManager() const {
175803 return buffer_manager;
175804 }
175806 BufferManager &GetBufferManager() {
175807 return buffer_manager;
175808 }
175810 block_id_t BlockId() const {
175811 return block_id;
175812 }
175814 BlockLock GetLock() {
175815 return BlockLock(lock);
175816 }
175818 void VerifyMutex(BlockLock &l) const {
175819 D_ASSERT(l.owns_lock());
175820 D_ASSERT(l.mutex() == &lock);
175821 }
175823 BlockState GetState() const {
175824 return state;
175825 }
175827 void SetState(BlockState state_p) {
175828 state = state_p;
175829 }
175831 bool IsUnloaded() const {
175832 return state == BlockState::BLOCK_UNLOADED;
175833 }
175835 int32_t GetReaders()
const {
175836 return readers;
175837 }
175839 int32_t IncrementReaders() {
175840 return ++readers;
175841 }
175843 int32_t DecrementReaders() {
175844 return --readers;
175845 }
175847 void SetReaders(int32_t n) {
175848 readers = n;
175849 }
175851 MemoryTag GetMemoryTag() const {
175852 return tag;
175853 }
175855 FileBufferType GetBufferType() const {
175856 return buffer_type;
175857 }
175859 unique_ptr<FileBuffer> &GetBuffer(BlockLock &l) {
175860 VerifyMutex(l);
175861 return GetBuffer();
175862 }
175864 unique_ptr<FileBuffer> &GetBuffer() {
175865 return buffer;
175866 }
175868 void SetBuffer(unique_ptr<FileBuffer> buffer_p) {
175869 buffer = std::move(buffer_p);
175870 }
175872 idx_t GetEvictionSequenceNumber()
const {
175873 return eviction_seq_num;
175874 }
175876 idx_t NextEvictionSequenceNumber() {
175877 return ++eviction_seq_num;
175878 }
175880 int64_t GetLRUTimestamp()
const {
175881 return lru_timestamp_msec;
175882 }
175884 void SetLRUTimestamp(int64_t timestamp_msec) {
175885 lru_timestamp_msec = timestamp_msec;
175886 }
175888 void SetDestroyBufferUpon(DestroyBufferUpon destroy_buffer_upon_p) {
175889 destroy_buffer_upon = destroy_buffer_upon_p;
175890 }
175892 bool MustAddToEvictionQueue() const {
175893 return destroy_buffer_upon != DestroyBufferUpon::UNPIN;
175894 }
175896 bool MustWriteToTemporaryFile() const {
175897 return destroy_buffer_upon == DestroyBufferUpon::BLOCK;
175898 }
175900 idx_t GetMemoryUsage()
const {
175901 return memory_usage;
175902 }
175904 void SetMemoryUsage(idx_t usage) {
175905 memory_usage = usage;
175906 }
175908 BufferPoolReservation &GetMemoryCharge(BlockLock &l) {
175909 VerifyMutex(l);
175910 return GetMemoryCharge();
175911 }
175913 BufferPoolReservation &GetMemoryCharge() {
175914 return memory_charge;
175915 }
175917 void ResizeMemory(BlockLock &l, idx_t alloc_size) {
175918 VerifyMutex(l);
175919 memory_charge.Resize(alloc_size);
175920 }
175922 void MergeMemoryReservation(BlockLock &l, BufferPoolReservation reservation) {
175923 VerifyMutex(l);
175924 memory_charge.Merge(std::move(reservation));
175925 }
175927 bool IsSwizzled() const {
175928 return !unswizzled;
175929 }
175931 void SetSwizzling(const char *unswizzler) {
175932 unswizzled = unswizzler;
175933 }
175935 void SetEvictionQueueIndex(const idx_t index) {
175936
175937 D_ASSERT(eviction_queue_idx == DConstants::INVALID_INDEX);
175938
175939 D_ASSERT(GetBufferType() == FileBufferType::MANAGED_BUFFER);
175940 eviction_queue_idx =
index;
175941 }
175943 idx_t GetEvictionQueueIndex()
const {
175944 return eviction_queue_idx;
175945 }
175946
175947public:
175948 void ChangeMemoryUsage(BlockLock &l, int64_t delta);
175949 void ConvertToPersistent(BlockLock &l, BlockHandle &new_block, unique_ptr<FileBuffer> new_buffer);
175950 void ResizeBuffer(BlockLock &l, idx_t block_size, idx_t block_header_size, int64_t memory_delta);
175954 bool CanUnload() const;
175955 unique_ptr<FileBuffer> UnloadAndTakeBlock(BlockLock &l);
175956 void Unload(BlockLock &l);
175957
175958private:
175960 BufferManager &buffer_manager;
175962 const block_id_t block_id;
175964 mutex lock;
175966 atomic<BlockState> state;
175968 atomic<int32_t> readers;
175970 const MemoryTag tag;
175972 const FileBufferType buffer_type;
175974 unique_ptr<FileBuffer> buffer;
175976 atomic<idx_t> eviction_seq_num;
175978 atomic<int64_t> lru_timestamp_msec;
175980 atomic<DestroyBufferUpon> destroy_buffer_upon;
175983 atomic<idx_t> memory_usage;
175985 BufferPoolReservation memory_charge;
175987 const char *unswizzled;
175989 atomic<idx_t> eviction_queue_idx;
175990};
175991
175992class BlockHandle : public enable_shared_from_this<BlockHandle> {
175993public:
175994 BlockHandle(BlockManager &block_manager, block_id_t block_id, MemoryTag tag);
175995 BlockHandle(BlockManager &block_manager, block_id_t block_id, MemoryTag tag, unique_ptr<FileBuffer> buffer,
175996 DestroyBufferUpon destroy_buffer_upon, idx_t size, BufferPoolReservation &&reservation);
175997 ~BlockHandle();
175998
175999public:
176001 BlockManager &GetBlockManager() const {
176002 return block_manager;
176003 }
176005 block_id_t BlockId() const {
176006 return block_id;
176007 }
176009 idx_t GetBlockAllocSize()
const {
176010 return block_alloc_size;
176011 }
176013 idx_t GetBlockHeaderSize()
const {
176014 return block_header_size;
176015 }
176019 idx_t GetBlockSize()
const {
176020 return block_alloc_size - block_header_size;
176021 }
176023 const BlockMemory &GetMemory() const {
176024 return memory;
176025 }
176027 BlockMemory &GetMemory() {
176028 return memory;
176029 }
176031 weak_ptr<BlockMemory> GetMemoryWeak() const {
176032 return weak_ptr<BlockMemory>(memory_p);
176033 }
176034
176035public:
176036 BufferHandle LoadFromBuffer(BlockLock &l, data_ptr_t data, unique_ptr<FileBuffer> reusable_buffer,
176037 BufferPoolReservation reservation);
176038 BufferHandle Load(QueryContext context, unique_ptr<FileBuffer> buffer = nullptr);
176039
176040private:
176042 BlockManager &block_manager;
176043
176048 idx_t block_alloc_size;
176050 idx_t block_header_size;
176052 const block_id_t block_id;
176053
176055 const shared_ptr<BlockMemory> memory_p;
176057 BlockMemory &memory;
176058};
176059
176060}
176061
176062
176063namespace duckdb {
176064
176065class CSVBufferHandle {
176066public:
176067 CSVBufferHandle(BufferHandle handle_p, idx_t actual_size_p, idx_t requested_size_p, const bool is_final_buffer_p,
176068 idx_t buffer_index_p)
176069 : handle(std::move(handle_p)), actual_size(actual_size_p), requested_size(requested_size_p),
176070 is_last_buffer(is_final_buffer_p), buffer_idx(buffer_index_p) {};
176071 CSVBufferHandle() : actual_size(0), requested_size(0), is_last_buffer(false), buffer_idx(0) {};
176072 ~CSVBufferHandle() {
176073 }
176075 BufferHandle handle;
176076 const idx_t actual_size;
176077 const idx_t requested_size;
176078 const bool is_last_buffer;
176079 const idx_t buffer_idx;
176080 inline char *
Ptr() {
176081 return char_ptr_cast(handle.Ptr());
176082 }
176083};
176084
176089class CSVBuffer {
176090public:
176092 CSVBuffer(ClientContext &context, idx_t buffer_size_p, CSVFileHandle &file_handle,
176093 const idx_t &global_csv_current_position);
176094
176096 CSVBuffer(CSVFileHandle &file_handle, ClientContext &context, idx_t buffer_size, idx_t global_csv_current_position,
176097 idx_t buffer_idx);
176098
176100 shared_ptr<CSVBuffer> Next(CSVFileHandle &file_handle, idx_t buffer_size, bool &has_seeked) const;
176101
176103 idx_t GetBufferSize()
const;
176104
176106 bool IsCSVFileLastBuffer() const;
176107
176109 void AllocateBuffer(idx_t buffer_size);
176110
176111 void Reload(CSVFileHandle &file_handle);
176114 shared_ptr<CSVBufferHandle> Pin(CSVFileHandle &file_handle, bool &has_seeked);
176116 void Unpin();
176118 return char_ptr_cast(handle.Ptr());
176119 }
176120 bool IsUnloaded() const {
176121 return block->GetMemory().IsUnloaded();
176122 }
176123
176125 static constexpr idx_t ROWS_PER_BUFFER = 16;
176126 static constexpr idx_t MIN_ROWS_PER_BUFFER = 4;
176127
176128 bool last_buffer = false;
176129
176130private:
176131 ClientContext &context;
176133 idx_t actual_buffer_size;
176134 idx_t requested_size;
176136 idx_t global_csv_start = 0;
176138 bool can_seek;
176140 bool is_pipe;
176142 idx_t buffer_idx = 0;
176145 shared_ptr<BlockHandle> block;
176146 BufferHandle handle;
176147};
176148}
176149
176150
176151
176152
176153
176154
176155
176156
176157
176158
176159
176160
176161
176162
176163
176164
176165
176166
176167
176168
176169
176170
176171
176172
176173#include <algorithm>
176174
176175namespace duckdb {
176176
176177enum class StrTimeSpecifier :
uint8_t {
176178 ABBREVIATED_WEEKDAY_NAME = 0,
176179 FULL_WEEKDAY_NAME = 1,
176180 WEEKDAY_DECIMAL = 2,
176181 DAY_OF_MONTH_PADDED = 3,
176182 DAY_OF_MONTH = 4,
176183 ABBREVIATED_MONTH_NAME = 5,
176184 FULL_MONTH_NAME = 6,
176185 MONTH_DECIMAL_PADDED = 7,
176186 MONTH_DECIMAL = 8,
176187 YEAR_WITHOUT_CENTURY_PADDED = 9,
176188 YEAR_WITHOUT_CENTURY = 10,
176189 YEAR_DECIMAL = 11,
176190 HOUR_24_PADDED = 12,
176191 HOUR_24_DECIMAL = 13,
176192 HOUR_12_PADDED = 14,
176193 HOUR_12_DECIMAL = 15,
176194 AM_PM = 16,
176195 MINUTE_PADDED = 17,
176196 MINUTE_DECIMAL = 18,
176197 SECOND_PADDED = 19,
176198 SECOND_DECIMAL = 20,
176199 MICROSECOND_PADDED = 21,
176200 MILLISECOND_PADDED = 22,
176201 UTC_OFFSET = 23,
176202 TZ_NAME = 24,
176203 DAY_OF_YEAR_PADDED = 25,
176204 DAY_OF_YEAR_DECIMAL = 26,
176205 WEEK_NUMBER_PADDED_SUN_FIRST =
176206 27,
176207
176208 WEEK_NUMBER_PADDED_MON_FIRST =
176209 28,
176210
176211 LOCALE_APPROPRIATE_DATE_AND_TIME =
176212 29,
176213 LOCALE_APPROPRIATE_DATE = 30,
176214 LOCALE_APPROPRIATE_TIME = 31,
176215 NANOSECOND_PADDED = 32,
176216
176217 YEAR_ISO =
176218 33,
176219 WEEKDAY_ISO = 34,
176220 WEEK_NUMBER_ISO = 35,
176221
176222};
176223
176224struct StrTimeFormat {
176225public:
176226 virtual ~StrTimeFormat() {
176227 }
176228
176229 DUCKDB_API
static string ParseFormatSpecifier(
const string &format_string, StrTimeFormat &
format);
176230
176231 inline bool HasFormatSpecifier(StrTimeSpecifier s) const {
176232 return std::find(specifiers.begin(), specifiers.end(), s) != specifiers.end();
176233 }
176235 DUCKDB_API bool Empty() const;
176236
176238 string format_specifier;
176239
176240protected:
176242 vector<StrTimeSpecifier> specifiers;
176246 vector<string> literals;
176248 idx_t constant_size = 0;
176250 vector<int> numeric_width;
176251
176252protected:
176253 void AddLiteral(string literal);
176254 DUCKDB_API virtual void AddFormatSpecifier(string preceding_literal, StrTimeSpecifier specifier);
176255};
176256
176257struct StrfTimeFormat : public StrTimeFormat {
176258 DUCKDB_API
idx_t GetLength(date_t date, dtime_t time, int32_t utc_offset,
const char *tz_name);
176259
176260 DUCKDB_API void FormatStringNS(date_t date, int32_t data[8], const char *tz_name, char *target) const;
176261 DUCKDB_API void FormatString(date_t date, int32_t data[8], const char *tz_name, char *target);
176262 void FormatString(date_t date, dtime_t time, char *target);
176263
176264 DUCKDB_API
static string Format(timestamp_t timestamp,
const string &
format);
176265
176266 DUCKDB_API void ConvertDateVector(Vector &input, Vector &result, idx_t count);
176267 DUCKDB_API void ConvertTimestampVector(Vector &input, Vector &result, idx_t count);
176268 DUCKDB_API void ConvertTimestampNSVector(Vector &input, Vector &result, idx_t count);
176269
176270protected:
176272 vector<StrTimeSpecifier> var_length_specifiers;
176275 vector<bool> is_date_specifier;
176276
176277protected:
176278 DUCKDB_API void AddFormatSpecifier(string preceding_literal, StrTimeSpecifier specifier) override;
176279 static idx_t GetSpecifierLength(StrTimeSpecifier specifier, date_t date, int32_t data[8],
const char *tz_name);
176280 idx_t GetLength(date_t date, int32_t data[8],
const char *tz_name)
const;
176281
176282 string_t ConvertTimestampValue(const timestamp_t &input, Vector &result) const;
176283 string_t ConvertTimestampValue(const timestamp_ns_t &input, Vector &result) const;
176284
176285 char *WriteString(char *target, const string_t &str) const;
176286 char *Write2(char *target, uint8_t value) const;
176287 char *WritePadded2(char *target, uint32_t value) const;
176288 char *WritePadded3(char *target, uint32_t value) const;
176289 char *WritePadded(char *target, uint32_t value, size_t padding) const;
176290 bool IsDateSpecifier(StrTimeSpecifier specifier);
176291 char *WriteDateSpecifier(StrTimeSpecifier specifier, date_t date, char *target) const;
176292 char *WriteStandardSpecifier(StrTimeSpecifier specifier, int32_t data[], const char *tz_name, size_t tz_len,
176293 char *target) const;
176294};
176295
176296struct StrpTimeFormat : public StrTimeFormat {
176297public:
176298 StrpTimeFormat();
176299
176301 struct ParseResult {
176303 string tz;
176304 string error_message;
176305 optional_idx error_position;
176306
176307 bool is_special;
176308 date_t special;
176309
176311
176312 date_t ToDate();
176313 dtime_t ToTime();
176315 timestamp_t ToTimestamp();
176316 timestamp_ns_t ToTimestampNS();
176317
176318 bool TryToDate(date_t &result);
176319 bool TryToTime(dtime_t &result);
176320 bool TryToTimestamp(timestamp_t &result);
176321 bool TryToTimestampNS(timestamp_ns_t &result);
176322
176323 DUCKDB_API string FormatError(string_t input, const string &format_specifier);
176324 };
176325
176326public:
176327 bool operator!=(
const StrpTimeFormat &other)
const {
176328 return format_specifier != other.format_specifier;
176329 }
176330 DUCKDB_API
static ParseResult Parse(
const string &
format,
const string &text);
176331 DUCKDB_API
static bool TryParse(
const string &
format,
const string &text, ParseResult &result);
176332
176333 DUCKDB_API bool Parse(string_t str, ParseResult &result, bool strict = false) const;
176334
176335 DUCKDB_API bool Parse(const char *data, size_t size, ParseResult &result, bool strict = false) const;
176336
176337 DUCKDB_API bool TryParseDate(const char *data, size_t size, date_t &result) const;
176338 DUCKDB_API bool TryParseTimestamp(const char *data, size_t size, timestamp_t &result) const;
176339 DUCKDB_API bool TryParseTimestampNS(const char *data, size_t size, timestamp_ns_t &result) const;
176340
176341 DUCKDB_API bool TryParseDate(string_t str, date_t &result, string &error_message) const;
176342 DUCKDB_API bool TryParseTime(string_t str, dtime_t &result, string &error_message) const;
176343 DUCKDB_API bool TryParseTimestamp(string_t str, timestamp_t &result, string &error_message) const;
176344 DUCKDB_API bool TryParseTimestampNS(string_t str, timestamp_ns_t &result, string &error_message) const;
176345
176346 void Serialize(Serializer &serializer) const;
176347 static StrpTimeFormat Deserialize(Deserializer &deserializer);
176348
176349protected:
176350 static string FormatStrpTimeError(const string &input, optional_idx position);
176351 DUCKDB_API void AddFormatSpecifier(string preceding_literal, StrTimeSpecifier specifier) override;
176352 int NumericSpecifierWidth(StrTimeSpecifier specifier);
176353 int32_t TryParseCollection(
const char *data, idx_t &pos, idx_t size,
const string_t collection[],
176354 idx_t collection_count) const;
176355
176356private:
176357 explicit StrpTimeFormat(const string &format_string);
176358};
176359
176360}
176361
176362
176363namespace duckdb {
176364
176365enum class NewLineIdentifier :
uint8_t {
176366 SINGLE_N = 1,
176367 CARRY_ON = 2,
176369 SINGLE_R = 4
176370
176371};
176372
176373class Serializer;
176374class Deserializer;
176375
176378template <typename T>
176379struct CSVOption {
176380public:
176381 CSVOption(T value_p) : value(value_p) {
176382 }
176383 CSVOption(T value_p, bool set_by_user_p) : set_by_user(set_by_user_p), value(value_p) {
176384 }
176385
176386 CSVOption() {};
176387
176390 void Set(T value_p, bool by_user = true) {
176391 D_ASSERT(!(by_user && set_by_user));
176392 if (!set_by_user) {
176393
176394 value = value_p;
176395 set_by_user = by_user;
176396 }
176397 }
176398
176401 void Set(CSVOption value_p, bool by_user = true) {
176402 D_ASSERT(!(by_user && set_by_user));
176403 if (!set_by_user) {
176404
176405 value = value_p;
176406 set_by_user = by_user;
176407 }
176408 }
176409
176410
176411 void ChangeSetByUserTrue() {
176412 set_by_user = true;
176413 }
176414
176415 bool operator==(
const CSVOption &other)
const {
176416 return value == other.value;
176417 }
176418
176419 bool operator!=(
const CSVOption &other)
const {
176420 return value != other.value;
176421 }
176422
176424 return value == other;
176425 }
176426
176428 return value != other;
176429 }
176431 inline const T &GetValue() const {
176432 return value;
176433 }
176434 bool IsSetByUser() const {
176435 return set_by_user;
176436 }
176437
176439 string FormatSet() const {
176440 if (set_by_user) {
176441 return "(Set By User)";
176442 }
176443 return "(Auto-Detected)";
176444 }
176445
176447 string FormatValue() const {
176448 return FormatValueInternal(value);
176449 }
176450
176452 DUCKDB_API void Serialize(Serializer &serializer) const;
176453
176455 DUCKDB_API static CSVOption<T> Deserialize(Deserializer &deserializer);
176456
176457private:
176459 bool set_by_user = false;
176460 T value;
176461
176465
176466 template <typename U>
176467 std::string FormatValueInternal(const U &val) const {
176468 throw InternalException("Type not accepted as CSV Option.");
176469 }
176470
176471 std::string FormatValueInternal(const std::string &val) const {
176472 return val;
176473 }
176474
176475 std::string FormatValueInternal(const idx_t &val) const {
176477 }
176478
176479 std::string FormatValueInternal(const char &val) const {
176480 string char_val;
176481 if (val == '\0') {
176482 char_val = "(empty)";
176483 return char_val;
176484 }
176485 char_val += val;
176486 return char_val;
176487 }
176488
176489 std::string FormatValueInternal(const NewLineIdentifier &val) const {
176490 switch (val) {
176491 case NewLineIdentifier::SINGLE_N:
176492 return "\\n";
176493 case NewLineIdentifier::SINGLE_R:
176494 return "\\r";
176495 case NewLineIdentifier::CARRY_ON:
176496 return "\\r\\n";
176497 case NewLineIdentifier::NOT_SET:
176498 return "Single-Line File";
176499 default:
176500 throw InternalException("Invalid Newline Detected.");
176501 }
176502 }
176503
176504 std::string FormatValueInternal(const StrpTimeFormat &val) const {
176505 return val.format_specifier;
176506 }
176507
176508 std::string FormatValueInternal(const bool &val) const {
176509 if (val) {
176510 return "true";
176511 }
176512 return "false";
176513 }
176514};
176515
176516}
176517
176518
176519
176520
176521
176522
176523
176524
176525
176526
176527
176528
176529
176530namespace duckdb {
176533struct CSVStateMachineOptions {
176534 CSVStateMachineOptions() {};
176535 CSVStateMachineOptions(string delimiter_p, char quote_p, char escape_p, char comment_p,
176536 NewLineIdentifier new_line_p, bool strict_mode_p)
176537 : delimiter(std::move(delimiter_p)), quote(quote_p), escape(escape_p), comment(comment_p), new_line(new_line_p),
176538 strict_mode(strict_mode_p) {};
176539
176541 CSVOption<string> delimiter {","};
176543 CSVOption<char> quote = '\"';
176545 CSVOption<char> escape = '\0';
176547 CSVOption<char> comment = '\0';
176549 CSVOption<NewLineIdentifier> new_line = NewLineIdentifier::NOT_SET;
176551 CSVOption<bool> strict_mode = true;
176552
176553 bool operator==(
const CSVStateMachineOptions &other)
const {
176554 return delimiter == other.delimiter && quote == other.quote && escape == other.escape &&
176555 new_line == other.new_line && comment == other.comment && strict_mode == other.strict_mode;
176556 }
176557};
176558}
176559
176560
176561
176562
176563
176564
176565
176566
176567
176568
176569
176570
176571
176572
176573
176574
176575
176576
176577
176578
176579
176580
176581
176582
176583
176584
176585
176586
176587
176588
176589
176590
176591
176592
176593
176594
176595
176596
176597
176598
176599
176600
176601
176602
176603
176604
176605
176606
176607
176608
176609
176610
176611
176612
176613
176614
176615
176616
176617
176618
176619
176620namespace duckdb {
176621
176622struct PerfectHash {
176623 std::size_t
operator()(
const idx_t &h)
const {
176624 return h;
176625 }
176626};
176627
176628struct PerfectEquality {
176629 bool operator()(
const idx_t &a,
const idx_t &b)
const {
176630 return a == b;
176631 }
176632};
176633
176634template <typename T>
176635using perfect_map_t = unordered_map<idx_t, T, PerfectHash, PerfectEquality>;
176636
176637using perfect_set_t = unordered_set<idx_t, PerfectHash, PerfectEquality>;
176638
176639}
176640
176641
176642
176643namespace duckdb {
176644
176645template <class T, bool is_const>
176646class fixed_size_map_iterator;
176647
176649template <class T>
176650class fixed_size_map_t {
176651 friend class fixed_size_map_iterator<T, false>;
176652 friend class fixed_size_map_iterator<T, true>;
176653
176654public:
176655 using key_type =
idx_t;
176656 using mapped_type = T;
176657 using occupied_mask = TemplatedValidityMask<uint8_t>;
176658 using iterator = fixed_size_map_iterator<mapped_type, false>;
176659 using const_iterator = fixed_size_map_iterator<mapped_type, true>;
176660
176661public:
176662 explicit fixed_size_map_t(idx_t capacity_p = 0) : capacity(capacity_p) {
176664 }
176665
176667 return count;
176668 }
176669
176670 void resize(idx_t capacity_p) {
176671 capacity = capacity_p;
176672 occupied = occupied_mask(capacity);
176673 values = make_unsafe_uniq_array_uninitialized<mapped_type>(capacity + 1);
176674 clear();
176675 }
176676
176677 void clear() {
176678 count = 0;
176679 occupied.SetAllInvalid(capacity);
176680 }
176681
176682 mapped_type &operator[](const key_type &key) {
176683 D_ASSERT(key < capacity);
176684 count += 1 - occupied.RowIsValidUnsafe(key);
176685 occupied.SetValidUnsafe(key);
176686 return values[key];
176687 }
176688
176689 const mapped_type &operator[](const key_type &key) const {
176690 D_ASSERT(key < capacity);
176691 return values[key];
176692 }
176693
176694 iterator begin() {
176695 iterator result(*this, 0);
176696 if (!occupied_mask::RowIsValid(occupied.GetValidityEntryUnsafe(0), 0)) {
176697 ++result;
176698 }
176699 return result;
176700 }
176701
176702 const_iterator begin() const {
176703 const_iterator result(*this, 0);
176704 if (!occupied_mask::RowIsValid(occupied.GetValidityEntryUnsafe(0), 0)) {
176705 ++result;
176706 }
176707 return result;
176708 }
176709
176710 iterator end() {
176711 return iterator(*this, capacity);
176712 }
176713
176714 const_iterator end() const {
176715 return const_iterator(*this, capacity);
176716 }
176717
176718 iterator find(const key_type &index) {
176719 return occupied.RowIsValidUnsafe(index) ? iterator(*this, index) : end();
176720 }
176721
176722 const_iterator find(const key_type &index) const {
176723 return occupied.RowIsValidUnsafe(index) ? const_iterator(*this, index) : end();
176724 }
176725
176726private:
176729
176730 occupied_mask occupied;
176731 unsafe_unique_array<mapped_type> values;
176732};
176733
176734template <class T, bool is_const>
176735class fixed_size_map_iterator {
176736public:
176737 using key_type =
idx_t;
176738 using mapped_type = T;
176739 using fixed_size_map_type = fixed_size_map_t<mapped_type>;
176740 using map_type = typename std::conditional<is_const, const fixed_size_map_type, fixed_size_map_type>::type;
176741 using occupied_mask = typename fixed_size_map_t<mapped_type>::occupied_mask;
176742
176743public:
176744 fixed_size_map_iterator(map_type &map_p, key_type index) : map(map_p) {
176745 occupied_mask::GetEntryIndex(index, entry_idx, idx_in_entry);
176746 }
176747
176748 fixed_size_map_iterator &operator++() {
176749
176750 if (++idx_in_entry == occupied_mask::BITS_PER_VALUE) {
176751 NextEntry();
176752 }
176753
176754 auto end = map.end();
176755 while (*this < end) {
176756 const auto &entry = map.occupied.GetValidityEntryUnsafe(entry_idx);
176757 if (entry ==
static_cast<uint8_t>(~occupied_mask::ValidityBuffer::MAX_ENTRY)) {
176758
176759 if (entry_idx == end.entry_idx) {
176760
176761 idx_in_entry = end.idx_in_entry;
176762 break;
176763 }
176764 NextEntry();
176765 } else {
176766
176767 const auto idx_to = entry_idx == end.entry_idx ? end.idx_in_entry : occupied_mask::BITS_PER_VALUE;
176768 for (; idx_in_entry < idx_to; idx_in_entry++) {
176769 if (map.occupied.RowIsValid(entry, idx_in_entry)) {
176770
176771 return *this;
176772 }
176773 }
176774
176775 if (*this != end) {
176776 NextEntry();
176777 }
176778 }
176779 }
176780 return *this;
176781 }
176782
176783 fixed_size_map_iterator operator++(int) {
176784 fixed_size_map_iterator tmp = *this;
176785 ++(*this);
176786 return tmp;
176787 }
176788
176789 key_type GetKey() const {
176790 return entry_idx * occupied_mask::BITS_PER_VALUE + idx_in_entry;
176791 }
176792
176793 mapped_type &GetValue() {
176794 return map.values[GetKey()];
176795 }
176796
176797 const mapped_type &GetValue() const {
176798 return map.values[GetKey()];
176799 }
176800
176801 friend bool operator==(
const fixed_size_map_iterator &a,
const fixed_size_map_iterator &b) {
176802 return a.entry_idx == b.entry_idx && a.idx_in_entry == b.idx_in_entry;
176803 }
176804
176805 friend bool operator!=(
const fixed_size_map_iterator &a,
const fixed_size_map_iterator &b) {
176806 return !(a == b);
176807 }
176808
176809 friend bool operator<(
const fixed_size_map_iterator &a,
const fixed_size_map_iterator &b) {
176810 if (a.entry_idx < b.entry_idx) {
176811 return true;
176812 }
176813 if (a.entry_idx == b.entry_idx) {
176814 return a.idx_in_entry < b.idx_in_entry;
176815 }
176816 return false;
176817 }
176818
176819private:
176820 void NextEntry() {
176821 entry_idx++;
176822 idx_in_entry = 0;
176823 }
176824
176825private:
176826 map_type ↦
176828 idx_t idx_in_entry;
176829};
176830
176832
176833
176834template <class T, bool fixed>
176835struct TemplatedMapGetter {
176836private:
176837 using key_type =
idx_t;
176838 using mapped_type = T;
176839 using fixed_size_map_type = fixed_size_map_t<mapped_type>;
176840 using perfect_map_type = perfect_map_t<mapped_type>;
176841 using map_type = typename std::conditional<fixed, fixed_size_map_type, perfect_map_type>::type;
176842 using iterator = typename map_type::iterator;
176843 using const_iterator = typename map_type::const_iterator;
176844
176845public:
176846 static key_type GetKey(const iterator &it) {
176847 return GetKeyInternal(it);
176848 }
176849
176850 static key_type GetKey(const const_iterator &it) {
176851 return GetKeyInternal(it);
176852 }
176853
176854 static mapped_type &GetValue(iterator &it) {
176855 return GetValueInternal(it);
176856 }
176857
176858 static const mapped_type &GetValue(const const_iterator &it) {
176859 return GetValueInternal(it);
176860 }
176861
176862private:
176863
176864
176865
176866
176867 static key_type GetKeyInternal(const typename perfect_map_type::iterator &it) {
176868 return it->first;
176869 }
176870
176871 static key_type GetKeyInternal(const typename perfect_map_type::const_iterator &it) {
176872 return it->first;
176873 }
176874
176875 static mapped_type &GetValueInternal(typename perfect_map_type::iterator &it) {
176876 return it->second;
176877 }
176878
176879 static const mapped_type &GetValueInternal(const typename perfect_map_type::const_iterator &it) {
176880 return it->second;
176881 }
176882
176883 static key_type GetKeyInternal(const typename fixed_size_map_type::iterator &it) {
176884 return it.GetKey();
176885 }
176886
176887 static key_type GetKeyInternal(const typename fixed_size_map_type::const_iterator &it) {
176888 return it.GetKey();
176889 }
176890
176891 static mapped_type &GetValueInternal(typename fixed_size_map_type::iterator &it) {
176892 return it.GetValue();
176893 }
176894
176895 static const mapped_type &GetValueInternal(const typename fixed_size_map_type::const_iterator &it) {
176896 return it.GetValue();
176897 }
176898};
176899
176900
176901}
176902
176903
176904
176905
176906
176907
176908
176909
176910
176911
176912
176913
176914
176915
176916
176917
176918
176919
176920
176921
176922
176923
176924
176925
176926
176927
176928
176929
176930
176931namespace duckdb {
176932
176933class DatabaseInstance;
176934class ClientContext;
176935class BlockHandle;
176936class ColumnDataAllocator;
176937
176938class ManagedResultSet : public enable_shared_from_this<ManagedResultSet> {
176939public:
176940 ManagedResultSet();
176941 ManagedResultSet(const weak_ptr<DatabaseInstance> &db, vector<shared_ptr<BlockHandle>> &handles);
176942
176943public:
176944 bool IsValid() const;
176945 shared_ptr<DatabaseInstance> GetDatabase() const;
176946 vector<shared_ptr<BlockHandle>> &GetHandles();
176947
176948private:
176949 bool valid;
176950 weak_ptr<DatabaseInstance>
db;
176951 optional_ptr<vector<shared_ptr<BlockHandle>>> handles;
176952};
176953
176954class ResultSetManager {
176955public:
176956 explicit ResultSetManager(DatabaseInstance &db);
176957
176958public:
176959 static ResultSetManager &Get(ClientContext &context);
176960 static ResultSetManager &Get(DatabaseInstance &db);
176961 ManagedResultSet Add(ColumnDataAllocator &allocator);
176962 void Remove(ColumnDataAllocator &allocator);
176963
176964private:
176965 mutex lock;
176966 weak_ptr<DatabaseInstance>
db;
176967 reference_map_t<ColumnDataAllocator, unique_ptr<vector<shared_ptr<BlockHandle>>>> open_results;
176968};
176969
176970}
176971
176972
176973namespace duckdb {
176974
176975struct ChunkMetaData;
176976struct VectorMetaData;
176977struct SwizzleMetaData;
176978
176979struct BlockMetaData {
176980public:
176985
176986private:
176988 shared_ptr<BlockHandle> handle;
176990 weak_ptr<BlockHandle> weak_handle;
176991
176992public:
176993 shared_ptr<BlockHandle> GetHandle() const;
176994 void SetHandle(ManagedResultSet &managed_result_set, shared_ptr<BlockHandle> handle);
176996};
176997
176998class ColumnDataAllocator {
176999public:
177000 explicit ColumnDataAllocator(Allocator &allocator);
177001 explicit ColumnDataAllocator(BufferManager &buffer_manager,
177002 ColumnDataCollectionLifetime lifetime = ColumnDataCollectionLifetime::REGULAR);
177003 ColumnDataAllocator(ClientContext &context, ColumnDataAllocatorType allocator_type,
177004 ColumnDataCollectionLifetime lifetime = ColumnDataCollectionLifetime::REGULAR);
177005 ColumnDataAllocator(ColumnDataAllocator &allocator);
177006 ~ColumnDataAllocator();
177007
177010 Allocator &GetAllocator();
177012 BufferManager &GetBufferManager();
177015 return type;
177016 }
177017 void MakeShared() {
177018 shared = true;
177019 }
177020 bool IsShared() const {
177021 return shared;
177022 }
177023 idx_t BlockCount()
const {
177024 return blocks.size();
177025 }
177026 idx_t SizeInBytes()
const {
177027 idx_t total_size = 0;
177028 for (const auto &block : blocks) {
177029 total_size += block.size;
177030 }
177031 return total_size;
177032 }
177033 idx_t AllocationSize()
const {
177034 return allocated_size;
177035 }
177037 void SetPartitionIndex(idx_t index) {
177038 D_ASSERT(!partition_index.IsValid());
177039 D_ASSERT(blocks.empty() && allocated_data.empty());
177040 partition_index =
index;
177041 }
177042
177043public:
177044 void AllocateData(idx_t size, uint32_t &block_id, uint32_t &offset, ChunkManagementState *chunk_state);
177045
177046 void Initialize(ColumnDataAllocator &other);
177047 void InitializeChunkState(ChunkManagementState &state, ChunkMetaData &meta_data);
177048 data_ptr_t GetDataPointer(ChunkManagementState &state, uint32_t block_id, uint32_t offset);
177049 void UnswizzlePointers(ChunkManagementState &state, Vector &result, SwizzleMetaData &swizzle_segment,
177050 const VectorMetaData &string_heap_segment, const idx_t &v_offset, const bool &copied);
177051
177053 void SetDestroyBufferUponUnpin(uint32_t block_id);
177055 shared_ptr<DatabaseInstance> GetDatabase() const;
177056
177057private:
177058 void AllocateEmptyBlock(idx_t size);
177059 BufferHandle AllocateBlock(idx_t size);
177060 BufferHandle Pin(uint32_t block_id);
177061
177062 bool HasBlocks() const {
177063 return !blocks.empty();
177064 }
177065
177066private:
177067 void AllocateBuffer(idx_t size, uint32_t &block_id, uint32_t &offset, ChunkManagementState *chunk_state);
177068 void AllocateMemory(idx_t size, uint32_t &block_id, uint32_t &offset, ChunkManagementState *chunk_state);
177069 void AssignPointer(uint32_t &block_id, uint32_t &offset, data_ptr_t pointer);
177070
177071private:
177073 union {
177075 Allocator *allocator;
177077 BufferManager *buffer_manager;
177078 } alloc;
177080 vector<BlockMetaData> blocks;
177082 vector<AllocatedData> allocated_data;
177084 bool shared = false;
177086 mutex lock;
177088 idx_t allocated_size = 0;
177090 optional_idx partition_index;
177092 ManagedResultSet managed_result_set;
177093};
177094
177095}
177096
177097
177098
177099namespace duckdb {
177100
177102struct PartitionedColumnDataAppendState {
177103public:
177104 PartitionedColumnDataAppendState() : partition_indices(LogicalType::UBIGINT) {
177105 }
177106
177107public:
177108 Vector partition_indices;
177109 SelectionVector partition_sel;
177110
177111 static constexpr idx_t MAP_THRESHOLD = 256;
177112 perfect_map_t<list_entry_t> partition_entries;
177113 fixed_size_map_t<list_entry_t> fixed_partition_entries;
177114
177115 DataChunk slice_chunk;
177116
177117 vector<unique_ptr<DataChunk>> partition_buffers;
177118 vector<unique_ptr<ColumnDataAppendState>> partition_append_states;
177119
177120public:
177121 template <bool fixed>
177122 typename std::conditional<fixed, fixed_size_map_t<list_entry_t>, perfect_map_t<list_entry_t>>::type &GetMap() {
177123 throw NotImplementedException("PartitionedColumnDataAppendState::GetMap for boolean value");
177124 }
177125
177126 optional_idx GetPartitionIndexIfSinglePartition(const bool use_fixed_size_map) {
177127 optional_idx result;
177128 if (use_fixed_size_map) {
177129 if (fixed_partition_entries.size() == 1) {
177130 result = fixed_partition_entries.begin().GetKey();
177131 }
177132 } else {
177133 if (partition_entries.size() == 1) {
177134 result = partition_entries.begin()->first;
177135 }
177136 }
177137 return result;
177138 }
177139};
177140
177141template <>
177142inline perfect_map_t<list_entry_t> &PartitionedColumnDataAppendState::GetMap<false>() {
177143 return partition_entries;
177144}
177145
177146template <>
177147inline fixed_size_map_t<list_entry_t> &PartitionedColumnDataAppendState::GetMap<true>() {
177148 return fixed_partition_entries;
177149}
177150
177152 INVALID,
177157};
177158
177160struct PartitionColumnDataAllocators {
177161 mutex lock;
177162 vector<shared_ptr<ColumnDataAllocator>> allocators;
177163};
177164
177167class PartitionedColumnData {
177168public:
177169 unique_ptr<PartitionedColumnData> CreateShared();
177170 virtual ~PartitionedColumnData();
177171
177172public:
177174 void InitializeAppendState(PartitionedColumnDataAppendState &state) const;
177176 void Append(PartitionedColumnDataAppendState &state, DataChunk &input);
177178 void FlushAppendState(PartitionedColumnDataAppendState &state);
177180 void Combine(PartitionedColumnData &other);
177182 vector<unique_ptr<ColumnDataCollection>> &GetPartitions();
177183
177184protected:
177185
177186
177187
177189 virtual idx_t BufferSize()
const {
177190 return MinValue<idx_t>(128, STANDARD_VECTOR_SIZE);
177191 }
177193 virtual void InitializeAppendStateInternal(PartitionedColumnDataAppendState &state) const {
177194 }
177198 virtual void ComputePartitionIndices(PartitionedColumnDataAppendState &state, DataChunk &input) {
177199 throw NotImplementedException("ComputePartitionIndices for this type of PartitionedColumnData");
177200 }
177202
177204 virtual idx_t MaxPartitionIndex()
const {
177205 return DConstants::INVALID_INDEX;
177206 }
177207
177208protected:
177210 PartitionedColumnData(PartitionedColumnDataType type, ClientContext &context, vector<LogicalType> types);
177211 PartitionedColumnData(const PartitionedColumnData &other);
177212
177214 inline idx_t HalfBufferSize()
const {
177215 D_ASSERT(IsPowerOfTwo(BufferSize()));
177216 return BufferSize() / 2;
177217 }
177219 void CreateAllocator();
177221 bool UseFixedSizeMap() const;
177224 void BuildPartitionSel(PartitionedColumnDataAppendState &state, const idx_t append_count) const;
177225 template <bool fixed>
177226 static void BuildPartitionSel(PartitionedColumnDataAppendState &state, const idx_t append_count);
177228 template <bool fixed>
177229 void AppendInternal(PartitionedColumnDataAppendState &state, DataChunk &input);
177231 unique_ptr<ColumnDataCollection> CreatePartitionCollection(idx_t partition_index) const {
177232 return make_uniq<ColumnDataCollection>(allocators->allocators[partition_index], types);
177233 }
177235 unique_ptr<DataChunk> CreatePartitionBuffer() const;
177236
177237protected:
177239 ClientContext &context;
177240 vector<LogicalType> types;
177241
177242 mutex lock;
177243 shared_ptr<PartitionColumnDataAllocators> allocators;
177244 vector<unique_ptr<ColumnDataCollection>> partitions;
177245
177246public:
177247 template <class TARGET>
177248 TARGET &Cast() {
177249 DynamicCastCheck<TARGET>(this);
177250 return reinterpret_cast<TARGET &>(*this);
177251 }
177252 template <class TARGET>
177253 const TARGET &Cast() const {
177254 DynamicCastCheck<TARGET>(this);
177255 return reinterpret_cast<const TARGET &>(*this);
177256 }
177257};
177258
177259}
177260
177261
177262
177263
177264
177265
177266
177267
177268
177269
177270
177271
177272
177273
177274
177275
177276
177277
177278
177279
177280
177281
177282
177283
177284
177285
177286
177287
177288namespace duckdb {
177289
177290enum class DebugVectorVerification :
uint8_t {
177291 NONE,
177292 DICTIONARY_EXPRESSION,
177293 DICTIONARY_OPERATOR,
177294 CONSTANT_OPERATOR,
177295 SEQUENCE_OPERATOR,
177296 NESTED_SHUFFLE,
177297 VARIANT_VECTOR
177298};
177299
177300}
177301
177302
177303namespace duckdb {
177304class Allocator;
177305class ExecutionContext;
177306
177308class ExpressionExecutor {
177309 friend class BoundIndex;
177310
177311public:
177312 DUCKDB_API explicit ExpressionExecutor(ClientContext &context);
177313 DUCKDB_API ExpressionExecutor(ClientContext &context, const Expression *expression);
177314 DUCKDB_API ExpressionExecutor(ClientContext &context, const Expression &expression);
177315 DUCKDB_API ExpressionExecutor(ClientContext &context, const vector<unique_ptr<Expression>> &expressions);
177316 ExpressionExecutor(ExpressionExecutor &&) = delete;
177317
177319 vector<const Expression *> expressions;
177322 DataChunk *chunk = nullptr;
177323
177324public:
177325 bool HasContext();
177326 ClientContext &GetContext();
177327 Allocator &GetAllocator();
177328
177330 DUCKDB_API void AddExpression(const Expression &expr);
177331 void ClearExpressions();
177332
177334 DUCKDB_API void Execute(DataChunk *input, DataChunk &result);
177335 inline void Execute(DataChunk &input, DataChunk &result) {
177336 Execute(&input, result);
177337 }
177338 inline void Execute(DataChunk &result) {
177339 Execute(nullptr, result);
177340 }
177341
177344 DUCKDB_API void ExecuteExpression(DataChunk &input, Vector &result);
177347 DUCKDB_API void ExecuteExpression(Vector &result);
177350 DUCKDB_API
idx_t SelectExpression(DataChunk &input, SelectionVector &sel);
177351
177352 DUCKDB_API
idx_t SelectExpression(DataChunk &input, SelectionVector &result_sel,
177353 optional_ptr<SelectionVector> current_sel, idx_t current_count);
177354
177355 DUCKDB_API
idx_t SelectExpression(DataChunk &input, optional_ptr<SelectionVector> true_sel,
177356 optional_ptr<SelectionVector> false_sel,
177357 optional_ptr<SelectionVector> current_sel, idx_t current_count);
177358
177360 DUCKDB_API void ExecuteExpression(idx_t expr_idx, Vector &result);
177362 DUCKDB_API static Value EvaluateScalar(ClientContext &context, const Expression &expr,
177363 bool allow_unfoldable = false);
177365 DUCKDB_API static bool TryEvaluateScalar(ClientContext &context, const Expression &expr, Value &result);
177366
177368 static unique_ptr<ExpressionState> InitializeState(const Expression &expr, ExpressionExecutorState &state);
177369
177370 inline void SetChunk(DataChunk *chunk) {
177371 this->chunk = chunk;
177372 }
177373 inline void SetChunk(DataChunk &chunk) {
177374 SetChunk(&chunk);
177375 }
177376
177377 DUCKDB_API vector<unique_ptr<ExpressionExecutorState>> &GetStates();
177378
177379protected:
177380 void Initialize(const Expression &expr, ExpressionExecutorState &state);
177381
177382 static unique_ptr<ExpressionState> InitializeState(const BoundReferenceExpression &expr,
177383 ExpressionExecutorState &state);
177384 static unique_ptr<ExpressionState> InitializeState(const BoundBetweenExpression &expr,
177385 ExpressionExecutorState &state);
177386 static unique_ptr<ExpressionState> InitializeState(const BoundCaseExpression &expr, ExpressionExecutorState &state);
177387 static unique_ptr<ExpressionState> InitializeState(const BoundCastExpression &expr, ExpressionExecutorState &state);
177388 static unique_ptr<ExpressionState> InitializeState(const BoundComparisonExpression &expr,
177389 ExpressionExecutorState &state);
177390 static unique_ptr<ExpressionState> InitializeState(const BoundConjunctionExpression &expr,
177391 ExpressionExecutorState &state);
177392 static unique_ptr<ExpressionState> InitializeState(const BoundConstantExpression &expr,
177393 ExpressionExecutorState &state);
177394 static unique_ptr<ExpressionState> InitializeState(const BoundFunctionExpression &expr,
177395 ExpressionExecutorState &state);
177396 static unique_ptr<ExpressionState> InitializeState(const BoundOperatorExpression &expr,
177397 ExpressionExecutorState &state);
177398 static unique_ptr<ExpressionState> InitializeState(const BoundParameterExpression &expr,
177399 ExpressionExecutorState &state);
177400
177401 void Execute(const Expression &expr, ExpressionState *state, const SelectionVector *sel, idx_t count,
177402 Vector &result);
177403
177404 void Execute(const BoundBetweenExpression &expr, ExpressionState *state, const SelectionVector *sel, idx_t count,
177405 Vector &result);
177406 void Execute(const BoundCaseExpression &expr, ExpressionState *state, const SelectionVector *sel, idx_t count,
177407 Vector &result);
177408 void Execute(const BoundCastExpression &expr, ExpressionState *state, const SelectionVector *sel, idx_t count,
177409 Vector &result);
177410
177411 void Execute(const BoundComparisonExpression &expr, ExpressionState *state, const SelectionVector *sel, idx_t count,
177412 Vector &result);
177413 void Execute(const BoundConjunctionExpression &expr, ExpressionState *state, const SelectionVector *sel,
177414 idx_t count, Vector &result);
177415 void Execute(const BoundConstantExpression &expr, ExpressionState *state, const SelectionVector *sel, idx_t count,
177416 Vector &result);
177417 void Execute(const BoundFunctionExpression &expr, ExpressionState *state, const SelectionVector *sel, idx_t count,
177418 Vector &result);
177419 void Execute(const BoundOperatorExpression &expr, ExpressionState *state, const SelectionVector *sel, idx_t count,
177420 Vector &result);
177421 void Execute(const BoundParameterExpression &expr, ExpressionState *state, const SelectionVector *sel, idx_t count,
177422 Vector &result);
177423 void Execute(const BoundReferenceExpression &expr, ExpressionState *state, const SelectionVector *sel, idx_t count,
177424 Vector &result);
177425
177428 idx_t Select(
const Expression &expr, ExpressionState *state,
const SelectionVector *sel, idx_t count,
177429 SelectionVector *true_sel, SelectionVector *false_sel);
177430 idx_t DefaultSelect(
const Expression &expr, ExpressionState *state,
const SelectionVector *sel, idx_t count,
177431 SelectionVector *true_sel, SelectionVector *false_sel);
177432
177433 idx_t Select(
const BoundBetweenExpression &expr, ExpressionState *state,
const SelectionVector *sel, idx_t count,
177434 SelectionVector *true_sel, SelectionVector *false_sel);
177435 idx_t Select(
const BoundComparisonExpression &expr, ExpressionState *state,
const SelectionVector *sel, idx_t count,
177436 SelectionVector *true_sel, SelectionVector *false_sel);
177437 idx_t Select(
const BoundConjunctionExpression &expr, ExpressionState *state,
const SelectionVector *sel,
177438 idx_t count, SelectionVector *true_sel, SelectionVector *false_sel);
177439
177441 void Verify(const Expression &expr, Vector &result, idx_t count);
177442
177443 void FillSwitch(Vector &vector, Vector &result, const SelectionVector &sel, sel_t count);
177444
177445private:
177447 optional_ptr<ClientContext> context;
177449 vector<unique_ptr<ExpressionExecutorState>> states;
177451 DebugVectorVerification debug_vector_verification = DebugVectorVerification::NONE;
177452
177453private:
177454
177455 DUCKDB_API ExpressionExecutor();
177456 DUCKDB_API explicit ExpressionExecutor(const vector<unique_ptr<Expression>> &exprs);
177457};
177458}
177459
177460
177461
177462
177463
177464
177465
177466
177467
177468
177469
177470
177471
177472
177473
177474
177475
177476
177477
177478
177479
177480
177481
177482
177483
177484
177485
177486
177487
177488
177489namespace duckdb {
177490
177491class ConstantFilter : public TableFilter {
177492public:
177493 static constexpr const TableFilterType
TYPE = TableFilterType::CONSTANT_COMPARISON;
177494
177495public:
177496 ConstantFilter(ExpressionType comparison_type, Value constant);
177497
177499 ExpressionType comparison_type;
177501 Value constant;
177502
177503public:
177504 bool Compare(const Value &value) const;
177505 FilterPropagateResult CheckStatistics(BaseStatistics &stats) const override;
177506 string ToString(const string &column_name) const override;
177507 bool Equals(const TableFilter &other) const override;
177508 unique_ptr<TableFilter> Copy() const override;
177509 unique_ptr<Expression> ToExpression(const Expression &column) const override;
177510 void Serialize(Serializer &serializer) const override;
177511 static unique_ptr<TableFilter> Deserialize(Deserializer &deserializer);
177512};
177513
177514}
177515
177516
177517
177518
177519
177520
177521
177522
177523
177524
177525
177526
177527
177528
177529
177530
177531
177532
177533
177534
177535
177536
177537
177538
177539namespace duckdb {
177540
177541
177542
177543
177544enum class IndexConstraintType :
uint8_t {
177545 NONE = 0,
177546 UNIQUE = 1,
177547 PRIMARY = 2,
177548 FOREIGN = 3
177549};
177550
177551
177552
177553
177554
177555enum class DeprecatedIndexType :
uint8_t {
177556 INVALID = 0,
177557 ART = 1,
177558 EXTENSION = 100
177559};
177560
177561}
177562
177563
177564
177565
177566
177567
177568
177569
177570
177571
177572
177573
177574
177575
177576
177577
177578
177579
177580
177581namespace duckdb {
177582
177583class Index;
177584
177586class ConflictInfo {
177587public:
177588 explicit ConflictInfo(const unordered_set<column_t> &column_ids, bool only_check_unique = true)
177589 : column_ids(column_ids), only_check_unique(only_check_unique) {
177590 }
177591
177592 const unordered_set<column_t> &column_ids;
177593 bool only_check_unique = true;
177594
177595public:
177596 bool ConflictTargetMatches(Index &index) const;
177598 bool SingleIndexTarget() const {
177599 return !column_ids.empty();
177600 }
177601};
177602
177603}
177604
177605
177606
177607
177608
177609
177610
177611
177612
177613
177614
177615
177616
177617
177618
177619
177620
177621
177622
177623
177624
177625
177626
177627
177628
177629
177630
177631namespace duckdb {
177632
177634struct FixedSizeAllocatorInfo {
177635 idx_t segment_size;
177636 vector<idx_t> buffer_ids;
177637 vector<BlockPointer> block_pointers;
177638 vector<idx_t> segment_counts;
177639 vector<idx_t> allocation_sizes;
177640 vector<idx_t> buffers_with_free_space;
177641
177642 void Serialize(Serializer &serializer) const;
177643 static FixedSizeAllocatorInfo Deserialize(Deserializer &deserializer);
177644};
177645
177647struct IndexBufferInfo {
177648 IndexBufferInfo(data_ptr_t buffer_ptr, const idx_t allocation_size)
177650 }
177651
177653 idx_t allocation_size;
177654};
177655
177657struct IndexStorageInfo {
177658 IndexStorageInfo() {};
177659 explicit IndexStorageInfo(const string &name) : name(name) {};
177660
177662 IndexStorageInfo(const IndexStorageInfo &) = delete;
177663 IndexStorageInfo &
operator=(
const IndexStorageInfo &) =
delete;
177664
177665 IndexStorageInfo(IndexStorageInfo &&) = default;
177666 IndexStorageInfo &
operator=(IndexStorageInfo &&) =
default;
177667
177669 string name;
177673 case_insensitive_map_t<Value> options;
177675 vector<FixedSizeAllocatorInfo> allocator_infos;
177676
177680 vector<vector<IndexBufferInfo>> buffers;
177681
177683 BlockPointer root_block_ptr;
177684
177690 bool IsValid() const {
177691 return root_block_ptr.IsValid() || !allocator_infos.empty();
177692 }
177693
177694 void Serialize(Serializer &serializer) const;
177695 static IndexStorageInfo Deserialize(Deserializer &deserializer);
177696};
177697
177699struct IndexInfo {
177700 bool is_unique;
177701 bool is_primary;
177702 bool is_foreign;
177703 unordered_set<column_t> column_set;
177704};
177705
177706}
177707
177708
177709
177710
177711
177712
177713
177714
177715
177716
177717
177718
177719
177720
177721
177722
177723
177724
177725
177726
177727
177728
177729
177730
177731
177732
177733
177734
177735
177736
177737
177738
177739
177740
177741
177742
177743
177744
177745
177746
177747
177748
177749
177750
177751
177752
177753
177754
177755
177756
177757
177758
177759
177760
177761
177762
177763
177764
177765
177766
177767#include <random>
177768
177769namespace duckdb {
177770class ClientContext;
177771struct RandomState;
177772
177773class RandomEngine {
177774public:
177775 explicit RandomEngine(int64_t seed = -1);
177776 ~RandomEngine();
177777
177779 double NextRandom(
double min,
double max);
177780
177782 double NextRandom();
177784 double NextRandom32();
177785 double NextRandom32(
double min,
double max);
177790
177791 void SetSeed(uint64_t seed);
177792
177793 void RandomData(duckdb::data_ptr_t data,
duckdb::idx_t len);
177794
177795 static RandomEngine &Get(ClientContext &context);
177796
177797 mutex lock;
177798
177799private:
177800 unique_ptr<RandomState> random_state;
177801};
177802
177803}
177804
177805
177806
177807
177808
177809
177810
177811
177812
177813
177814
177815
177816
177817#ifdef WIN32
177818
177819#ifdef min
177820#undef min
177821#endif
177822
177823#ifdef max
177824#undef max
177825#endif
177826
177827#ifdef ERROR
177828#undef ERROR
177829#endif
177830
177831#ifdef small
177832#undef small
177833#endif
177834
177835#ifdef CreateDirectory
177836#undef CreateDirectory
177837#endif
177838
177839#ifdef MoveFile
177840#undef MoveFile
177841#endif
177842
177843#ifdef RemoveDirectory
177844#undef RemoveDirectory
177845#endif
177846
177847#ifdef UUID
177848#undef UUID
177849#endif
177850
177851#ifdef interface
177852#undef interface
177853#endif
177854
177855#ifdef DELETE
177856#undef DELETE
177857#endif
177858
177859#endif
177860
177861
177862
177863
177864
177865
177866#define FIXED_SAMPLE_SIZE 2048
177867
177868namespace duckdb {
177869
177870enum class SampleType :
uint8_t { BLOCKING_SAMPLE = 0, RESERVOIR_SAMPLE = 1, RESERVOIR_PERCENTAGE_SAMPLE = 2 };
177871
177872enum class SamplingState :
uint8_t { RANDOM = 0, RESERVOIR = 1 };
177873
177874class ReservoirRNG : public RandomEngine {
177875public:
177876
177878
177879 explicit ReservoirRNG(int64_t seed) : RandomEngine(seed) {};
177880
177882 return NextRandomInteger();
177883 };
177884
177885 static constexpr result_type
min() {
177886 return NumericLimits<result_type>::Minimum();
177887 };
177888 static constexpr result_type
max() {
177889 return NumericLimits<result_type>::Maximum();
177890 };
177891};
177892
177894class BaseReservoirSampling {
177895public:
177896 explicit BaseReservoirSampling(int64_t seed);
177897 BaseReservoirSampling();
177898
177899 void InitializeReservoirWeights(idx_t cur_size, idx_t sample_size);
177900
177901 void SetNextEntry();
177902
177903 void ReplaceElementWithIndex(idx_t entry_index, double with_weight, bool pop = true);
177904 void ReplaceElement(double with_weight = -1);
177905
177906 void UpdateMinWeightThreshold();
177907
177911 void FillWeights(SelectionVector &sel, idx_t &sel_size);
177912
177913 unique_ptr<BaseReservoirSampling> Copy();
177914
177916 ReservoirRNG random;
177917
177919 idx_t next_index_to_sample;
177921 double min_weight_threshold;
177923 idx_t min_weighted_entry_index;
177926 idx_t num_entries_to_skip_b4_next_sample;
177929 idx_t num_entries_seen_total;
177931 std::priority_queue<std::pair<double, idx_t>> reservoir_weights;
177932
177933 void Serialize(Serializer &serializer) const;
177934 static unique_ptr<BaseReservoirSampling> Deserialize(Deserializer &deserializer);
177935
177936
177937
177938
177939
177940 friend class BlockingSample;
177941};
177942
177943class BlockingSample {
177944public:
177945 static constexpr const SampleType
TYPE = SampleType::BLOCKING_SAMPLE;
177946
177947 unique_ptr<BaseReservoirSampling> base_reservoir_sample;
177949 SampleType type;
177951 bool destroyed;
177952
177953public:
177954 explicit BlockingSample(int64_t seed = -1)
177955 : base_reservoir_sample(make_uniq<BaseReservoirSampling>(seed)), type(SampleType::BLOCKING_SAMPLE),
177956 destroyed(false) {
177957 }
177958 virtual ~BlockingSample() {
177959 }
177960
177962 virtual void AddToReservoir(DataChunk &input) = 0;
177963 virtual unique_ptr<BlockingSample> Copy() const = 0;
177964 virtual void Finalize() = 0;
177965 virtual void Destroy();
177966
177969 virtual unique_ptr<DataChunk> GetChunk() = 0;
177970
177971 virtual void Serialize(Serializer &serializer) const;
177972 static unique_ptr<BlockingSample> Deserialize(Deserializer &deserializer);
177973
177975 std::pair<double, idx_t> PopFromWeightQueue();
177976 double GetMinWeightThreshold();
177977 idx_t GetPriorityQueueSize();
177978
177979public:
177980 template <class TARGET>
177981 TARGET &Cast() {
177982 if (type != TARGET::TYPE && TARGET::TYPE != SampleType::BLOCKING_SAMPLE) {
177983 throw InternalException("Failed to cast sample to type - sample type mismatch");
177984 }
177985 return reinterpret_cast<TARGET &>(*this);
177986 }
177987
177988 template <class TARGET>
177989 const TARGET &Cast() const {
177990 if (type != TARGET::TYPE && TARGET::TYPE != SampleType::BLOCKING_SAMPLE) {
177991 throw InternalException("Failed to cast sample to type - sample type mismatch");
177992 }
177993 return reinterpret_cast<const TARGET &>(*this);
177994 }
177995};
177996
177997class ReservoirChunk {
177998public:
177999 ReservoirChunk() {
178000 }
178001
178002 DataChunk chunk;
178003 void Serialize(Serializer &serializer) const;
178004 static unique_ptr<ReservoirChunk> Deserialize(Deserializer &deserializer);
178005
178006 unique_ptr<ReservoirChunk> Copy() const;
178007};
178008
178009struct SelectionVectorHelper {
178010 SelectionVector sel;
178012};
178013
178014class ReservoirSample : public BlockingSample {
178015public:
178016 static constexpr const SampleType
TYPE = SampleType::RESERVOIR_SAMPLE;
178017
178018 constexpr static idx_t FIXED_SAMPLE_SIZE_MULTIPLIER = 10;
178019
178020
178021
178022
178023
178024
178025 constexpr static idx_t FAST_TO_SLOW_THRESHOLD = MinValue<idx_t>(STANDARD_VECTOR_SIZE, 60);
178026
178027
178028
178029 constexpr static double SAVE_PERCENTAGE = 0.01;
178030
178031 ReservoirSample(Allocator &allocator, idx_t sample_count, int64_t seed = 1);
178032 explicit ReservoirSample(idx_t sample_count, unique_ptr<ReservoirChunk> = nullptr);
178033
178035 void EvictOverBudgetSamples();
178036 void ExpandSerializedSample();
178037
178038 SamplingState GetSamplingState() const;
178039
178042 void Vacuum();
178043
178045 void ConvertToReservoirSample();
178046
178048 template <typename T>
178049 T GetReservoirChunkCapacity() const;
178050
178053 unique_ptr<BlockingSample> Copy() const override;
178054
178056 idx_t FillReservoir(DataChunk &chunk);
178058 void AddToReservoir(DataChunk &input) override;
178060 void Merge(unique_ptr<BlockingSample> other);
178061
178062 void ShuffleSel(SelectionVector &sel, idx_t range, idx_t size) const;
178063
178066 void UpdateSampleAppend(DataChunk &this_, DataChunk &other, SelectionVector &other_sel, idx_t append_count) const;
178067
178068 idx_t GetTuplesSeen()
const;
178069 idx_t NumSamplesCollected()
const;
178070 idx_t GetActiveSampleCount()
const;
178071 static bool ValidSampleType(const LogicalType &type);
178072
178073
178074 DataChunk &Chunk();
178075
178078
178079 unique_ptr<DataChunk> GetChunk() override;
178080 void Destroy() override;
178081 void Finalize() override;
178082 void Verify();
178083
178084 idx_t GetSampleCount();
178085
178086
178087
178088
178089
178090
178091
178093 SelectionVectorHelper GetReplacementIndexes(idx_t sample_chunk_offset, idx_t theoretical_chunk_length);
178094
178095 void Serialize(Serializer &serializer) const override;
178096 static unique_ptr<BlockingSample> Deserialize(Deserializer &deserializer);
178097
178098private:
178099
178100
178101
178102
178103 void NormalizeWeights();
178104
178105 SelectionVectorHelper GetReplacementIndexesSlow(const idx_t sample_chunk_offset, const idx_t chunk_length);
178106 SelectionVectorHelper GetReplacementIndexesFast(const idx_t sample_chunk_offset, const idx_t chunk_length);
178107 void SimpleMerge(ReservoirSample &other);
178108 void WeightedMerge(ReservoirSample &other_sample);
178109
178110
178111
178112
178113
178114 unique_ptr<ReservoirChunk> CreateNewSampleChunk(vector<LogicalType> &types, idx_t size) const;
178115
178116
178117
178118 vector<uint32_t> GetRandomizedVector(uint32_t range, uint32_t size) const;
178119
178120 idx_t sample_count;
178121 Allocator &allocator;
178122 unique_ptr<ReservoirChunk> reservoir_chunk;
178123 bool stats_sample;
178124 SelectionVector sel;
178126};
178127
178129class ReservoirSamplePercentage : public BlockingSample {
178130 constexpr static idx_t RESERVOIR_THRESHOLD = 100000;
178131
178132public:
178133 static constexpr const SampleType
TYPE = SampleType::RESERVOIR_PERCENTAGE_SAMPLE;
178134
178135 ReservoirSamplePercentage(Allocator &allocator, double percentage, int64_t seed = -1);
178136 ReservoirSamplePercentage(double percentage, int64_t seed, idx_t reservoir_sample_size);
178137 explicit ReservoirSamplePercentage(double percentage, int64_t seed = -1);
178138
178140 void AddToReservoir(DataChunk &input) override;
178141
178142 unique_ptr<BlockingSample> Copy() const override;
178143
178145 unique_ptr<DataChunk> GetChunk() override;
178146 void Finalize() override;
178147
178148 void Serialize(Serializer &serializer) const override;
178149 static unique_ptr<BlockingSample> Deserialize(Deserializer &deserializer);
178150
178151private:
178152 Allocator &allocator;
178154 double sample_percentage;
178156 idx_t reservoir_sample_size;
178157
178159 unique_ptr<ReservoirSample> current_sample;
178160
178162 vector<unique_ptr<ReservoirSample>> finished_samples;
178163
178165 idx_t current_count = 0;
178168 bool is_finalized;
178169};
178170
178171}
178172
178173
178174
178175
178176
178177
178178
178179
178180
178181
178182
178183
178184
178185
178186
178187
178188
178189
178190
178191
178192
178193
178194
178195
178196
178197
178198
178199
178200
178201
178202
178203
178204
178205
178206
178207
178208
178209
178210
178211
178212
178213
178214
178215
178216
178217
178218
178219
178220namespace duckdb {
178221
178222template <class T>
178223struct CountZeros {};
178224
178225template <>
178227
178228 inline static idx_t Leading(
const uint64_t value_in) {
178229 if (!value_in) {
178230 return 64;
178231 }
178232
178234
178235 constexpr uint64_t index64msb[] = {0, 47, 1, 56, 48, 27, 2, 60, 57, 49, 41, 37, 28, 16, 3, 61,
178236 54, 58, 35, 52, 50, 42, 21, 44, 38, 32, 29, 23, 17, 11, 4, 62,
178237 46, 55, 26, 59, 40, 36, 15, 53, 34, 51, 20, 43, 31, 22, 10, 45,
178238 25, 39, 14, 33, 19, 30, 9, 24, 13, 18, 8, 12, 7, 6, 5, 63};
178239
178240 constexpr uint64_t debruijn64msb = 0X03F79D71B4CB0A89;
178241
178242 value |= value >> 1;
178243 value |= value >> 2;
178244 value |= value >> 4;
178245 value |= value >> 8;
178246 value |= value >> 16;
178247 value |= value >> 32;
178248 auto result = 63 - index64msb[(value * debruijn64msb) >> 58];
178249#ifdef __clang__
178250 D_ASSERT(result ==
static_cast<uint64_t>(__builtin_clzl(value_in)));
178251#endif
178252 return result;
178253 }
178254 inline static idx_t Trailing(uint64_t value_in) {
178255 if (!value_in) {
178256 return 64;
178257 }
178259
178260 constexpr uint64_t index64lsb[] = {63, 0, 58, 1, 59, 47, 53, 2, 60, 39, 48, 27, 54, 33, 42, 3,
178261 61, 51, 37, 40, 49, 18, 28, 20, 55, 30, 34, 11, 43, 14, 22, 4,
178262 62, 57, 46, 52, 38, 26, 32, 41, 50, 36, 17, 19, 29, 10, 13, 21,
178263 56, 45, 25, 31, 35, 16, 9, 12, 44, 24, 15, 8, 23, 7, 6, 5};
178264 constexpr uint64_t debruijn64lsb = 0x07EDD5E59A4E28C2ULL;
178265 auto result = index64lsb[((value & -value) * debruijn64lsb) >> 58];
178266#ifdef __clang__
178267 D_ASSERT(result ==
static_cast<uint64_t>(__builtin_ctzl(value_in)));
178268#endif
178269 return result;
178270 }
178271};
178272
178273template <>
178275 inline static idx_t Leading(uint32_t value) {
178276 return CountZeros<uint64_t>::Leading(
static_cast<uint64_t>(value)) - 32;
178277 }
178278 inline static idx_t Trailing(uint32_t value) {
178279 return CountZeros<uint64_t>::Trailing(
static_cast<uint64_t>(value));
178280 }
178281};
178282
178283template <>
178284struct CountZeros<hugeint_t> {
178285 inline static idx_t Leading(hugeint_t value) {
178287 const uint64_t lower = value.lower;
178288
178289 if (upper) {
178290 return CountZeros<uint64_t>::Leading(upper);
178291 } else if (lower) {
178292 return 64 + CountZeros<uint64_t>::Leading(lower);
178293 } else {
178294 return 128;
178295 }
178296 }
178297
178298 inline static idx_t Trailing(hugeint_t value) {
178300 const uint64_t lower = value.lower;
178301
178302 if (lower) {
178303 return CountZeros<uint64_t>::Trailing(lower);
178304 } else if (upper) {
178305 return 64 + CountZeros<uint64_t>::Trailing(upper);
178306 } else {
178307 return 128;
178308 }
178309 }
178310};
178311
178312template <>
178313struct CountZeros<uhugeint_t> {
178314 inline static idx_t Leading(uhugeint_t value) {
178316 const uint64_t lower = value.lower;
178317
178318 if (upper) {
178319 return CountZeros<uint64_t>::Leading(upper);
178320 } else if (lower) {
178321 return 64 + CountZeros<uint64_t>::Leading(lower);
178322 } else {
178323 return 128;
178324 }
178325 }
178326
178327 inline static idx_t Trailing(uhugeint_t value) {
178329 const uint64_t lower = value.lower;
178330
178331 if (lower) {
178332 return CountZeros<uint64_t>::Trailing(lower);
178333 } else if (upper) {
178334 return 64 + CountZeros<uint64_t>::Trailing(upper);
178335 } else {
178336 return 128;
178337 }
178338 }
178339};
178340
178341}
178342
178343
178344
178345
178346
178347
178348
178349
178350
178351
178352
178353
178354#include <algorithm>
178355#include <cmath>
178356
178357
178358namespace duckdb {
178359
178361 HLL_V1 = 1,
178363};
178364
178365class Serializer;
178366class Deserializer;
178367
178371class HyperLogLog {
178372public:
178373 static constexpr idx_t P = 6;
178374 static constexpr idx_t Q = 64 - P;
178375 static constexpr idx_t M = 1 << P;
178376 static constexpr double ALPHA = 0.721347520444481703680;
178377
178378 static double GetErrorRate() {
178379 return std::sqrt(PI / 2.0) /
sqrt(M);
178380 }
178381
178382public:
178383 HyperLogLog() {
178384 memset(k, 0, sizeof(k));
178385 }
178386
178388 inline void InsertElement(hash_t h) {
178389 const auto i = h & ((1 << P) - 1);
178390 h >>= P;
178392 const uint8_t z = UnsafeNumericCast<uint8_t>(CountZeros<hash_t>::Trailing(h) + 1);
178393 Update(i, z);
178394 }
178395
178396 inline void Update(const idx_t &i, const uint8_t &z) {
178397 k[i] = MaxValue<uint8_t>(k[i], z);
178398 }
178399
178400 inline uint8_t GetRegister(
const idx_t &i)
const {
178401 return k[i];
178402 }
178403
178404 idx_t Count()
const;
178405
178407 void Merge(const HyperLogLog &other);
178408
178409public:
178411 void Update(Vector &input, Vector &hashes, idx_t count);
178413 unique_ptr<HyperLogLog> Copy() const;
178414
178415 void Serialize(Serializer &serializer) const;
178416 static unique_ptr<HyperLogLog> Deserialize(Deserializer &deserializer);
178417
178419 void ExtractCounts(uint32_t *c) const;
178421 static int64_t EstimateCardinality(uint32_t *c);
178422
178423private:
178425};
178426
178427}
178428
178429
178430namespace duckdb {
178431class Vector;
178432class Serializer;
178433class Deserializer;
178434
178435class DistinctStatistics {
178436public:
178437 DistinctStatistics();
178438 explicit DistinctStatistics(unique_ptr<HyperLogLog> log, idx_t sample_count, idx_t total_count);
178439
178441 unique_ptr<HyperLogLog>
log;
178443 atomic<idx_t> sample_count;
178445 atomic<idx_t> total_count;
178446
178447public:
178448 void Merge(const DistinctStatistics &other);
178449
178450 unique_ptr<DistinctStatistics> Copy() const;
178451
178452 void UpdateSample(Vector &new_data, idx_t count, Vector &hashes);
178453 void Update(Vector &new_data, idx_t count, Vector &hashes);
178454
178455 string ToString() const;
178456 idx_t GetCount()
const;
178457
178458 static bool TypeIsSupported(const LogicalType &type);
178459
178460 void Serialize(Serializer &serializer) const;
178461 static unique_ptr<DistinctStatistics> Deserialize(Deserializer &deserializer);
178462
178463private:
178464 void UpdateInternal(Vector &update, idx_t count, Vector &hashes);
178465
178466private:
178468 static constexpr double BASE_SAMPLE_RATE = 0.1;
178470 static constexpr double INTEGRAL_SAMPLE_RATE = 0.3;
178471};
178472
178473}
178474
178475
178476namespace duckdb {
178477class Serializer;
178478
178479class ColumnStatistics {
178480public:
178481 explicit ColumnStatistics(BaseStatistics stats_p);
178482 ColumnStatistics(BaseStatistics stats_p, unique_ptr<DistinctStatistics> distinct_stats_p);
178483
178484public:
178485 static shared_ptr<ColumnStatistics> CreateEmptyStats(const LogicalType &type);
178486
178487 void Merge(ColumnStatistics &other);
178488
178489 void UpdateDistinctStatistics(Vector &
v, idx_t count, Vector &hashes);
178490
178491 BaseStatistics &Statistics();
178492
178493 bool HasDistinctStats();
178494 DistinctStatistics &DistinctStats();
178495 void SetDistinct(unique_ptr<DistinctStatistics> distinct_stats);
178496
178497 shared_ptr<ColumnStatistics> Copy() const;
178498
178499 void Serialize(Serializer &serializer) const;
178500 static shared_ptr<ColumnStatistics> Deserialize(Deserializer &source);
178501
178502private:
178503 BaseStatistics stats;
178505 unique_ptr<DistinctStatistics> distinct_stats;
178506};
178507
178508}
178509
178510
178511
178512namespace duckdb {
178513class ColumnList;
178514class PersistentTableData;
178515class Serializer;
178516class Deserializer;
178517
178518class TableStatisticsLock {
178519public:
178520 explicit TableStatisticsLock(mutex &l) : guard(l) {
178521 }
178522
178523 lock_guard<mutex> guard;
178524};
178525
178526class TableStatistics {
178527public:
178528 void Initialize(const vector<LogicalType> &types, PersistentTableData &data);
178529 void InitializeEmpty(const vector<LogicalType> &types);
178530 void InitializeEmpty(const TableStatistics &other);
178531
178532 void InitializeAddColumn(TableStatistics &parent, const LogicalType &new_column_type);
178533 void InitializeRemoveColumn(TableStatistics &parent, idx_t removed_column);
178534 void InitializeAlterType(TableStatistics &parent, idx_t changed_idx, const LogicalType &new_type);
178535 void InitializeAddConstraint(TableStatistics &parent);
178536
178537 void MergeStats(TableStatistics &other);
178538 void MergeStats(idx_t i, BaseStatistics &stats);
178539 void MergeStats(TableStatisticsLock &lock, idx_t i, BaseStatistics &stats);
178540
178541 void SetStats(TableStatistics &other);
178542 void CopyStats(TableStatistics &other);
178543 void CopyStats(TableStatisticsLock &lock, TableStatistics &other);
178544 unique_ptr<BaseStatistics> CopyStats(const StorageIndex &i);
178547 ColumnStatistics &GetStats(TableStatisticsLock &lock, idx_t i);
178549
178551 unique_ptr<BlockingSample> GetTableSample(TableStatisticsLock &lock);
178552 void SetTableSample(TableStatisticsLock &lock, unique_ptr<BlockingSample> sample);
178553
178554 void DestroyTableSample(TableStatisticsLock &lock) const;
178555 void AppendToTableSample(TableStatisticsLock &lock, unique_ptr<BlockingSample> sample);
178556
178557 bool Empty();
178558
178559 unique_ptr<TableStatisticsLock> GetLock();
178560
178561 void Serialize(Serializer &serializer) const;
178562 void Deserialize(Deserializer &deserializer, ColumnList &columns);
178563
178564private:
178566 shared_ptr<mutex> stats_lock;
178568 vector<shared_ptr<ColumnStatistics>> column_stats;
178570 unique_ptr<BlockingSample> table_sample;
178571};
178572
178573}
178574
178575
178576
178577
178578
178579
178580
178581
178582
178583
178584
178585
178586
178587
178588
178589
178590
178591namespace duckdb {
178592class DatabaseInstance;
178593struct MetadataBlockInfo;
178594
178595struct MetadataBlock {
178596 MetadataBlock();
178597
178598 MetadataBlock(const MetadataBlock &other) = delete;
178599 MetadataBlock &
operator=(
const MetadataBlock &) =
delete;
178601 DUCKDB_API MetadataBlock(MetadataBlock &&other) noexcept;
178602 DUCKDB_API MetadataBlock &
operator=(MetadataBlock &&) noexcept;
178603
178604 shared_ptr<BlockHandle> block;
178605 block_id_t block_id;
178606 vector<uint8_t> free_blocks;
178607 atomic<bool> dirty;
178608
178609 void Write(WriteStream &sink);
178610 static MetadataBlock Read(ReadStream &source);
178611
178612 idx_t FreeBlocksToInteger();
178613 void FreeBlocksFromInteger(idx_t blocks);
178614 static vector<uint8_t> BlocksFromInteger(idx_t free_list);
178615
178616 string ToString() const;
178617};
178618
178619struct MetadataPointer {
178620 idx_t block_index : 56;
178622};
178623
178624struct MetadataHandle {
178625 MetadataPointer pointer;
178626 BufferHandle handle;
178627};
178628
178629class MetadataManager {
178630public:
178632 static constexpr const idx_t METADATA_BLOCK_COUNT = 64;
178633
178634public:
178635 MetadataManager(BlockManager &block_manager, BufferManager &buffer_manager);
178636 ~MetadataManager();
178637
178638 BufferManager &GetBufferManager() const {
178639 return buffer_manager;
178640 }
178641
178642 MetadataHandle AllocateHandle();
178643 MetadataHandle Pin(const MetadataPointer &pointer);
178644
178645 MetadataHandle Pin(const QueryContext &context, const MetadataPointer &pointer);
178646
178647 MetaBlockPointer GetDiskPointer(const MetadataPointer &pointer, uint32_t offset = 0);
178648 MetadataPointer FromDiskPointer(MetaBlockPointer pointer);
178649 MetadataPointer RegisterDiskPointer(MetaBlockPointer pointer);
178650
178651 static BlockPointer ToBlockPointer(MetaBlockPointer meta_pointer, const idx_t metadata_block_size);
178652 static MetaBlockPointer FromBlockPointer(BlockPointer block_pointer, const idx_t metadata_block_size);
178653
178655 void Flush();
178656
178657 bool BlockHasBeenCleared(const MetaBlockPointer &ptr);
178658
178659 void MarkBlocksAsModified();
178660 void ClearModifiedBlocks(const vector<MetaBlockPointer> &pointers);
178661
178662 vector<MetadataBlockInfo> GetMetadataInfo() const;
178663 vector<shared_ptr<BlockHandle>> GetBlocks() const;
178664 idx_t BlockCount();
178665
178666 void Write(WriteStream &sink);
178667 void Read(ReadStream &source);
178668
178669 idx_t GetMetadataBlockSize()
const;
178670
178671protected:
178672 BlockManager &block_manager;
178673 BufferManager &buffer_manager;
178674 mutable mutex block_lock;
178675 unordered_map<block_id_t, MetadataBlock> blocks;
178676 unordered_map<block_id_t, idx_t> modified_blocks;
178677
178678protected:
178679 block_id_t AllocateNewBlock(unique_lock<mutex> &block_lock);
178680 block_id_t PeekNextBlockId() const;
178681 block_id_t GetNextBlockId() const;
178682
178683 void AddBlock(unique_lock<mutex> &block_lock, MetadataBlock new_block, bool if_exists = false);
178684 void AddAndRegisterBlock(unique_lock<mutex> &block_lock, MetadataBlock block);
178685 void ConvertToTransient(unique_lock<mutex> &block_lock, MetadataBlock &block);
178686 MetadataPointer FromDiskPointerInternal(unique_lock<mutex> &block_lock, MetaBlockPointer pointer);
178687};
178688
178689}
178690
178691
178692namespace duckdb {
178693class BaseStatistics;
178694
178695class PersistentTableData {
178696public:
178697 explicit PersistentTableData(idx_t column_count);
178698 ~PersistentTableData();
178699
178700 MetaBlockPointer base_table_pointer;
178701 vector<MetaBlockPointer> read_metadata_pointers;
178702 TableStatistics table_stats;
178704 idx_t row_group_count;
178705 MetaBlockPointer block_pointer;
178706};
178707
178708}
178709
178710
178711
178712
178713
178714
178715
178716
178717
178718
178719
178720
178721
178722
178723
178724
178725
178726
178727
178728
178729
178730
178731
178732
178733
178734
178735
178736
178737
178738
178739
178740
178741
178742
178743
178744
178745namespace duckdb {
178746
178747enum class ScanVectorType { SCAN_ENTIRE_VECTOR, SCAN_FLAT_VECTOR };
178748
178749}
178750
178751
178752
178753
178754
178755
178756
178757
178758
178759
178760
178761
178762
178763
178764
178765
178766
178767
178768
178769
178770
178771
178772
178773
178774
178775namespace duckdb {
178776class DatabaseInstance;
178777class ColumnData;
178778struct ColumnDataCheckpointData;
178779class ColumnSegment;
178780class SegmentStatistics;
178781class TableFilter;
178782struct TableFilterState;
178783struct ColumnSegmentState;
178784struct ColumnFetchState;
178785struct ColumnScanState;
178786struct PrefetchState;
178787struct SegmentScanState;
178788
178789class CompressionInfo {
178790public:
178791 explicit CompressionInfo(BlockManager &block_manager) : block_manager(block_manager) {
178792 }
178793
178794public:
178796 idx_t GetCompactionFlushLimit()
const {
178797 return block_manager.GetBlockSize() / 5 * 4;
178798 }
178800 idx_t GetBlockSize()
const {
178801 return block_manager.GetBlockSize();
178802 }
178803
178805 idx_t GetBlockHeaderSize()
const {
178806 return block_manager.GetBlockHeaderSize();
178807 }
178808
178809 BlockManager &GetBlockManager() const {
178810 return block_manager;
178811 }
178812
178813private:
178814 BlockManager &block_manager;
178815};
178816
178817struct AnalyzeState {
178818 explicit AnalyzeState(const CompressionInfo &info) : info(info) {};
178819 virtual ~AnalyzeState() {
178820 }
178821
178822 template <class TARGET>
178823 TARGET &Cast() {
178824 DynamicCastCheck<TARGET>(this);
178825 return reinterpret_cast<TARGET &>(*this);
178826 }
178827 template <class TARGET>
178828 const TARGET &Cast() const {
178829 DynamicCastCheck<TARGET>(this);
178830 return reinterpret_cast<const TARGET &>(*this);
178831 }
178832
178833 CompressionInfo info;
178834};
178835
178836struct CompressionState {
178837 explicit CompressionState(const CompressionInfo &info) : info(info) {};
178838 virtual ~CompressionState() {
178839 }
178840
178841 template <class TARGET>
178842 TARGET &Cast() {
178843 DynamicCastCheck<TARGET>(this);
178844 return reinterpret_cast<TARGET &>(*this);
178845 }
178846 template <class TARGET>
178847 const TARGET &Cast() const {
178848 DynamicCastCheck<TARGET>(this);
178849 return reinterpret_cast<const TARGET &>(*this);
178850 }
178851
178852 CompressionInfo info;
178853};
178854
178855struct CompressedSegmentState {
178856 virtual ~CompressedSegmentState() {
178857 }
178858
178860 virtual string GetSegmentInfo() const {
178861 return "";
178862 }
178863
178864 template <class TARGET>
178865 TARGET &Cast() {
178866 DynamicCastCheck<TARGET>(this);
178867 return reinterpret_cast<TARGET &>(*this);
178868 }
178869 template <class TARGET>
178870 const TARGET &Cast() const {
178871 DynamicCastCheck<TARGET>(this);
178872 return reinterpret_cast<const TARGET &>(*this);
178873 }
178874};
178875
178876struct CompressionAppendState {
178877 explicit CompressionAppendState(BufferHandle handle_p) : handle(std::move(handle_p)) {
178878 }
178879 virtual ~CompressionAppendState() {
178880 }
178881
178882 BufferHandle handle;
178883
178884 template <class TARGET>
178885 TARGET &Cast() {
178886 DynamicCastCheck<TARGET>(this);
178887 return reinterpret_cast<TARGET &>(*this);
178888 }
178889 template <class TARGET>
178890 const TARGET &Cast() const {
178891 DynamicCastCheck<TARGET>(this);
178892 return reinterpret_cast<const TARGET &>(*this);
178893 }
178894};
178895
178896
178897
178898
178906
178908typedef unique_ptr<AnalyzeState> (*compression_init_analyze_t)(ColumnData &col_data,
PhysicalType type);
178909typedef bool (*compression_analyze_t)(AnalyzeState &state, Vector &input,
idx_t count);
178910typedef idx_t (*compression_final_analyze_t)(AnalyzeState &state);
178911
178912
178913
178914
178915typedef unique_ptr<CompressionState> (*compression_init_compression_t)(ColumnDataCheckpointData &checkpoint_data,
178916 unique_ptr<AnalyzeState> state);
178917typedef void (*compression_compress_data_t)(CompressionState &state, Vector &scan_vector,
idx_t count);
178918typedef void (*compression_compress_finalize_t)(CompressionState &state);
178919
178920
178921
178922
178923typedef void (*compression_init_prefetch_t)(ColumnSegment &segment, PrefetchState &prefetch_state);
178924typedef unique_ptr<SegmentScanState> (*compression_init_segment_scan_t)(const QueryContext &context,
178925 ColumnSegment &segment);
178926
178928typedef void (*compression_scan_vector_t)(ColumnSegment &segment, ColumnScanState &state,
idx_t scan_count,
178929 Vector &result);
178931typedef void (*compression_scan_partial_t)(ColumnSegment &segment, ColumnScanState &state,
idx_t scan_count,
178932 Vector &result,
idx_t result_offset);
178934typedef void (*compression_select_t)(ColumnSegment &segment, ColumnScanState &state,
idx_t vector_count, Vector &result,
178935 const SelectionVector &sel,
idx_t sel_count);
178937typedef void (*compression_filter_t)(ColumnSegment &segment, ColumnScanState &state,
idx_t vector_count, Vector &result,
178938 SelectionVector &sel,
idx_t &sel_count,
const TableFilter &
filter,
178939 TableFilterState &filter_state);
178941typedef void (*compression_fetch_row_t)(ColumnSegment &segment, ColumnFetchState &state,
row_t row_id, Vector &result,
178942 idx_t result_idx);
178945typedef void (*compression_skip_t)(ColumnSegment &segment, ColumnScanState &state,
idx_t skip_count);
178946
178947
178948
178949
178950typedef unique_ptr<CompressedSegmentState> (*compression_init_segment_t)(
178951 ColumnSegment &segment, block_id_t block_id, optional_ptr<ColumnSegmentState> segment_state);
178952typedef unique_ptr<CompressionAppendState> (*compression_init_append_t)(ColumnSegment &segment);
178953typedef idx_t (*compression_append_t)(CompressionAppendState &append_state, ColumnSegment &segment,
178954 SegmentStatistics &stats, UnifiedVectorFormat &data,
idx_t offset,
idx_t count);
178955typedef idx_t (*compression_finalize_append_t)(ColumnSegment &segment, SegmentStatistics &stats);
178956typedef void (*compression_revert_append_t)(ColumnSegment &segment,
idx_t new_count);
178957
178958
178959
178960
178962typedef unique_ptr<ColumnSegmentState> (*compression_serialize_state_t)(ColumnSegment &segment);
178964typedef unique_ptr<ColumnSegmentState> (*compression_deserialize_state_t)(Deserializer &deserializer);
178966typedef void (*compression_visit_block_ids_t)(const ColumnSegment &segment, BlockIdVisitor &visitor);
178967
178968
178969
178970
178972typedef InsertionOrderPreservingMap<string> (*compression_get_segment_info_t)(QueryContext context,
178973 ColumnSegment &segment);
178974
178975enum class CompressionValidity :
uint8_t { REQUIRES_VALIDITY, NO_VALIDITY_REQUIRED };
178976
178977class CompressionFunction {
178978public:
178979 CompressionFunction(CompressionType type, PhysicalType data_type, compression_init_analyze_t init_analyze,
178980 compression_analyze_t analyze, compression_final_analyze_t final_analyze,
178981 compression_init_compression_t init_compression, compression_compress_data_t compress,
178982 compression_compress_finalize_t compress_finalize, compression_init_segment_scan_t init_scan,
178983 compression_scan_vector_t scan_vector, compression_scan_partial_t scan_partial,
178984 compression_fetch_row_t fetch_row, compression_skip_t skip,
178985 compression_init_segment_t init_segment = nullptr,
178986 compression_init_append_t init_append = nullptr, compression_append_t append = nullptr,
178987 compression_finalize_append_t finalize_append = nullptr,
178988 compression_revert_append_t revert_append = nullptr,
178989 compression_serialize_state_t serialize_state = nullptr,
178990 compression_deserialize_state_t deserialize_state = nullptr,
178991 compression_visit_block_ids_t visit_block_ids = nullptr,
178992 compression_init_prefetch_t init_prefetch = nullptr, compression_select_t select = nullptr,
178993 compression_filter_t filter = nullptr)
178994 : type(type), data_type(data_type), init_analyze(init_analyze), analyze(analyze), final_analyze(final_analyze),
178995 init_compression(init_compression), compress(compress), compress_finalize(compress_finalize),
178996 init_prefetch(init_prefetch), init_scan(init_scan), scan_vector(scan_vector), scan_partial(scan_partial),
178998 init_append(init_append), append(append), finalize_append(finalize_append), revert_append(revert_append),
178999 serialize_state(serialize_state), deserialize_state(deserialize_state), visit_block_ids(visit_block_ids) {
179000 }
179001
179003 CompressionType type;
179006
179013 compression_analyze_t analyze;
179018 compression_final_analyze_t final_analyze;
179019
179022 compression_init_compression_t init_compression;
179024 compression_compress_data_t compress;
179026 compression_compress_finalize_t compress_finalize;
179027
179029 compression_init_prefetch_t init_prefetch;
179031 compression_init_segment_scan_t init_scan;
179047
179048
179050
179052 compression_init_segment_t init_segment;
179054 compression_init_append_t init_append;
179056 compression_append_t append;
179058 compression_finalize_append_t finalize_append;
179060 compression_revert_append_t revert_append;
179061
179062
179064
179071
179072
179075
179078
179081 CompressionValidity validity = CompressionValidity::REQUIRES_VALIDITY;
179082};
179083
179085struct CompressionFunctionSet {
179086 static constexpr idx_t COMPRESSION_TYPE_COUNT = 16;
179087 static constexpr idx_t PHYSICAL_TYPE_COUNT = 19;
179088
179089public:
179090 CompressionFunctionSet();
179091
179092 vector<reference<const CompressionFunction>> GetCompressionFunctions(PhysicalType physical_type);
179093 optional_ptr<const CompressionFunction> GetCompressionFunction(CompressionType type, PhysicalType physical_type);
179094 void SetDisabledCompressionMethods(const vector<CompressionType> &methods);
179095 vector<CompressionType> GetDisabledCompressionMethods() const;
179096
179097private:
179098 atomic<bool> is_disabled[COMPRESSION_TYPE_COUNT];
179099 vector<vector<CompressionFunction>> functions;
179100
179101private:
179102 static idx_t GetCompressionIndex(PhysicalType physical_type);
179103 static idx_t GetCompressionIndex(CompressionType type);
179104 void ResetDisabledMethods();
179105};
179106
179107}
179108
179109
179110
179111
179112
179113
179114namespace duckdb {
179115
179116class BaseStatistics;
179117class BlockManager;
179118class ColumnData;
179119class ColumnSegment;
179120class DatabaseInstance;
179121class TableFilter;
179122class Transaction;
179123class UpdateSegment;
179124struct ColumnAppendState;
179125struct ColumnFetchState;
179126struct ColumnScanState;
179127struct PrefetchState;
179128struct TableFilterState;
179129
179130enum class ColumnSegmentType :
uint8_t { TRANSIENT, PERSISTENT };
179132
179133class ColumnSegment : public SegmentBase<ColumnSegment> {
179134public:
179136 ColumnSegment(DatabaseInstance &db, shared_ptr<BlockHandle> block, const LogicalType &type,
179137 const ColumnSegmentType segment_type, const idx_t count, const CompressionFunction &function_p,
179138 BaseStatistics statistics, const block_id_t block_id_p, const idx_t offset,
179139 const idx_t segment_size_p, unique_ptr<ColumnSegmentState> segment_state_p = nullptr);
179142 ColumnSegment(ColumnSegment &other);
179143 ~ColumnSegment();
179144
179145public:
179146 static unique_ptr<ColumnSegment> CreatePersistentSegment(DatabaseInstance &db, BlockManager &block_manager,
179147 block_id_t id, idx_t offset, const LogicalType &type_p,
179148 idx_t count, CompressionType compression_type,
179149 BaseStatistics statistics,
179150 unique_ptr<ColumnSegmentState> segment_state);
179151 static unique_ptr<ColumnSegment> CreateTransientSegment(DatabaseInstance &db, const CompressionFunction &function,
179152 const LogicalType &type, const idx_t segment_size,
179153 BlockManager &block_manager);
179154
179155public:
179156 void InitializePrefetch(PrefetchState &prefetch_state, ColumnScanState &scan_state);
179157 void InitializeScan(ColumnScanState &state);
179159 void Scan(ColumnScanState &state, idx_t scan_count, Vector &result, idx_t result_offset, ScanVectorType scan_type);
179161 void Select(ColumnScanState &state, idx_t scan_count, Vector &result, const SelectionVector &sel, idx_t sel_count);
179163 void Filter(ColumnScanState &state, idx_t scan_count, Vector &result, SelectionVector &sel, idx_t &sel_count,
179164 const TableFilter &filter, TableFilterState &filter_state);
179166 void FetchRow(ColumnFetchState &state, row_t row_id, Vector &result, idx_t result_idx);
179167
179168 static idx_t FilterSelection(SelectionVector &sel, Vector &vector, UnifiedVectorFormat &vdata,
179169 const TableFilter &filter, TableFilterState &filter_state, idx_t scan_count,
179170 idx_t &approved_tuple_count);
179171
179173 void Skip(ColumnScanState &state);
179174
179175
179176 idx_t SegmentSize()
const;
179178 void Resize(idx_t segment_size);
179179 const CompressionFunction &GetCompressionFunction();
179180
179182 void InitializeAppend(ColumnAppendState &state);
179184 idx_t Append(ColumnAppendState &state, UnifiedVectorFormat &data, idx_t offset, idx_t count);
179188 idx_t FinalizeAppend(ColumnAppendState &state);
179190 void RevertAppend(idx_t new_count);
179191
179194 void ConvertToPersistent(QueryContext context, optional_ptr<BlockManager> block_manager, const block_id_t block_id);
179197 void MarkAsPersistent(shared_ptr<BlockHandle> block, uint32_t offset_in_block);
179198 void SetBlock(shared_ptr<BlockHandle> block, uint32_t offset);
179200 DataPointer GetDataPointer(idx_t row_start);
179201
179202 block_id_t GetBlockId() {
179203 D_ASSERT(segment_type == ColumnSegmentType::PERSISTENT);
179204 return block_id;
179205 }
179206
179208 idx_t GetBlockSize()
const {
179209 return block->GetBlockSize();
179210 }
179211
179212 idx_t GetBlockOffset() {
179213 D_ASSERT(segment_type == ColumnSegmentType::PERSISTENT || offset == 0);
179214 return offset;
179215 }
179216
179217 optional_ptr<CompressedSegmentState> GetSegmentState() const {
179218 return segment_state.get();
179219 }
179220
179221 void VisitBlockIds(BlockIdVisitor &visitor) const;
179222
179223private:
179224 void Scan(ColumnScanState &state, idx_t scan_count, Vector &result);
179225 void ScanPartial(ColumnScanState &state, idx_t scan_count, Vector &result, idx_t result_offset);
179226
179227public:
179229 DatabaseInstance &
db;
179231 LogicalType type;
179235 ColumnSegmentType segment_type;
179237 SegmentStatistics stats;
179239 shared_ptr<BlockHandle> block;
179240
179241private:
179243 reference<const CompressionFunction> function;
179245 block_id_t block_id;
179249 idx_t segment_size;
179251 unique_ptr<CompressedSegmentState> segment_state;
179252};
179253
179254}
179255
179256
179257namespace duckdb {
179258
179259class ColumnSegmentTree : public SegmentTree<ColumnSegment> {};
179260
179261}
179262
179263
179264
179265
179266
179267
179268
179269
179270
179271
179272
179273
179274
179275
179276
179277
179278
179279
179280
179281namespace duckdb {
179282
179283template <class T, bool SAFE = true>
179284class atomic_ptr {
179285public:
179286 atomic_ptr() noexcept : ptr(nullptr) {
179287 }
179288 atomic_ptr(T *ptr_p) : ptr(ptr_p) {
179289 }
179290 atomic_ptr(T &ref) : ptr(&ref) {
179291 }
179292 atomic_ptr(
const unique_ptr<T> &ptr_p) : ptr(ptr_p.
get()) {
179293 }
179294 atomic_ptr(
const shared_ptr<T> &ptr_p) : ptr(ptr_p.
get()) {
179295 }
179296
179297 void CheckValid(const T *ptr) const {
179298 if (MemorySafety<SAFE>::ENABLED) {
179299 return;
179300 }
179301 if (!ptr) {
179302 throw InternalException("Attempting to dereference an optional pointer that is not set");
179303 }
179304 }
179305
179306 T *GetPointer() {
179307 auto res = ptr.load();
179308 CheckValid(res);
179309 return res;
179310 }
179311
179312 const T *GetPointer() const {
179313 auto res = ptr.load();
179314 CheckValid(res);
179315 return res;
179316 }
179317
179318 operator bool() const {
179319 return ptr;
179320 }
179322 return *GetPointer();
179323 }
179325 return *GetPointer();
179326 }
179327 T *operator->() {
179328 return GetPointer();
179329 }
179330 const T *operator->() const {
179331 return GetPointer();
179332 }
179334 return GetPointer();
179335 }
179336 const T *
get()
const {
179337 return GetPointer();
179338 }
179339
179340 T *get_mutable() const {
179341 return GetPointer();
179342 }
179343
179344 void set(T &ref) {
179345 ptr = &ref;
179346 }
179347
179348 void reset() {
179349 ptr = nullptr;
179350 }
179351
179352 bool operator==(
const atomic_ptr<T> &rhs)
const {
179353 return ptr.load() == rhs.ptr.load();
179354 }
179355
179356 bool operator!=(
const atomic_ptr<T> &rhs)
const {
179357 return ptr.load() != rhs.ptr.load();
179358 }
179359
179360private:
179361 atomic<T *> ptr;
179362};
179363
179364template <typename T>
179365using unsafe_atomic_ptr = atomic_ptr<T, false>;
179366
179367}
179368
179369
179370namespace duckdb {
179371class ColumnData;
179372class ColumnSegment;
179373class DatabaseInstance;
179374class RowGroup;
179375class RowGroupWriter;
179376class StorageManager;
179377class TableDataWriter;
179378class TableStorageInfo;
179379struct DataTableInfo;
179380struct PrefetchState;
179381struct RowGroupWriteInfo;
179382struct TableScanOptions;
179383struct TransactionData;
179384struct PersistentColumnData;
179385class ValidityColumnData;
179386
179387using column_segment_vector_t = vector<SegmentNode<ColumnSegment>>;
179388
179389struct ColumnCheckpointInfo {
179390 ColumnCheckpointInfo(RowGroupWriteInfo &info, idx_t column_idx);
179391
179393
179394public:
179395 PartialBlockManager &GetPartialBlockManager();
179396 CompressionType GetCompressionType();
179397
179398private:
179399 RowGroupWriteInfo &info;
179400};
179401
179402enum class ColumnDataType { MAIN_TABLE, INITIAL_TRANSACTION_LOCAL, TRANSACTION_LOCAL, CHECKPOINT_TARGET };
179403
179404class ColumnData : public enable_shared_from_this<ColumnData> {
179405 friend class ColumnDataCheckpointer;
179406
179407public:
179408 ColumnData(BlockManager &block_manager, DataTableInfo &info, idx_t column_index, LogicalType type,
179409 ColumnDataType data_type, optional_ptr<ColumnData> parent);
179410 virtual ~ColumnData();
179411
179413 atomic<idx_t> count;
179415 BlockManager &block_manager;
179417 DataTableInfo &info;
179419 idx_t column_index;
179421 LogicalType type;
179422
179423public:
179424 virtual FilterPropagateResult CheckZonemap(ColumnScanState &state, TableFilter &filter);
179425
179426 BlockManager &GetBlockManager() const {
179427 return block_manager;
179428 }
179429 DatabaseInstance &GetDatabase() const;
179430 DataTableInfo &GetTableInfo() const;
179431 StorageManager &GetStorageManager() const;
179432 virtual idx_t GetMaxEntry();
179433
179434 idx_t GetAllocationSize()
const {
179435 return allocation_size;
179436 }
179437 optional_ptr<const CompressionFunction> GetCompressionFunction() const {
179438 return compression.get();
179439 }
179440 virtual void SetDataType(ColumnDataType data_type);
179441 ColumnDataType GetDataType() const {
179442 return data_type;
179443 }
179444
179445 bool HasParent() const {
179446 return parent;
179447 }
179448 void SetParent(optional_ptr<ColumnData> parent) {
179449 this->parent = parent;
179450 }
179451 const ColumnData &Parent() const {
179452 D_ASSERT(HasParent());
179453 return *parent;
179454 }
179455
179456 virtual const BaseStatistics &GetChildStats(const ColumnData &child) const;
179457
179458 const LogicalType &GetType() const {
179459 return type;
179460 }
179461 ColumnSegmentTree &GetSegmentTree() {
179462 return data;
179463 }
179464 void SetCount(idx_t new_count) {
179465 this->count = new_count;
179466 }
179467
179469 bool HasUpdates() const;
179470 bool HasChanges(idx_t start_row, idx_t end_row) const;
179472 bool HasChanges() const;
179473
179475 virtual bool HasAnyChanges() const;
179477 virtual ScanVectorType GetVectorScanType(ColumnScanState &state, idx_t scan_count, Vector &result);
179478
179480 virtual void InitializePrefetch(PrefetchState &prefetch_state, ColumnScanState &scan_state, idx_t
rows);
179482 virtual void InitializeScan(ColumnScanState &state);
179484 virtual void InitializeScanWithOffset(ColumnScanState &state, idx_t row_idx);
179486 idx_t Scan(TransactionData transaction, idx_t vector_index, ColumnScanState &state, Vector &result);
179487 virtual idx_t Scan(TransactionData transaction, idx_t vector_index, ColumnScanState &state, Vector &result,
179488 idx_t scan_count);
179489
179490 virtual void ScanCommittedRange(idx_t row_group_start, idx_t offset_in_row_group, idx_t count, Vector &result);
179491 virtual idx_t ScanCount(ColumnScanState &state, Vector &result, idx_t count, idx_t result_offset = 0);
179492
179494 virtual void Filter(TransactionData transaction, idx_t vector_index, ColumnScanState &state, Vector &result,
179495 SelectionVector &sel, idx_t &count, const TableFilter &filter, TableFilterState &filter_state);
179496 virtual void Select(TransactionData transaction, idx_t vector_index, ColumnScanState &state, Vector &result,
179497 SelectionVector &sel, idx_t count);
179498
179500 virtual void Skip(ColumnScanState &state, idx_t count = STANDARD_VECTOR_SIZE);
179501
179503 virtual void InitializeAppend(ColumnAppendState &state);
179505 virtual void Append(BaseStatistics &stats, ColumnAppendState &state, Vector &vector, idx_t count);
179507 void Append(ColumnAppendState &state, Vector &vector, idx_t count);
179508 virtual void AppendData(BaseStatistics &stats, ColumnAppendState &state, UnifiedVectorFormat &vdata, idx_t count);
179510 virtual void RevertAppend(row_t new_count);
179511
179513 virtual idx_t Fetch(ColumnScanState &state, row_t row_id, Vector &result);
179515 virtual void FetchRow(TransactionData transaction, ColumnFetchState &state, const StorageIndex &storage_index,
179516 row_t row_id, Vector &result, idx_t result_idx);
179517
179518 virtual void Update(TransactionData transaction, DataTable &data_table, idx_t column_index, Vector &update_vector,
179519 row_t *row_ids, idx_t update_count, idx_t row_group_start);
179520 virtual void UpdateColumn(TransactionData transaction, DataTable &data_table, const vector<column_t> &column_path,
179521 Vector &update_vector, row_t *row_ids, idx_t update_count, idx_t depth,
179522 idx_t row_group_start);
179523 virtual unique_ptr<BaseStatistics> GetUpdateStatistics();
179524
179525 virtual void VisitBlockIds(BlockIdVisitor &visitor) const;
179526
179527 virtual unique_ptr<ColumnCheckpointState> CreateCheckpointState(const RowGroup &row_group,
179528 PartialBlockManager &partial_block_manager);
179531 unique_ptr<ColumnCheckpointState> Checkpoint(const RowGroup &row_group, ColumnCheckpointInfo &info);
179532 virtual unique_ptr<ColumnCheckpointState> Checkpoint(const RowGroup &row_group, ColumnCheckpointInfo &info,
179533 const BaseStatistics &stats);
179534
179535 virtual void CheckpointScan(ColumnSegment &segment, ColumnScanState &state, idx_t count, Vector &scan_vector) const;
179536
179537 virtual bool IsPersistent();
179538 vector<DataPointer> GetDataPointers();
179539
179540 virtual PersistentColumnData Serialize();
179541 void InitializeColumn(PersistentColumnData &column_data);
179542 virtual void InitializeColumn(PersistentColumnData &column_data, BaseStatistics &target_stats);
179543 static shared_ptr<ColumnData> Deserialize(BlockManager &block_manager, DataTableInfo &info, idx_t column_index,
179544 ReadStream &source, const LogicalType &type);
179545
179546 virtual void GetColumnSegmentInfo(const QueryContext &context, idx_t row_group_index, vector<idx_t> col_path,
179547 vector<ColumnSegmentInfo> &result);
179548 virtual void Verify(RowGroup &parent);
179549
179550 FilterPropagateResult CheckZonemap(const StorageIndex &index, TableFilter &filter);
179551
179552 static shared_ptr<ColumnData> CreateColumn(BlockManager &block_manager, DataTableInfo &info, idx_t column_index,
179553 const LogicalType &type,
179554 ColumnDataType data_type = ColumnDataType::MAIN_TABLE,
179555 optional_ptr<ColumnData> parent = nullptr);
179556
179557 void MergeStatistics(const BaseStatistics &other);
179558 void MergeIntoStatistics(BaseStatistics &other);
179559 unique_ptr<BaseStatistics> GetStatistics() const;
179560 const BaseStatistics &GetStatisticsRef() const;
179561
179562protected:
179564 void AppendTransientSegment(SegmentLock &l, idx_t start_row);
179565 void AppendSegment(SegmentLock &l, unique_ptr<ColumnSegment> segment);
179566
179567 void BeginScanVectorInternal(ColumnScanState &state);
179569 idx_t ScanVector(ColumnScanState &state, Vector &result, idx_t remaining, ScanVectorType scan_type,
179570 idx_t result_offset = 0);
179572 idx_t ScanVector(TransactionData transaction, idx_t vector_index, ColumnScanState &state, Vector &result,
179573 idx_t target_scan, ScanVectorType scan_type, UpdateScanType update_type);
179574 idx_t ScanVector(TransactionData transaction, idx_t vector_index, ColumnScanState &state, Vector &result,
179575 idx_t target_scan, UpdateScanType update_type);
179576 void SelectVector(ColumnScanState &state, Vector &result, idx_t target_count, const SelectionVector &sel,
179577 idx_t sel_count);
179578 void FilterVector(ColumnScanState &state, Vector &result, idx_t target_count, SelectionVector &sel,
179579 idx_t &sel_count, const TableFilter &filter, TableFilterState &filter_state);
179580
179581 void FetchUpdates(TransactionData transaction, idx_t vector_index, Vector &result, idx_t scan_count,
179582 UpdateScanType update_type);
179583 void FetchUpdateRow(TransactionData transaction, row_t row_id, Vector &result, idx_t result_idx);
179584 void UpdateInternal(TransactionData transaction, DataTable &data_table, idx_t column_index, Vector &update_vector,
179585 row_t *row_ids, idx_t update_count, Vector &base_vector, idx_t row_group_start);
179586 idx_t FetchUpdateData(ColumnScanState &state, row_t *row_ids, Vector &base_vector, idx_t row_group_start);
179587
179588 idx_t GetVectorCount(idx_t vector_index)
const;
179589
179590private:
179591 void UpdateCompressionFunction(SegmentLock &l, const CompressionFunction &function);
179592
179593protected:
179595 ColumnSegmentTree data;
179597 mutable mutex update_lock;
179599 unique_ptr<UpdateSegment> updates;
179601 mutable mutex stats_lock;
179603 atomic<idx_t> allocation_size;
179605 unique_ptr<SegmentStatistics> stats;
179606
179607private:
179609 atomic<ColumnDataType> data_type;
179611 optional_ptr<ColumnData> parent;
179614 atomic_ptr<const CompressionFunction> compression;
179615
179616public:
179617 template <class TARGET>
179618 TARGET &Cast() {
179619 DynamicCastCheck<TARGET>(this);
179620 return reinterpret_cast<TARGET &>(*this);
179621 }
179622 template <class TARGET>
179623 const TARGET &Cast() const {
179624 DynamicCastCheck<TARGET>(this);
179625 return reinterpret_cast<const TARGET &>(*this);
179626 }
179627};
179628
179629enum class ExtraPersistentColumnDataType :
uint8_t {
179630 INVALID = 0,
179631 VARIANT = 1,
179632 GEOMETRY = 2,
179633};
179634
179635class ExtraPersistentColumnData {
179636public:
179637 ExtraPersistentColumnDataType GetType() const {
179638 return type;
179639 }
179640
179641 virtual ~ExtraPersistentColumnData() = default;
179642
179643 template <class TARGET>
179644 TARGET &Cast() {
179645 D_ASSERT(type == TARGET::TYPE);
179646 DynamicCastCheck<TARGET>(this);
179647 return reinterpret_cast<TARGET &>(*this);
179648 }
179649 template <class TARGET>
179650 const TARGET &Cast() const {
179651 D_ASSERT(type == TARGET::TYPE);
179652 DynamicCastCheck<TARGET>(this);
179653 return reinterpret_cast<const TARGET &>(*this);
179654 }
179655
179656 void Serialize(Serializer &serializer) const;
179657 static unique_ptr<ExtraPersistentColumnData> Deserialize(Deserializer &deserializer);
179658
179659protected:
179660 explicit ExtraPersistentColumnData(ExtraPersistentColumnDataType type_p) : type(type_p) {
179661 }
179662
179663private:
179664 ExtraPersistentColumnDataType type;
179665};
179666
179667class VariantPersistentColumnData final : public ExtraPersistentColumnData {
179668public:
179669 static constexpr auto TYPE = ExtraPersistentColumnDataType::VARIANT;
179670 VariantPersistentColumnData() : ExtraPersistentColumnData(
TYPE) {
179671 }
179672 explicit VariantPersistentColumnData(const LogicalType &storage_type)
179673 : ExtraPersistentColumnData(
TYPE), logical_type(storage_type) {
179674 }
179675
179676 LogicalType logical_type;
179677};
179678
179679class GeometryPersistentColumnData final : public ExtraPersistentColumnData {
179680public:
179681 static constexpr auto TYPE = ExtraPersistentColumnDataType::GEOMETRY;
179682 GeometryPersistentColumnData() : ExtraPersistentColumnData(
TYPE) {
179683 }
179684 explicit GeometryPersistentColumnData(GeometryStorageType storage_type)
179685 : ExtraPersistentColumnData(
TYPE), storage_type(storage_type) {
179686 }
179687
179688 GeometryStorageType storage_type;
179689};
179690
179691struct PersistentColumnData {
179692public:
179693 explicit PersistentColumnData(const LogicalType &logical_type);
179694 PersistentColumnData(const LogicalType &logical_type, vector<DataPointer> pointers);
179695
179696 PersistentColumnData(const PersistentColumnData &other) = delete;
179697 PersistentColumnData &
operator=(
const PersistentColumnData &) =
delete;
179699 PersistentColumnData(PersistentColumnData &&other) noexcept = default;
179700 PersistentColumnData &
operator=(PersistentColumnData &&) =
default;
179701 ~PersistentColumnData();
179702
179703public:
179704 void Serialize(Serializer &serializer) const;
179705 static PersistentColumnData Deserialize(Deserializer &deserializer);
179706 void DeserializeField(Deserializer &deserializer, field_id_t field_idx, const char *field_name,
179707 const LogicalType &type);
179708 bool HasUpdates() const;
179709
179710public:
179711 LogicalType logical_type;
179712 vector<DataPointer> pointers;
179713 vector<PersistentColumnData> child_columns;
179714 bool has_updates = false;
179715
179717 unique_ptr<ExtraPersistentColumnData> extra_data;
179718};
179719
179720struct PersistentRowGroupData {
179721 explicit PersistentRowGroupData(vector<LogicalType> types);
179722 PersistentRowGroupData() = default;
179723
179724 PersistentRowGroupData(const PersistentRowGroupData &other) = delete;
179725 PersistentRowGroupData &
operator=(
const PersistentRowGroupData &) =
delete;
179727 PersistentRowGroupData(PersistentRowGroupData &&other) noexcept = default;
179728 PersistentRowGroupData &
operator=(PersistentRowGroupData &&) =
default;
179729 ~PersistentRowGroupData() = default;
179730
179731 vector<LogicalType> types;
179732 vector<PersistentColumnData> column_data;
179735
179736 void Serialize(Serializer &serializer) const;
179737 static PersistentRowGroupData Deserialize(Deserializer &deserializer);
179738 bool HasUpdates() const;
179739};
179740
179741struct PersistentCollectionData {
179742 PersistentCollectionData() = default;
179743
179744 PersistentCollectionData(const PersistentCollectionData &other) = delete;
179745 PersistentCollectionData &
operator=(
const PersistentCollectionData &) =
delete;
179747 PersistentCollectionData(PersistentCollectionData &&other) noexcept = default;
179748 PersistentCollectionData &
operator=(PersistentCollectionData &&) =
default;
179749 ~PersistentCollectionData() = default;
179750
179751 vector<PersistentRowGroupData> row_group_data;
179752
179753 void Serialize(Serializer &serializer) const;
179754 static PersistentCollectionData Deserialize(Deserializer &deserializer);
179755 bool HasUpdates() const;
179756 vector<block_id_t> GetBlockIds() const;
179757};
179758
179759}
179760
179761
179762
179763namespace duckdb {
179764
179766struct ColumnSegmentInfo {
179767 idx_t row_group_index;
179769 string column_path;
179770 idx_t segment_idx;
179771 string segment_type;
179772 idx_t segment_start;
179773 idx_t segment_count;
179774 string compression_type;
179775 string segment_stats;
179776 bool has_updates;
179777 bool persistent;
179778 block_id_t block_id;
179779 vector<block_id_t> additional_blocks;
179780 idx_t block_offset;
179781 string segment_info;
179782};
179783
179785class TableStorageInfo {
179786public:
179788 optional_idx cardinality;
179790 vector<IndexInfo> index_info;
179791};
179792
179793}
179794
179795
179796namespace duckdb {
179797
179798class ClientContext;
179799class TableIOManager;
179800class Transaction;
179801class ConflictManager;
179802
179803struct IndexLock;
179804struct IndexScanState;
179805
179807class Index {
179808protected:
179809 Index(const vector<column_t> &column_ids, TableIOManager &table_io_manager, AttachedDatabase &db);
179810
179818 vector<column_t> column_ids;
179820 unordered_set<column_t> column_id_set;
179821
179822public:
179824 TableIOManager &table_io_manager;
179826 AttachedDatabase &
db;
179827
179828public:
179829 virtual ~Index() = default;
179830
179832 virtual bool IsBound() const = 0;
179833
179835 virtual const string &GetIndexType() const = 0;
179836
179838 virtual const string &GetIndexName() const = 0;
179839
179841 virtual IndexConstraintType GetConstraintType() const = 0;
179842
179844 bool IsUnique() const {
179845 auto type = GetConstraintType();
179846 return type == IndexConstraintType::UNIQUE || type == IndexConstraintType::PRIMARY;
179847 }
179848
179850 bool IsPrimary() const {
179851 auto index_constraint_type = GetConstraintType();
179852 return (index_constraint_type == IndexConstraintType::PRIMARY);
179853 }
179854
179856 bool IsForeign() const {
179857 auto index_constraint_type = GetConstraintType();
179858 return (index_constraint_type == IndexConstraintType::FOREIGN);
179859 }
179860
179861 const vector<column_t> &GetColumnIds() const {
179862 return column_ids;
179863 }
179864
179865 const unordered_set<column_t> &GetColumnIdSet() const {
179866 return column_id_set;
179867 }
179868
179869
179870 virtual void CommitDrop() = 0;
179871
179872public:
179873 template <class TARGET>
179874 TARGET &Cast() {
179875 DynamicCastCheck<TARGET>(this);
179876 return reinterpret_cast<TARGET &>(*this);
179877 }
179878
179879 template <class TARGET>
179880 const TARGET &Cast() const {
179881 DynamicCastCheck<TARGET>(this);
179882 return reinterpret_cast<const TARGET &>(*this);
179883 }
179884};
179885
179886}
179887
179888
179889
179890
179891
179892
179893
179894
179895
179896
179897
179898
179899
179900
179901
179902
179903
179904
179905
179906
179907
179908
179909
179910
179911
179912
179913
179914
179915
179916
179917
179918
179919
179920
179921
179922
179923
179924
179925
179926
179927
179928
179929
179930
179931
179932
179933
179934
179935
179936
179937
179938
179939
179940
179941
179942
179943
179944
179945
179946
179947
179948namespace duckdb {
179949
179950struct CreateIndexInfo : public CreateInfo {
179951 CreateIndexInfo();
179952 CreateIndexInfo(const CreateIndexInfo &info);
179953
179955 string table;
179957 string index_name;
179958
179960 case_insensitive_map_t<Value> options;
179961
179965 IndexConstraintType constraint_type;
179967 vector<column_t> column_ids;
179969 vector<unique_ptr<ParsedExpression>> expressions;
179970 vector<unique_ptr<ParsedExpression>> parsed_expressions;
179971
179973 vector<LogicalType> scan_types;
179975 vector<string> names;
179976
179977public:
179978 DUCKDB_API unique_ptr<CreateInfo> Copy() const override;
179979 string ToString() const override;
179980 void Serialize(Serializer &serializer) const override;
179981 static unique_ptr<CreateInfo> Deserialize(Deserializer &deserializer);
179982
179983 vector<string> ExpressionsToList() const;
179984 string ExpressionsToString() const;
179985};
179986
179987}
179988
179989
179990
179991
179992namespace duckdb {
179993
179994class ColumnDataCollection;
179995
179996enum class BufferedIndexReplay :
uint8_t { INSERT_ENTRY = 0, DEL_ENTRY = 1 };
179997
179998struct ReplayRange {
179999 BufferedIndexReplay type;
180000
180001
180004 explicit ReplayRange(const BufferedIndexReplay replay_type, const idx_t start_p, const idx_t end_p)
180005 : type(replay_type), start(start_p), end(end_p) {
180006 }
180007};
180008
180009
180010
180011
180012
180013
180014
180015
180016
180017
180018struct BufferedIndexReplays {
180019 vector<ReplayRange> ranges;
180020 unique_ptr<ColumnDataCollection> buffered_inserts;
180021 unique_ptr<ColumnDataCollection> buffered_deletes;
180022
180023 BufferedIndexReplays() = default;
180024
180025 unique_ptr<ColumnDataCollection> &GetBuffer(const BufferedIndexReplay replay_type) {
180026 if (replay_type == BufferedIndexReplay::INSERT_ENTRY) {
180027 return buffered_inserts;
180028 }
180029 return buffered_deletes;
180030 }
180031
180032 bool HasBufferedReplays() const {
180033 return !ranges.empty();
180034 }
180035};
180036
180037class UnboundIndex final : public Index {
180038private:
180040 unique_ptr<CreateInfo> create_info;
180042 IndexStorageInfo storage_info;
180043
180045 BufferedIndexReplays buffered_replays;
180046
180051 vector<StorageIndex> mapped_column_ids;
180052
180053public:
180054 UnboundIndex(unique_ptr<CreateInfo> create_info, IndexStorageInfo storage_info, TableIOManager &table_io_manager,
180055 AttachedDatabase &db);
180056
180057public:
180058 bool IsBound() const override {
180059 return false;
180060 }
180061 const string &GetIndexType() const override {
180062 return GetCreateInfo().index_type;
180063 }
180064 const string &GetIndexName() const override {
180065 return GetCreateInfo().index_name;
180066 }
180067 IndexConstraintType GetConstraintType() const override {
180068 return GetCreateInfo().constraint_type;
180069 }
180070 const CreateIndexInfo &GetCreateInfo() const {
180071 return create_info->Cast<CreateIndexInfo>();
180072 }
180073 const IndexStorageInfo &GetStorageInfo() const {
180074 return storage_info;
180075 }
180076 const vector<unique_ptr<ParsedExpression>> &GetParsedExpressions() const {
180077 return GetCreateInfo().parsed_expressions;
180078 }
180079 const string &GetTableName() const {
180080 return GetCreateInfo().table;
180081 }
180082
180083 void CommitDrop() override;
180084
180088 void BufferChunk(DataChunk &index_column_chunk, Vector &row_ids, const vector<StorageIndex> &mapped_column_ids_p,
180089 BufferedIndexReplay replay_type);
180090 bool HasBufferedReplays() const {
180091 return buffered_replays.HasBufferedReplays();
180092 }
180093
180094 BufferedIndexReplays &GetBufferedReplays() {
180095 return buffered_replays;
180096 }
180097
180098 const vector<StorageIndex> &GetMappedColumnIds() const {
180099 return mapped_column_ids;
180100 }
180101};
180102
180103}
180104
180105
180106
180107
180108
180109
180110
180111
180112
180113
180114
180115namespace duckdb {
180116
180117class ClientContext;
180118class TableIOManager;
180119class Transaction;
180120class ConflictManager;
180121
180122struct IndexLock;
180123struct IndexScanState;
180124
180125enum class IndexAppendMode :
uint8_t { DEFAULT = 0, IGNORE_DUPLICATES = 1, INSERT_DUPLICATES = 2 };
180126
180127class IndexAppendInfo {
180128public:
180129 IndexAppendInfo() : append_mode(IndexAppendMode::DEFAULT) {
180130 }
180131 IndexAppendInfo(const IndexAppendMode append_mode, optional_ptr<BoundIndex> delete_index)
180132 : append_mode(append_mode) {
180133 if (delete_index) {
180134 delete_indexes.push_back(*delete_index);
180135 }
180136 }
180137
180138public:
180139 IndexAppendMode append_mode;
180140 vector<reference<BoundIndex>> delete_indexes;
180141};
180142
180143enum class DeltaIndexType {
180144 NONE,
180145 LOCAL_APPEND,
180146 LOCAL_DELETE,
180147 ADDED_DURING_CHECKPOINT,
180148 REMOVED_DURING_CHECKPOINT,
180149 DELETED_ROWS_IN_USE
180150};
180151
180153class BoundIndex : public Index {
180154public:
180155 BoundIndex(
const string &name,
const string &
index_type, IndexConstraintType index_constraint_type,
180156 const vector<column_t> &column_ids, TableIOManager &table_io_manager,
180157 const vector<unique_ptr<Expression>> &unbound_expressions, AttachedDatabase &db);
180158
180160 vector<PhysicalType> types;
180162 vector<LogicalType> logical_types;
180163
180165 string name;
180169 IndexConstraintType index_constraint_type;
180170
180181 vector<unique_ptr<Expression>> unbound_expressions;
180182
180184 DeltaIndexType delta_index_type = DeltaIndexType::NONE;
180185
180186public:
180187 bool IsBound() const override {
180188 return true;
180189 }
180190 const string &GetIndexType() const override {
180192 }
180193 const string &GetIndexName() const override {
180194 return name;
180195 }
180196 IndexConstraintType GetConstraintType() const override {
180197 return index_constraint_type;
180198 }
180199
180200public:
180202 void InitializeLock(IndexLock &state);
180204 virtual ErrorData Append(IndexLock &l, DataChunk &chunk, Vector &row_ids) = 0;
180206 ErrorData Append(DataChunk &chunk, Vector &row_ids);
180208 virtual ErrorData Append(IndexLock &l, DataChunk &chunk, Vector &row_ids, IndexAppendInfo &info);
180210 ErrorData Append(DataChunk &chunk, Vector &row_ids, IndexAppendInfo &info);
180211
180213 virtual void VerifyAppend(DataChunk &chunk, IndexAppendInfo &info, optional_ptr<ConflictManager> manager);
180215 virtual void VerifyConstraint(DataChunk &chunk, IndexAppendInfo &info, ConflictManager &manager);
180216
180218 virtual void CommitDrop(IndexLock &index_lock) = 0;
180219
180221
180222 void CommitDrop() override;
180226 virtual idx_t TryDelete(IndexLock &state, DataChunk &entries, Vector &row_identifiers,
180227 optional_ptr<SelectionVector> deleted_sel = nullptr,
180228 optional_ptr<SelectionVector> non_deleted_sel = nullptr);
180230 idx_t TryDelete(DataChunk &entries, Vector &row_identifiers, optional_ptr<SelectionVector> deleted_sel =
nullptr,
180231 optional_ptr<SelectionVector> non_deleted_sel = nullptr);
180234 virtual void Delete(IndexLock &state, DataChunk &entries, Vector &row_identifiers);
180236 void Delete(DataChunk &entries, Vector &row_identifiers);
180237
180239 virtual ErrorData Insert(IndexLock &l, DataChunk &chunk, Vector &row_ids) = 0;
180241 virtual ErrorData Insert(IndexLock &l, DataChunk &chunk, Vector &row_ids, IndexAppendInfo &info);
180242
180245 virtual bool MergeIndexes(IndexLock &state, BoundIndex &other_index) = 0;
180247 bool MergeIndexes(BoundIndex &other_index);
180248
180251 virtual void Vacuum(IndexLock &l) = 0;
180253 void Vacuum();
180254
180256 virtual bool SupportsDeltaIndexes() const;
180259 virtual unique_ptr<BoundIndex> CreateDeltaIndex(DeltaIndexType delta_index_type) const;
180260
180262 virtual idx_t GetInMemorySize(IndexLock &state) = 0;
180264 idx_t GetInMemorySize();
180265
180267 virtual void Verify(IndexLock &l) = 0;
180269 void Verify();
180270
180272 virtual string ToString(IndexLock &l, bool display_ascii = false) = 0;
180274 string ToString(bool display_ascii = false);
180275
180277 virtual void VerifyAllocations(IndexLock &l) = 0;
180279 void VerifyAllocations();
180280
180282 virtual void VerifyBuffers(IndexLock &l);
180284 void VerifyBuffers();
180285
180287 bool IndexIsUpdated(const vector<PhysicalIndex> &column_ids) const;
180288
180290 virtual IndexStorageInfo SerializeToDisk(QueryContext context, const case_insensitive_map_t<Value> &options);
180292 virtual IndexStorageInfo SerializeToWAL(const case_insensitive_map_t<Value> &options);
180293
180295 void ExecuteExpressions(DataChunk &input, DataChunk &result);
180296 static string AppendRowError(DataChunk &input, idx_t index);
180297
180299 virtual string GetConstraintViolationMessage(VerifyExistenceType verify_type, idx_t failed_index,
180300 DataChunk &input) = 0;
180301
180305 void ApplyBufferedReplays(const vector<LogicalType> &table_types, BufferedIndexReplays &buffered_replays,
180306 const vector<StorageIndex> &mapped_column_ids);
180307
180308protected:
180310 mutex lock;
180311
180318 vector<unique_ptr<Expression>> bound_expressions;
180319
180320private:
180322 ExpressionExecutor executor;
180323
180325 unique_ptr<Expression> BindExpression(unique_ptr<Expression> expr);
180326};
180327
180328}
180329
180330
180331
180332namespace duckdb {
180333
180334class ConflictManager;
180335class LocalTableStorage;
180336struct IndexStorageInfo;
180337struct DataTableInfo;
180338template <class T>
180339class TableIndexIterationHelper;
180340
180343
180345struct IndexEntry {
180346 explicit IndexEntry(unique_ptr<Index> index);
180347
180348 atomic<IndexBindState> bind_state;
180350 mutex lock;
180351 unique_ptr<Index>
index;
180352 unique_ptr<BoundIndex> deleted_rows_in_use;
180354 unique_ptr<BoundIndex> added_data_during_checkpoint;
180356 unique_ptr<BoundIndex> removed_data_during_checkpoint;
180358 optional_idx last_written_checkpoint;
180359};
180360
180361struct IndexSerializationInfo {
180362 case_insensitive_map_t<Value> options;
180364};
180365
180366
180367
180368
180369
180370
180371
180372
180373
180374struct IndexSerializationResult {
180376 vector<reference<const IndexStorageInfo>> ordered_infos;
180378 vector<IndexStorageInfo> bound_infos;
180379};
180380
180381class TableIndexList {
180382public:
180383 TableIndexIterationHelper<IndexEntry> IndexEntries() const;
180384 TableIndexIterationHelper<Index> Indexes() const;
180386 void AddIndex(unique_ptr<Index> index);
180388 void RemoveIndex(const string &name);
180390 void CommitDrop(const string &name);
180392 bool NameIsUnique(const string &name);
180394 optional_ptr<BoundIndex> Find(const string &name);
180396 void Bind(ClientContext &context, DataTableInfo &table_info,
const char *
index_type =
nullptr);
180398 bool Empty() const {
180399 return Count() == 0;
180400 }
180402 idx_t Count()
const {
180403 lock_guard<mutex> lock(index_entries_lock);
180404 return index_entries.size();
180405 }
180407 bool HasUnbound() const {
180408 lock_guard<mutex> lock(index_entries_lock);
180409 return unbound_count != 0;
180410 }
180412 unordered_set<string> DistinctIndexTypes() const;
180414 void Move(TableIndexList &other) {
180415 D_ASSERT(index_entries.empty());
180416 index_entries = std::move(other.index_entries);
180417 }
180419 void MergeCheckpointDeltas(transaction_t checkpoint_id);
180422 optional_ptr<IndexEntry> FindForeignKeyIndex(const vector<PhysicalIndex> &fk_keys, const ForeignKeyType fk_type);
180424 void VerifyForeignKey(optional_ptr<LocalTableStorage> storage, const vector<PhysicalIndex> &fk_keys,
180425 DataChunk &chunk, ConflictManager &conflict_manager);
180427 unordered_set<column_t> GetRequiredColumns();
180429 IndexSerializationResult SerializeToDisk(QueryContext context, const IndexSerializationInfo &info);
180430
180431public:
180433 static void InitializeIndexChunk(DataChunk &index_chunk, const vector<LogicalType> &table_types,
180434 vector<StorageIndex> &mapped_column_ids, DataTableInfo &data_table_info);
180436 static void ReferenceIndexChunk(DataChunk &table_chunk, DataChunk &index_chunk,
180437 vector<StorageIndex> &mapped_column_ids);
180438
180439private:
180441 mutable mutex index_entries_lock;
180443 vector<unique_ptr<IndexEntry>> index_entries;
180445 idx_t unbound_count = 0;
180446};
180447
180448template <class T>
180449class TableIndexIterationHelper {
180450public:
180451 TableIndexIterationHelper(mutex &index_lock, const vector<unique_ptr<IndexEntry>> &index_entries);
180452
180453private:
180454 unique_lock<mutex> lock;
180455 const vector<unique_ptr<IndexEntry>> &index_entries;
180456
180457private:
180458 class TableIndexIterator {
180459 public:
180460 explicit TableIndexIterator(optional_ptr<const vector<unique_ptr<IndexEntry>>> index_entries);
180461
180462 optional_ptr<const vector<unique_ptr<IndexEntry>>> index_entries;
180463 optional_idx
index;
180464
180465 public:
180466 TableIndexIterator &operator++();
180467 bool operator!=(
const TableIndexIterator &other)
const;
180469 };
180470
180471public:
180472 TableIndexIterator begin() {
180473 return TableIndexIterator(&index_entries);
180474 }
180475 TableIndexIterator end() {
180476 return TableIndexIterator(nullptr);
180477 }
180478};
180479
180480template <>
180481IndexEntry &TableIndexIterationHelper<IndexEntry>::TableIndexIterator::operator*() const;
180482template <>
180483Index &TableIndexIterationHelper<Index>::TableIndexIterator::operator*() const;
180484
180485}
180486
180487
180488
180489namespace duckdb {
180490class DatabaseInstance;
180491class TableIOManager;
180492
180493struct DataTableInfo {
180494 friend class DataTable;
180495
180496public:
180497 DataTableInfo(AttachedDatabase &db, shared_ptr<TableIOManager> table_io_manager_p, string schema, string table);
180498
180501 void BindIndexes(ClientContext &context,
const char *
index_type =
nullptr);
180502
180504 bool IsTemporary() const;
180505
180506 AttachedDatabase &GetDB() {
180508 }
180509
180510 TableIOManager &GetIOManager() {
180511 return *table_io_manager;
180512 }
180513
180514 TableIndexList &GetIndexes() {
180515 return indexes;
180516 }
180518 IndexStorageInfo ExtractIndexStorageInfo(const string &name);
180519 unique_ptr<StorageLockKey> GetSharedLock() {
180520 return checkpoint_lock.GetSharedLock();
180521 }
180522 bool AppendRequiresNewRowGroup(RowGroupCollection &collection, transaction_t checkpoint_id);
180523 optional_idx CheckpointRowGroupCount(const CheckpointOptions &options) const;
180524 void VerifyIndexBuffers();
180525
180526 string GetSchemaName();
180527 string GetTableName();
180528 void SetTableName(string name);
180529
180530private:
180532 AttachedDatabase &
db;
180534 shared_ptr<TableIOManager> table_io_manager;
180536 mutex name_lock;
180538 string schema;
180540 string table;
180542 TableIndexList indexes;
180544 vector<IndexStorageInfo> index_storage_infos;
180546 StorageLock checkpoint_lock;
180548 optional_idx last_seen_checkpoint;
180550 optional_idx checkpoint_row_group_count;
180551};
180552
180553}
180554
180555
180556
180557
180558
180559
180560
180561
180562
180563
180564
180565
180566
180567
180568
180569
180570
180571
180572
180573
180574
180575
180576
180577
180578
180579
180580
180581
180582namespace duckdb {
180583
180594 DELETED_ROWS_IN_USE
180595};
180596
180597}
180598
180599
180600namespace duckdb {
180601
180602struct ParallelTableScanState;
180603struct ParallelCollectionScanState;
180604class CreateIndexScanState;
180605class CollectionScanState;
180606class PersistentTableData;
180607class TableDataWriter;
180608class TableIndexList;
180609class TableStatistics;
180610struct TableAppendState;
180611class DuckTransaction;
180612class BoundConstraint;
180613class RowGroupSegmentTree;
180614class StorageCommitState;
180615struct ColumnSegmentInfo;
180616class MetadataManager;
180617struct VacuumState;
180618struct CollectionCheckpointState;
180619struct PersistentCollectionData;
180620class CheckpointTask;
180621class TableIOManager;
180622class DataTable;
180623class RowGroupIterationHelper;
180624class TableScanState;
180625
180626class RowGroupCollection {
180627public:
180628 RowGroupCollection(shared_ptr<DataTableInfo> info, TableIOManager &io_manager, vector<LogicalType> types,
180629 idx_t row_start, idx_t total_rows = 0);
180630 RowGroupCollection(shared_ptr<DataTableInfo> info, BlockManager &block_manager, vector<LogicalType> types,
180631 idx_t row_start, idx_t total_rows, idx_t row_group_size);
180632
180633public:
180634 idx_t GetTotalRows()
const;
180635 idx_t GetRowGroupCount()
const;
180636 Allocator &GetAllocator() const;
180637
180638 void Initialize(PersistentCollectionData &data);
180639 void Initialize(PersistentTableData &data);
180640 void InitializeEmpty();
180641 void FinalizeCheckpoint(MetaBlockPointer pointer, const vector<MetaBlockPointer> &existing_pointers);
180642
180643 bool IsEmpty() const;
180644
180645 void AppendRowGroup(SegmentLock &l, idx_t start_row);
180647 optional_ptr<RowGroup> GetRowGroup(int64_t index);
180649 void SetRowGroup(int64_t index, shared_ptr<RowGroup> new_row_group);
180650 void Verify();
180651 void Destroy();
180652
180653 void InitializeScan(const QueryContext &context, CollectionScanState &state, const vector<StorageIndex> &column_ids,
180654 optional_ptr<TableFilterSet> table_filters);
180655 void InitializeCreateIndexScan(CreateIndexScanState &state);
180656 void InitializeScanWithOffset(const QueryContext &context, CollectionScanState &state,
180657 const vector<StorageIndex> &column_ids, idx_t start_row, idx_t end_row);
180658 static bool InitializeScanInRowGroup(ClientContext &context, CollectionScanState &state,
180659 RowGroupCollection &collection, SegmentNode<RowGroup> &row_group,
180660 idx_t vector_index, idx_t max_row);
180661 void InitializeParallelScan(ParallelCollectionScanState &state);
180662 bool NextParallelScan(ClientContext &context, ParallelCollectionScanState &state, CollectionScanState &scan_state);
180663
180664 RowGroupIterationHelper Chunks(DuckTransaction &transaction);
180665 RowGroupIterationHelper Chunks(DuckTransaction &transaction, const vector<StorageIndex> &column_ids);
180666
180667 void Fetch(TransactionData transaction, DataChunk &result, const vector<StorageIndex> &column_ids,
180668 const Vector &row_identifiers, idx_t fetch_count, ColumnFetchState &state);
180669
180671 bool CanFetch(TransactionData, const row_t row_id);
180672
180674 void InitializeAppend(TableAppendState &state);
180677 void InitializeAppend(TransactionData transaction, TableAppendState &state);
180679 bool Append(DataChunk &chunk, TableAppendState &state);
180681 void FinalizeAppend(TransactionData transaction, TableAppendState &state);
180682 void CommitAppend(transaction_t commit_id, idx_t row_start, idx_t count);
180683 void RevertAppendInternal(idx_t start_row);
180684 void CleanupAppend(transaction_t lowest_transaction, idx_t start, idx_t count);
180685
180686 void MergeStorage(RowGroupCollection &data, optional_ptr<DataTable> table,
180687 optional_ptr<StorageCommitState> commit_state);
180688 bool IsPersistent() const;
180689
180690 void RemoveFromIndexes(const QueryContext &context, TableIndexList &indexes, Vector &row_identifiers, idx_t count,
180691 IndexRemovalType removal_type, optional_idx active_checkpoint = optional_idx());
180692
180693 idx_t Delete(TransactionData transaction, DataTable &table, row_t *ids, idx_t count);
180694 void Update(TransactionData transaction, DataTable &table, row_t *ids, const vector<PhysicalIndex> &column_ids,
180695 DataChunk &updates);
180696 void UpdateColumn(TransactionData transaction, DataTable &table, Vector &row_ids,
180697 const vector<column_t> &column_path, DataChunk &updates);
180698
180699 void Checkpoint(TableDataWriter &writer, TableStatistics &global_stats);
180700
180701 void InitializeVacuumState(CollectionCheckpointState &checkpoint_state, VacuumState &state,
180702 optional_idx checkpoint_row_group_count);
180703 bool ScheduleVacuumTasks(CollectionCheckpointState &checkpoint_state, VacuumState &state, idx_t segment_idx,
180704 bool schedule_vacuum);
180705 unique_ptr<CheckpointTask> GetCheckpointTask(CollectionCheckpointState &checkpoint_state, idx_t segment_idx);
180706
180707 void CommitDropColumn(const idx_t column_index);
180708 void CommitDropTable();
180709
180710 vector<PartitionStatistics> GetPartitionStats() const;
180711 vector<ColumnSegmentInfo> GetColumnSegmentInfo(const QueryContext &context);
180712 const vector<LogicalType> &GetTypes() const;
180713
180714 shared_ptr<RowGroupCollection> AddColumn(ClientContext &context, ColumnDefinition &new_column,
180715 ExpressionExecutor &default_executor);
180716 shared_ptr<RowGroupCollection> RemoveColumn(idx_t col_idx);
180717 shared_ptr<RowGroupCollection> AlterType(ClientContext &context, idx_t changed_idx, const LogicalType &target_type,
180718 vector<StorageIndex> bound_columns, Expression &cast_expr);
180719 void VerifyNewConstraint(const QueryContext &context, DataTable &parent, const BoundConstraint &constraint);
180720
180721 void SetStats(TableStatistics &new_stats);
180722 void CopyStats(TableStatistics &stats);
180723 unique_ptr<BaseStatistics> CopyStats(const StorageIndex &column_id);
180724 unique_ptr<BlockingSample> GetSample();
180725 void SetDistinct(column_t column_id, unique_ptr<DistinctStatistics> distinct_stats);
180726
180727 AttachedDatabase &GetAttached();
180728 BlockManager &GetBlockManager() {
180729 return block_manager;
180730 }
180731 MetadataManager &GetMetadataManager();
180732 DataTableInfo &GetTableInfo() {
180733 return *info;
180734 }
180735
180736 idx_t GetAllocationSize()
const {
180737 return allocation_size;
180738 }
180739
180740 idx_t GetRowGroupSize()
const {
180741 return row_group_size;
180742 }
180743 void SetAppendRequiresNewRowGroup();
180745 idx_t GetSegmentCount();
180746
180747private:
180748 optional_ptr<SegmentNode<RowGroup>> NextUpdateRowGroup(RowGroupSegmentTree &row_groups, row_t *ids, idx_t &pos,
180749 idx_t count) const;
180750
180751 shared_ptr<RowGroupSegmentTree> GetRowGroups() const;
180752 void SetRowGroups(shared_ptr<RowGroupSegmentTree> row_groups);
180753
180754private:
180756 BlockManager &block_manager;
180758 const idx_t row_group_size;
180760 atomic<idx_t> total_rows;
180762 shared_ptr<DataTableInfo> info;
180764 vector<LogicalType> types;
180766 mutable mutex row_group_pointer_lock;
180768 shared_ptr<RowGroupSegmentTree> owned_row_groups;
180770 TableStatistics stats;
180772 atomic<idx_t> allocation_size;
180774 MetaBlockPointer metadata_pointer;
180776 vector<MetaBlockPointer> metadata_pointers;
180778 bool requires_new_row_group;
180779};
180780
180781class RowGroupIterationHelper {
180782public:
180783 RowGroupIterationHelper(RowGroupCollection &collection, DuckTransaction &transaction,
180784 vector<StorageIndex> column_ids);
180785
180786private:
180787 RowGroupCollection &collection;
180788 DuckTransaction &transaction;
180789 vector<StorageIndex> column_ids;
180790
180791private:
180792 class RowGroupIterator {
180793 public:
180794 RowGroupIterator(optional_ptr<RowGroupCollection> collection, optional_ptr<DuckTransaction> transaction,
180795 const vector<StorageIndex> &column_ids);
180796 ~RowGroupIterator();
180798 RowGroupIterator(RowGroupIterator &&other) noexcept;
180799
180800 optional_ptr<RowGroupCollection> collection;
180801 optional_ptr<DuckTransaction> transaction;
180802 unique_ptr<DataChunk> chunk;
180803 unique_ptr<TableScanState> state;
180804
180805 public:
180806 RowGroupIterator &operator++();
180807 bool operator!=(
const RowGroupIterator &other)
const;
180809 };
180810
180811public:
180812 RowGroupIterator begin();
180813 RowGroupIterator end();
180814};
180815
180816}
180817
180818
180819
180820
180821
180822
180823
180824
180825
180826
180827
180828
180829
180830
180831
180832
180833
180834
180835
180836
180837
180838
180839
180840
180841
180842
180843
180844
180845namespace duckdb {
180846class PartialBlockManager;
180847
180848struct OptimisticWriteCollection {
180849 ~OptimisticWriteCollection();
180850
180851 shared_ptr<RowGroupCollection> collection;
180852 set<idx_t> unflushed_row_groups;
180853 idx_t complete_row_groups = 0;
180854 vector<unique_ptr<PartialBlockManager>> partial_block_managers;
180855
180856 void MergeStorage(OptimisticWriteCollection &collection);
180857};
180858
180859enum class OptimisticWritePartialManagers { PER_COLUMN, GLOBAL };
180860
180861class OptimisticDataWriter {
180862public:
180863 OptimisticDataWriter(ClientContext &context, DataTable &table);
180864 OptimisticDataWriter(DataTable &table, OptimisticDataWriter &parent);
180865 ~OptimisticDataWriter();
180866
180868 unique_ptr<OptimisticWriteCollection>
180869 CreateCollection(DataTable &storage, const vector<LogicalType> &insert_types,
180870 OptimisticWritePartialManagers type = OptimisticWritePartialManagers::PER_COLUMN);
180872 void WriteNewRowGroup(OptimisticWriteCollection &row_groups);
180874 void WriteUnflushedRowGroups(OptimisticWriteCollection &row_groups);
180876 void FinalFlush();
180878 void Merge(OptimisticDataWriter &other);
180879 void Merge(unique_ptr<PartialBlockManager> &other_manager);
180881 void Rollback();
180882
180884 ClientContext &GetClientContext() {
180885 return context;
180886 }
180887
180888private:
180890 bool PrepareWrite();
180892 void FlushToDisk(OptimisticWriteCollection &collection, const vector<const_reference<RowGroup>> &row_groups,
180893 const vector<int64_t> &segment_indexes);
180894
180895private:
180897 ClientContext &context;
180899 DataTable &table;
180901 unique_ptr<PartialBlockManager> partial_manager;
180902};
180903
180904}
180905
180906
180907
180908
180909namespace duckdb {
180910class AttachedDatabase;
180911class Catalog;
180912class DataTable;
180913class StorageCommitState;
180914class Transaction;
180915class WriteAheadLog;
180916struct LocalAppendState;
180917struct TableAppendState;
180918
180919class LocalTableStorage : public enable_shared_from_this<LocalTableStorage> {
180920public:
180921
180922 explicit LocalTableStorage(ClientContext &context, DataTable &table);
180924 LocalTableStorage(ClientContext &context, DataTable &new_data_table, LocalTableStorage &parent,
180925 const idx_t alter_column_index, const LogicalType &target_type,
180926 const vector<StorageIndex> &bound_columns, Expression &cast_expr);
180928 LocalTableStorage(DataTable &new_data_table, LocalTableStorage &parent, const idx_t drop_column_index);
180929
180930 LocalTableStorage(ClientContext &context, DataTable &table, LocalTableStorage &parent, ColumnDefinition &new_column,
180931 ExpressionExecutor &default_executor);
180932 ~LocalTableStorage();
180933
180934 QueryContext context;
180935
180936 reference<DataTable> table_ref;
180937
180938 Allocator &allocator;
180940 unique_ptr<OptimisticWriteCollection> row_groups;
180942 TableIndexList append_indexes;
180944 TableIndexList delete_indexes;
180946 IndexAppendMode index_append_mode = IndexAppendMode::DEFAULT;
180948 idx_t deleted_rows;
180949
180951 vector<unique_ptr<OptimisticWriteCollection>> optimistic_collections;
180953 OptimisticDataWriter optimistic_writer;
180954
180956 bool is_dropped = false;
180957
180958public:
180959 void InitializeScan(CollectionScanState &state, optional_ptr<TableFilterSet> table_filters = nullptr);
180961 void WriteNewRowGroup();
180962 void FlushBlocks();
180963 void Rollback();
180964 idx_t EstimatedSize();
180965
180966 void AppendToIndexes(DuckTransaction &transaction, TableAppendState &append_state);
180967 void AppendToTable(DuckTransaction &transaction, TableAppendState &append_state);
180968 ErrorData AppendToIndexes(DuckTransaction &transaction, RowGroupCollection &source, TableIndexList &index_list,
180969 const vector<LogicalType> &table_types, row_t &start_row);
180970 void AppendToDeleteIndexes(Vector &row_ids, DataChunk &delete_chunk);
180971
180974 PhysicalIndex CreateOptimisticCollection(unique_ptr<OptimisticWriteCollection> collection);
180976 OptimisticWriteCollection &GetOptimisticCollection(const PhysicalIndex collection_index);
180978 void ResetOptimisticCollection(const PhysicalIndex collection_index);
180980 OptimisticDataWriter &GetOptimisticWriter();
180981
180982 RowGroupCollection &GetCollection();
180983 OptimisticWriteCollection &GetPrimaryCollection();
180984
180985private:
180986 mutex collections_lock;
180987};
180988
180989class LocalTableManager {
180990public:
180991 shared_ptr<LocalTableStorage> MoveEntry(DataTable &table);
180992 reference_map_t<DataTable, shared_ptr<LocalTableStorage>> MoveEntries();
180993 optional_ptr<LocalTableStorage> GetStorage(DataTable &table) const;
180994 LocalTableStorage &GetOrCreateStorage(ClientContext &context, DataTable &table);
180995 idx_t EstimatedSize()
const;
180996 bool IsEmpty() const;
180997 void InsertEntry(DataTable &table, shared_ptr<LocalTableStorage> entry);
180998
180999private:
181000 mutable mutex table_storage_lock;
181001 reference_map_t<DataTable, shared_ptr<LocalTableStorage>> table_storage;
181002};
181003
181005class LocalStorage {
181006public:
181007 struct CommitState {
181008 CommitState();
181009 ~CommitState();
181010
181011 reference_map_t<DataTable, unique_ptr<TableAppendState>> append_states;
181012 };
181013
181014public:
181015 explicit LocalStorage(ClientContext &context, DuckTransaction &transaction);
181016
181017 static LocalStorage &Get(DuckTransaction &transaction);
181018 static LocalStorage &Get(ClientContext &context, AttachedDatabase &db);
181019 static LocalStorage &Get(ClientContext &context, Catalog &catalog);
181020
181022 void InitializeScan(DataTable &table, CollectionScanState &state, optional_ptr<TableFilterSet> table_filters);
181024 void Scan(CollectionScanState &state, const vector<StorageIndex> &column_ids, DataChunk &result);
181025
181026 void InitializeParallelScan(DataTable &table, ParallelCollectionScanState &state);
181027 bool NextParallelScan(ClientContext &context, DataTable &table, ParallelCollectionScanState &state,
181028 CollectionScanState &scan_state);
181029
181031 void InitializeAppend(LocalAppendState &state, DataTable &table);
181033 void InitializeStorage(LocalAppendState &state, DataTable &table);
181035 static void Append(LocalAppendState &state, DataChunk &table_chunk, DataTableInfo &data_table_info);
181037 static void FinalizeAppend(LocalAppendState &state);
181039 void LocalMerge(DataTable &table, OptimisticWriteCollection &collection);
181042 PhysicalIndex CreateOptimisticCollection(DataTable &table, unique_ptr<OptimisticWriteCollection> collection);
181044 OptimisticWriteCollection &GetOptimisticCollection(DataTable &table, const PhysicalIndex collection_index);
181046 void ResetOptimisticCollection(DataTable &table, const PhysicalIndex collection_index);
181048 OptimisticDataWriter &GetOptimisticWriter(DataTable &table);
181049
181051 idx_t Delete(DataTable &table, Vector &row_ids, idx_t count);
181053 void Update(DataTable &table, Vector &row_ids, const vector<PhysicalIndex> &column_ids, DataChunk &data);
181054
181056 void Commit(optional_ptr<StorageCommitState> commit_state);
181058 void Rollback();
181059
181060 bool ChangesMade() noexcept;
181061 idx_t EstimatedSize();
181062
181063 void DropTable(DataTable &table);
181064 bool Find(DataTable &table);
181065
181066 idx_t AddedRows(DataTable &table);
181067 vector<PartitionStatistics> GetPartitionStats(DataTable &table) const;
181068
181069 void AddColumn(DataTable &old_dt, DataTable &new_dt, ColumnDefinition &new_column,
181070 ExpressionExecutor &default_executor);
181071 void DropColumn(DataTable &old_dt, DataTable &new_dt, const idx_t drop_column_index);
181072 void ChangeType(DataTable &old_dt, DataTable &new_dt, idx_t changed_idx, const LogicalType &target_type,
181073 const vector<StorageIndex> &bound_columns, Expression &cast_expr);
181074
181075 void MoveStorage(DataTable &old_dt, DataTable &new_dt);
181076 void FetchChunk(DataTable &table, const Vector &row_ids, idx_t count, const vector<StorageIndex> &col_ids,
181077 DataChunk &chunk, ColumnFetchState &fetch_state);
181079 bool CanFetch(DataTable &table, const row_t row_id);
181080 TableIndexList &GetIndexes(ClientContext &context, DataTable &table);
181081 optional_ptr<LocalTableStorage> GetStorage(DataTable &table);
181082
181083 void VerifyNewConstraint(DataTable &parent, const BoundConstraint &constraint);
181084
181085 ClientContext &GetClientContext() const {
181086 return context;
181087 }
181088
181089private:
181090 ClientContext &context;
181091 DuckTransaction &transaction;
181092 LocalTableManager table_manager;
181093
181094private:
181095 void Flush(DataTable &table, LocalTableStorage &storage, optional_ptr<StorageCommitState> commit_state);
181096};
181097
181098}
181099
181100
181101namespace duckdb {
181102
181103class BoundForeignKeyConstraint;
181104class ClientContext;
181105class ColumnDataCollection;
181106class ColumnDefinition;
181107class DataTable;
181108class DuckTransaction;
181109class RowGroup;
181110class StorageManager;
181111class TableCatalogEntry;
181112class TableIOManager;
181113class Transaction;
181114class WriteAheadLog;
181115class TableDataWriter;
181116class ConflictManager;
181117class TableScanState;
181118struct TableDeleteState;
181119struct ConstraintState;
181120struct TableUpdateState;
181121enum class VerifyExistenceType :
uint8_t;
181122struct OptimisticWriteCollection;
181123
181124enum class DataTableVersion {
181125 MAIN_TABLE,
181126 ALTERED,
181127 DROPPED
181128};
181129
181131class DataTable : public enable_shared_from_this<DataTable> {
181132public:
181134 DataTable(AttachedDatabase &db, shared_ptr<TableIOManager> table_io_manager, const string &schema,
181135 const string &table, vector<ColumnDefinition> column_definitions_p,
181136 unique_ptr<PersistentTableData> data = nullptr);
181138 DataTable(ClientContext &context, DataTable &parent, ColumnDefinition &new_column, Expression &default_value);
181140 DataTable(ClientContext &context, DataTable &parent, idx_t removed_column);
181142 DataTable(ClientContext &context, DataTable &parent, idx_t changed_idx, const LogicalType &target_type,
181143 const vector<StorageIndex> &bound_columns, Expression &cast_expr);
181145 DataTable(ClientContext &context, DataTable &parent, BoundConstraint &constraint);
181146
181148 AttachedDatabase &
db;
181149
181150public:
181151 AttachedDatabase &GetAttached();
181152 TableIOManager &GetTableIOManager();
181153
181154 bool IsTemporary() const;
181155
181157 vector<LogicalType> GetTypes();
181158 const vector<ColumnDefinition> &Columns() const;
181159
181160 void InitializeScan(ClientContext &context, DuckTransaction &transaction, TableScanState &state,
181161 const vector<StorageIndex> &column_ids, optional_ptr<TableFilterSet> table_filters = nullptr);
181162
181164 idx_t MaxThreads(ClientContext &context)
const;
181165 void InitializeParallelScan(ClientContext &context, ParallelTableScanState &state,
181166 const vector<ColumnIndex> &column_indexes);
181167 idx_t NextParallelScan(ClientContext &context, ParallelTableScanState &state, TableScanState &scan_state);
181168
181173 void Scan(DuckTransaction &transaction, DataChunk &result, TableScanState &state);
181174
181176 void Fetch(DuckTransaction &transaction, DataChunk &result, const vector<StorageIndex> &column_ids,
181177 const Vector &row_ids, idx_t fetch_count, ColumnFetchState &state);
181178 void FetchCommitted(DataChunk &result, const vector<StorageIndex> &column_ids, const Vector &row_identifiers,
181179 idx_t fetch_count, ColumnFetchState &state);
181181 bool CanFetch(DuckTransaction &transaction, const row_t row_id);
181182
181184 void InitializeLocalAppend(LocalAppendState &state, TableCatalogEntry &table, ClientContext &context,
181185 const vector<unique_ptr<BoundConstraint>> &bound_constraints);
181187 void InitializeLocalStorage(LocalAppendState &state, TableCatalogEntry &table, ClientContext &context,
181188 const vector<unique_ptr<BoundConstraint>> &bound_constraints);
181190 void LocalAppend(LocalAppendState &state, ClientContext &context, DataChunk &chunk, bool unsafe);
181192 void FinalizeLocalAppend(LocalAppendState &state);
181194 void LocalAppend(TableCatalogEntry &table, ClientContext &context, DataChunk &chunk,
181195 const vector<unique_ptr<BoundConstraint>> &bound_constraints, Vector &row_ids,
181196 DataChunk &delete_chunk);
181198 void LocalAppend(TableCatalogEntry &table, ClientContext &context, DataChunk &chunk,
181199 const vector<unique_ptr<BoundConstraint>> &bound_constraints);
181201 void LocalWALAppend(TableCatalogEntry &table, ClientContext &context, DataChunk &chunk,
181202 const vector<unique_ptr<BoundConstraint>> &bound_constraints);
181204 void LocalAppend(TableCatalogEntry &table, ClientContext &context, ColumnDataCollection &collection,
181205 const vector<unique_ptr<BoundConstraint>> &bound_constraints,
181206 optional_ptr<const vector<LogicalIndex>> column_ids);
181208 void LocalMerge(ClientContext &context, OptimisticWriteCollection &collection);
181211 PhysicalIndex CreateOptimisticCollection(ClientContext &context, unique_ptr<OptimisticWriteCollection> collection);
181213 OptimisticWriteCollection &GetOptimisticCollection(ClientContext &context, const PhysicalIndex collection_index);
181215 void ResetOptimisticCollection(ClientContext &context, const PhysicalIndex collection_index);
181217 OptimisticDataWriter &GetOptimisticWriter(ClientContext &context);
181218
181219 unique_ptr<TableDeleteState> InitializeDelete(TableCatalogEntry &table, ClientContext &context,
181220 const vector<unique_ptr<BoundConstraint>> &bound_constraints);
181222 idx_t Delete(TableDeleteState &state, ClientContext &context, Vector &row_ids, idx_t count);
181223
181224 unique_ptr<TableUpdateState> InitializeUpdate(TableCatalogEntry &table, ClientContext &context,
181225 const vector<unique_ptr<BoundConstraint>> &bound_constraints);
181227 void Update(TableUpdateState &state, ClientContext &context, Vector &row_ids,
181228 const vector<PhysicalIndex> &column_ids, DataChunk &data);
181238 void UpdateColumn(TableCatalogEntry &table, ClientContext &context, Vector &row_ids,
181239 const vector<column_t> &column_path, DataChunk &updates);
181240
181242 void AppendLock(DuckTransaction &transaction, TableAppendState &state);
181244 void InitializeAppend(DuckTransaction &transaction, TableAppendState &state);
181246 void Append(DataChunk &chunk, TableAppendState &state);
181248 void FinalizeAppend(DuckTransaction &transaction, TableAppendState &state);
181250 void CommitAppend(transaction_t commit_id, idx_t row_start, idx_t count);
181252 void WriteToLog(DuckTransaction &transaction, WriteAheadLog &log, idx_t row_start, idx_t count,
181253 optional_ptr<StorageCommitState> commit_state);
181256 void RevertAppend(DuckTransaction &transaction, idx_t start_row, idx_t count);
181257 void RevertAppendInternal(idx_t start_row);
181258
181259 void ScanTableSegment(DuckTransaction &transaction, idx_t start_row, idx_t count,
181260 const std::function<void(DataChunk &chunk)> &function);
181261
181263 void MergeStorage(RowGroupCollection &data, optional_ptr<StorageCommitState> commit_state);
181264
181267 static ErrorData AppendToIndexes(TableIndexList &indexes, optional_ptr<TableIndexList> delete_indexes,
181268 DataChunk &table_chunk, DataChunk &index_chunk,
181269 const vector<StorageIndex> &mapped_column_ids, row_t row_start,
181270 const IndexAppendMode index_append_mode, optional_idx active_checkpoint);
181271 ErrorData AppendToIndexes(optional_ptr<TableIndexList> delete_indexes, DataChunk &table_chunk,
181272 DataChunk &index_chunk, const vector<StorageIndex> &mapped_column_ids, row_t row_start,
181273 const IndexAppendMode index_append_mode);
181275 void RevertIndexAppend(TableAppendState &state, DataChunk &chunk, row_t row_start);
181277 void RevertIndexAppend(TableAppendState &state, DataChunk &chunk, Vector &row_identifiers);
181279 void RemoveFromIndexes(const QueryContext &context, Vector &row_identifiers, idx_t count,
181280 IndexRemovalType removal_type, optional_idx checkpoint_id = optional_idx());
181281
181282 void SetAsMainTable() {
181283 this->version = DataTableVersion::MAIN_TABLE;
181284 }
181285
181286 void SetAsDropped() {
181287 this->version = DataTableVersion::DROPPED;
181288 }
181289
181290 bool IsMainTable() const {
181291 return this->version == DataTableVersion::MAIN_TABLE;
181292 }
181293 bool IsRoot() const {
181294 return IsMainTable();
181295 }
181296 string TableModification() const;
181297
181299 unique_ptr<BaseStatistics> GetStatistics(ClientContext &context, const StorageIndex &column_id);
181300
181302 unique_ptr<BlockingSample> GetSample();
181304 void SetDistinct(column_t column_id, unique_ptr<DistinctStatistics> distinct_stats);
181305
181307 unique_ptr<StorageLockKey> GetCheckpointLock();
181309 void Checkpoint(TableDataWriter &writer, Serializer &serializer);
181310 void CommitDropTable();
181311 void CommitDropColumn(const idx_t column_index);
181312
181313 idx_t ColumnCount()
const;
181314 idx_t GetTotalRows()
const;
181315
181316 vector<ColumnSegmentInfo> GetColumnSegmentInfo(const QueryContext &context);
181317
181319 bool CreateIndexScan(TableScanState &state, DataChunk &result);
181322 bool IndexNameIsUnique(const string &name);
181323
181325 unique_ptr<ConstraintState> InitializeConstraintState(TableCatalogEntry &table,
181326 const vector<unique_ptr<BoundConstraint>> &bound_constraints);
181328 void VerifyAppendConstraints(ConstraintState &constraint_state, ClientContext &context, DataChunk &chunk,
181329 optional_ptr<LocalTableStorage> local_storage, optional_ptr<ConflictManager> manager);
181330
181331 shared_ptr<DataTableInfo> &GetDataTableInfo();
181332
181333 void BindIndexes(ClientContext &context);
181334 bool HasIndexes() const;
181335 bool HasUniqueIndexes() const;
181336 bool HasForeignKeyIndex(const vector<PhysicalIndex> &keys, ForeignKeyType type);
181337 void SetIndexStorageInfo(vector<IndexStorageInfo> index_storage_info);
181338 void VacuumIndexes();
181339 void VerifyIndexBuffers();
181340 void CleanupAppend(transaction_t lowest_transaction, idx_t start, idx_t count);
181341 void Destroy();
181342
181343 string GetTableName() const;
181344 void SetTableName(string new_name);
181345
181346 TableStorageInfo GetStorageInfo();
181347
181348 idx_t GetRowGroupSize()
const;
181349
181351 void VerifyUniqueIndexes(TableIndexList &indexes, optional_ptr<LocalTableStorage> storage, DataChunk &chunk,
181352 optional_ptr<ConflictManager> manager);
181355 void AddIndex(const ColumnList &columns, const vector<LogicalIndex> &column_indexes, const IndexConstraintType type,
181356 IndexStorageInfo index_info);
181358 void AddIndex(unique_ptr<Index> index);
181359
181361 vector<PartitionStatistics> GetPartitionStats(ClientContext &context);
181362
181363private:
181365 void VerifyNewConstraint(LocalStorage &local_storage, DataTable &parent, const BoundConstraint &constraint);
181366
181368 void VerifyUpdateConstraints(ConstraintState &state, ClientContext &context, DataChunk &chunk,
181369 const vector<PhysicalIndex> &column_ids);
181371 void VerifyDeleteConstraints(optional_ptr<LocalTableStorage> storage, TableDeleteState &state,
181372 ClientContext &context, DataChunk &chunk);
181373
181374 void InitializeScanWithOffset(DuckTransaction &transaction, TableScanState &state,
181375 const vector<StorageIndex> &column_ids, idx_t start_row, idx_t end_row);
181376
181378 void RebuildIndexes();
181379
181380 void VerifyForeignKeyConstraint(optional_ptr<LocalTableStorage> storage,
181381 const BoundForeignKeyConstraint &bound_foreign_key, ClientContext &context,
181382 DataChunk &chunk, VerifyExistenceType type);
181383 void VerifyAppendForeignKeyConstraint(optional_ptr<LocalTableStorage> storage,
181384 const BoundForeignKeyConstraint &bound_foreign_key, ClientContext &context,
181385 DataChunk &chunk);
181386 void VerifyDeleteForeignKeyConstraint(optional_ptr<LocalTableStorage> storage,
181387 const BoundForeignKeyConstraint &bound_foreign_key, ClientContext &context,
181388 DataChunk &chunk);
181389
181390private:
181392 shared_ptr<DataTableInfo> info;
181394 vector<ColumnDefinition> column_definitions;
181396 mutex append_lock;
181398 shared_ptr<RowGroupCollection> row_groups;
181400 atomic<DataTableVersion> version;
181401};
181402}
181403
181404#include <functional>
181405#include <map>
181406
181407namespace duckdb {
181408class Optimizer;
181409
181410enum class ValueComparisonResult { PRUNE_LEFT, PRUNE_RIGHT, UNSATISFIABLE_CONDITION, PRUNE_NOTHING };
181411enum class FilterResult { UNSATISFIABLE, SUCCESS, UNSUPPORTED };
181412enum class FilterPushdownResult { NO_PUSHDOWN, PUSHED_DOWN_PARTIALLY, PUSHED_DOWN_FULLY };
181413
181419class FilterCombiner {
181420public:
181421 explicit FilterCombiner(ClientContext &context);
181422 explicit FilterCombiner(Optimizer &optimizer);
181423
181424 ClientContext &context;
181425
181426public:
181427 struct ExpressionValueInformation {
181428 Value constant;
181429 ExpressionType comparison_type;
181430 };
181431
181432 FilterResult AddFilter(unique_ptr<Expression> expr);
181433
181436 static bool IsDenseRange(vector<Value> &in_list);
181437 static bool ContainsNull(vector<Value> &in_list);
181438 static bool FindNextLegalUTF8(string &prefix_string);
181439
181440 void GenerateFilters(const std::function<void(unique_ptr<Expression> filter)> &callback);
181441 bool HasFilters();
181442 TableFilterSet GenerateTableScanFilters(const vector<ColumnIndex> &column_ids,
181443 vector<FilterPushdownResult> &pushdown_results);
181444
181445 FilterPushdownResult TryPushdownGenericExpression(LogicalGet &
get, Expression &expr);
181446
181447private:
181448 FilterResult AddFilter(Expression &expr);
181449 FilterResult AddBoundComparisonFilter(Expression &expr);
181450 FilterResult AddTransitiveFilters(BoundComparisonExpression &comparison, bool is_root = true);
181451 unique_ptr<Expression> FindTransitiveFilter(Expression &expr);
181452 Expression &GetNode(Expression &expr);
181453 idx_t GetEquivalenceSet(Expression &expr);
181454 FilterResult AddConstantComparison(vector<ExpressionValueInformation> &info_list, ExpressionValueInformation info);
181455
181456 FilterPushdownResult TryPushdownConstantFilter(TableFilterSet &table_filters, const vector<ColumnIndex> &column_ids,
181457 column_t column_id, vector<ExpressionValueInformation> &info_list);
181458 FilterPushdownResult TryPushdownExpression(TableFilterSet &table_filters, const vector<ColumnIndex> &column_ids,
181459 Expression &expr);
181460 FilterPushdownResult TryPushdownPrefixFilter(TableFilterSet &table_filters, const vector<ColumnIndex> &column_ids,
181461 Expression &expr);
181462 FilterPushdownResult TryPushdownLikeFilter(TableFilterSet &table_filters, const vector<ColumnIndex> &column_ids,
181463 Expression &expr);
181464 FilterPushdownResult TryPushdownInFilter(TableFilterSet &table_filters, const vector<ColumnIndex> &column_ids,
181465 Expression &expr);
181466 FilterPushdownResult TryPushdownOrClause(TableFilterSet &table_filters, const vector<ColumnIndex> &column_ids,
181467 Expression &expr);
181468
181469private:
181470 vector<unique_ptr<Expression>> remaining_filters;
181471
181472 expression_map_t<unique_ptr<Expression>> stored_expressions;
181473 expression_map_t<idx_t> equivalence_set_map;
181474 map<idx_t, vector<ExpressionValueInformation>> constant_values;
181475 map<idx_t, vector<reference<Expression>>> equivalence_map;
181476 idx_t set_index = 0;
181477};
181478
181479}
181480
181481
181482
181483
181484
181485
181486
181487
181488
181489
181490
181491
181492
181493
181494
181495
181496
181497
181498
181499
181500namespace duckdb {
181501
181502class Optimizer;
181503class ClientContext;
181504class LogicalOperator;
181505class TableFilter;
181506struct BoundOrderByNode;
181507
181508class StatisticsPropagator {
181509public:
181510 StatisticsPropagator(Optimizer &optimizer, LogicalOperator &root);
181511
181512 unique_ptr<NodeStatistics> PropagateStatistics(unique_ptr<LogicalOperator> &node_ptr);
181513
181514 column_binding_map_t<unique_ptr<BaseStatistics>> GetStatisticsMap() {
181515 return std::move(statistics_map);
181516 }
181517
181519 static bool CanPropagateCast(const LogicalType &source, const LogicalType &target);
181520 static unique_ptr<BaseStatistics> TryPropagateCast(const BaseStatistics &stats, const LogicalType &source,
181521 const LogicalType &target);
181522
181523private:
181525 unique_ptr<NodeStatistics> PropagateStatistics(LogicalOperator &node, unique_ptr<LogicalOperator> &node_ptr);
181526
181527 unique_ptr<NodeStatistics> PropagateStatistics(LogicalFilter &op, unique_ptr<LogicalOperator> &node_ptr);
181528 unique_ptr<NodeStatistics> PropagateStatistics(LogicalGet &op, unique_ptr<LogicalOperator> &node_ptr);
181529 unique_ptr<NodeStatistics> PropagateStatistics(LogicalJoin &op, unique_ptr<LogicalOperator> &node_ptr);
181530 unique_ptr<NodeStatistics> PropagateStatistics(LogicalPositionalJoin &op, unique_ptr<LogicalOperator> &node_ptr);
181531 unique_ptr<NodeStatistics> PropagateStatistics(LogicalProjection &op, unique_ptr<LogicalOperator> &node_ptr);
181532 void PropagateStatistics(LogicalComparisonJoin &op, unique_ptr<LogicalOperator> &node_ptr);
181533 void PropagateStatistics(LogicalAnyJoin &op, unique_ptr<LogicalOperator> &node_ptr);
181534 unique_ptr<NodeStatistics> PropagateStatistics(LogicalSetOperation &op, unique_ptr<LogicalOperator> &node_ptr);
181535 unique_ptr<NodeStatistics> PropagateStatistics(LogicalAggregate &op, unique_ptr<LogicalOperator> &node_ptr);
181536 unique_ptr<NodeStatistics> PropagateStatistics(LogicalCrossProduct &op, unique_ptr<LogicalOperator> &node_ptr);
181537 unique_ptr<NodeStatistics> PropagateStatistics(LogicalLimit &op, unique_ptr<LogicalOperator> &node_ptr);
181538 unique_ptr<NodeStatistics> PropagateStatistics(LogicalOrder &op, unique_ptr<LogicalOperator> &node_ptr);
181539 unique_ptr<NodeStatistics> PropagateStatistics(LogicalWindow &op, unique_ptr<LogicalOperator> &node_ptr);
181540
181541 unique_ptr<NodeStatistics> PropagateChildren(LogicalOperator &node, unique_ptr<LogicalOperator> &node_ptr);
181542
181544 unique_ptr<BaseStatistics> StatisticsFromValue(const Value &input);
181546 FilterPropagateResult PropagateComparison(BaseStatistics &left, BaseStatistics &right, ExpressionType comparison);
181547
181549 void UpdateFilterStatistics(BaseStatistics &input, ExpressionType comparison_type, const Value &constant);
181551 void UpdateFilterStatistics(BaseStatistics &lstats, BaseStatistics &rstats, ExpressionType comparison_type);
181553 void UpdateFilterStatistics(Expression &left, Expression &right, ExpressionType comparison_type);
181555 void UpdateFilterStatistics(Expression &condition);
181557 void SetStatisticsNotNull(ColumnBinding binding);
181559 FilterPropagateResult HandleFilter(unique_ptr<Expression> &condition);
181560
181562 FilterPropagateResult PropagateTableFilter(ColumnBinding stats_binding, BaseStatistics &stats, TableFilter &filter);
181564 void UpdateFilterStatistics(BaseStatistics &input, const TableFilter &filter);
181565
181567 void AddCardinalities(unique_ptr<NodeStatistics> &stats, NodeStatistics &new_stats);
181570 void MultiplyCardinalities(unique_ptr<NodeStatistics> &stats, NodeStatistics &new_stats);
181572 void CreateFilterFromJoinStats(unique_ptr<LogicalOperator> &child, unique_ptr<Expression> &expr,
181573 const BaseStatistics &stats_before, const BaseStatistics &stats_after);
181574
181575 unique_ptr<BaseStatistics> PropagateExpression(unique_ptr<Expression> &expr);
181576 unique_ptr<BaseStatistics> PropagateExpression(Expression &expr, unique_ptr<Expression> &expr_ptr);
181578 unique_ptr<BaseStatistics> PropagateExpression(BoundAggregateExpression &expr, unique_ptr<Expression> &expr_ptr);
181579 unique_ptr<BaseStatistics> PropagateExpression(BoundBetweenExpression &expr, unique_ptr<Expression> &expr_ptr);
181580 unique_ptr<BaseStatistics> PropagateExpression(BoundCaseExpression &expr, unique_ptr<Expression> &expr_ptr);
181581 unique_ptr<BaseStatistics> PropagateExpression(BoundCastExpression &expr, unique_ptr<Expression> &expr_ptr);
181582 unique_ptr<BaseStatistics> PropagateExpression(BoundConjunctionExpression &expr, unique_ptr<Expression> &expr_ptr);
181583 unique_ptr<BaseStatistics> PropagateExpression(BoundFunctionExpression &expr, unique_ptr<Expression> &expr_ptr);
181584 unique_ptr<BaseStatistics> PropagateExpression(BoundComparisonExpression &expr, unique_ptr<Expression> &expr_ptr);
181585 unique_ptr<BaseStatistics> PropagateExpression(BoundConstantExpression &expr, unique_ptr<Expression> &expr_ptr);
181586 unique_ptr<BaseStatistics> PropagateExpression(BoundColumnRefExpression &expr, unique_ptr<Expression> &expr_ptr);
181587 unique_ptr<BaseStatistics> PropagateExpression(BoundOperatorExpression &expr, unique_ptr<Expression> &expr_ptr);
181588
181590 void TryExecuteAggregates(LogicalAggregate &op, unique_ptr<LogicalOperator> &node_ptr);
181591 void ReplaceWithEmptyResult(unique_ptr<LogicalOperator> &node);
181592
181593 bool ExpressionIsConstant(Expression &expr, const Value &val);
181594 bool ExpressionIsConstantOrNull(Expression &expr, const Value &val);
181595
181596 unique_ptr<NodeStatistics> PropagateUnion(LogicalSetOperation &setop, unique_ptr<LogicalOperator> &node_ptr);
181597
181598private:
181599 Optimizer &optimizer;
181600 ClientContext &context;
181602 optional_ptr<LogicalOperator> root;
181604 column_binding_map_t<unique_ptr<BaseStatistics>> statistics_map;
181606 unique_ptr<NodeStatistics> node_stats;
181607};
181608
181609}
181610
181611
181612
181613
181614
181615
181616
181617
181618
181619
181620
181621
181622
181623
181624#include <functional>
181625
181626namespace duckdb {
181627
181628class ExpressionIterator {
181629public:
181630 static void EnumerateChildren(const Expression &expression,
181631 const std::function<void(const Expression &child)> &callback);
181632 static void EnumerateChildren(Expression &expression, const std::function<void(Expression &child)> &callback);
181633 static void EnumerateChildren(Expression &expression,
181634 const std::function<void(unique_ptr<Expression> &child)> &callback);
181635
181636 static void EnumerateExpression(unique_ptr<Expression> &expr,
181637 const std::function<void(Expression &child)> &callback);
181638 static void EnumerateExpression(unique_ptr<Expression> &expr,
181639 const std::function<void(unique_ptr<Expression> &child)> &callback);
181640
181641 static void VisitExpressionClass(const Expression &expr, ExpressionClass expr_class,
181642 const std::function<void(const Expression &child)> &callback);
181643 static void VisitExpressionClassMutable(unique_ptr<Expression> &expr, ExpressionClass expr_class,
181644 const std::function<void(unique_ptr<Expression> &child)> &callback);
181645
181646 template <class T>
181647 static void VisitExpressionMutable(unique_ptr<Expression> &expr,
181648 const std::function<void(T &child, unique_ptr<Expression> &)> &callback) {
181649 VisitExpressionClassMutable(expr, T::TYPE,
181650 [&](unique_ptr<Expression> &child) { callback(child->Cast<T>(), child); });
181651 }
181652 template <class T>
181653 static void VisitExpression(const Expression &expr, const std::function<void(const T &child)> &callback) {
181654 VisitExpressionClass(expr, T::TYPE, [&](const Expression &child) { callback(child.Cast<T>()); });
181655 }
181656};
181657
181658}
181659
181660
181661
181662
181663
181664#include <iostream>
181665
181666namespace duckdb {
181667struct MultiFilePushdownInfo;
181668
181669struct HivePartitioningFilterInfo {
181670 unordered_map<string, column_t> column_map;
181671 bool hive_enabled;
181672 bool filename_enabled;
181673};
181674
181675class HivePartitioning {
181676public:
181678 DUCKDB_API static std::map<string, string> Parse(const string &filename);
181682 DUCKDB_API static void ApplyFiltersToFileList(ClientContext &context, vector<OpenFileInfo> &files,
181683 vector<unique_ptr<Expression>> &filters,
181684 const HivePartitioningFilterInfo &filter_info,
181685 MultiFilePushdownInfo &info);
181686
181687 DUCKDB_API static Value GetValue(ClientContext &context, const string &key, const string &value,
181688 const LogicalType &type);
181690 DUCKDB_API static string Escape(const string &input);
181692 DUCKDB_API static string Unescape(const string &input);
181694 DUCKDB_API static bool IsNull(const string &input);
181695};
181696
181697struct HivePartitionKey {
181699 vector<Value> values;
181702
181703 struct Hash {
181704 std::size_t
operator()(
const HivePartitionKey &k)
const {
181705 return k.hash;
181706 }
181707 };
181708
181709 struct Equality {
181710 bool operator()(
const HivePartitionKey &a,
const HivePartitionKey &b)
const {
181711 if (a.values.size() != b.values.size()) {
181712 return false;
181713 }
181714 for (idx_t i = 0; i < a.values.size(); i++) {
181716 return false;
181717 }
181718 }
181719 return true;
181720 }
181721 };
181722};
181723
181725typedef unordered_map<HivePartitionKey, idx_t, HivePartitionKey::Hash, HivePartitionKey::Equality>
hive_partition_map_t;
181726
181729class GlobalHivePartitionState {
181730public:
181731 mutex lock;
181733};
181734
181735class HivePartitionedColumnData : public PartitionedColumnData {
181736public:
181737 HivePartitionedColumnData(ClientContext &context, vector<LogicalType> types, vector<idx_t> partition_by_cols,
181738 shared_ptr<GlobalHivePartitionState> global_state = nullptr);
181739 void ComputePartitionIndices(PartitionedColumnDataAppendState &state, DataChunk &input) override;
181740
181742 std::map<idx_t, const HivePartitionKey *> GetReverseMap();
181743
181744protected:
181746 idx_t RegisterNewPartition(HivePartitionKey key, PartitionedColumnDataAppendState &state);
181748 void AddNewPartition(HivePartitionKey key, idx_t partition_id, PartitionedColumnDataAppendState &state);
181749
181750private:
181751 void InitializeKeys();
181752
181753protected:
181755 shared_ptr<GlobalHivePartitionState> global_state;
181759 vector<idx_t> group_by_columns;
181761 Vector hashes_v;
181763 vector<HivePartitionKey> keys;
181764};
181765
181766}
181767
181768
181769
181770
181771namespace duckdb {
181772struct BindInfo;
181773class MultiFileList;
181774
181775enum class MultiFileColumnMappingMode :
uint8_t { BY_NAME, BY_FIELD_ID };
181776
181777struct MultiFileOptions {
181778 bool filename = false;
181779 bool hive_partitioning = false;
181780 bool auto_detect_hive_partitioning = true;
181781 bool union_by_name = false;
181782 bool hive_types_autocast = true;
181783 MultiFileColumnMappingMode mapping = MultiFileColumnMappingMode::BY_NAME;
181784
181785 case_insensitive_map_t<LogicalType> hive_types_schema;
181786
181787
181788 static constexpr const char *DEFAULT_FILENAME_COLUMN = "filename";
181789 string filename_column = DEFAULT_FILENAME_COLUMN;
181790
181791 case_insensitive_map_t<Value> custom_options;
181792
181793 DUCKDB_API void Serialize(Serializer &serializer) const;
181794 DUCKDB_API static MultiFileOptions Deserialize(Deserializer &source);
181795 DUCKDB_API void AddBatchInfo(BindInfo &bind_info) const;
181796 DUCKDB_API void AutoDetectHivePartitioning(MultiFileList &files, ClientContext &context);
181797 DUCKDB_API static bool AutoDetectHivePartitioningInternal(MultiFileList &files, ClientContext &context);
181798 DUCKDB_API void AutoDetectHiveTypesInternal(MultiFileList &files, ClientContext &context);
181799 DUCKDB_API void VerifyHiveTypesArePartitions(const std::map<string, string> &partitions) const;
181800 DUCKDB_API LogicalType GetHiveLogicalType(const string &hive_partition_column) const;
181801 DUCKDB_API Value GetHivePartitionValue(const string &base, const string &entry, ClientContext &context) const;
181802 DUCKDB_API bool AnySet() const;
181803};
181804
181805}
181806
181807
181808
181809
181810
181811
181812
181813
181814
181815
181816
181817
181818namespace duckdb {
181821struct SetColumns {
181822 SetColumns(const vector<LogicalType> *types_p, const vector<string> *names_p);
181823 SetColumns();
181825 const vector<LogicalType> *types = nullptr;
181827 const vector<string> *names = nullptr;
181829 bool IsSet() const;
181833 bool IsCandidateUnacceptable(const idx_t num_cols, bool null_padding, bool ignore_errors,
181834 bool last_value_always_empty) const;
181835
181836 string ToString() const;
181837};
181838
181839}
181840
181841
181842namespace duckdb {
181843
181844struct DialectOptions {
181845 CSVStateMachineOptions state_machine_options;
181847 idx_t num_cols = 0;
181849 CSVOption<bool> header = false;
181851 map<LogicalTypeId, CSVOption<StrpTimeFormat>> date_format = {{LogicalTypeId::DATE, {}},
181852 {LogicalTypeId::TIMESTAMP, {}}};
181854 CSVOption<idx_t> skip_rows = 0;
181855 idx_t rows_until_header = 0;
181856};
181857
181858struct CSVReaderOptions {
181859 CSVReaderOptions() {
181860 }
181861 CSVReaderOptions(CSVOption<char> single_byte_delimiter, const CSVOption<string> &multi_byte_delimiter);
181862
181863
181864
181866 DialectOptions dialect_options;
181868 CSVOption<bool> ignore_errors = false;
181870 CSVOption<bool> store_rejects = false;
181872 CSVOption<string> rejects_table_name = {"reject_errors"};
181874 CSVOption<string> rejects_scan_name = {"reject_scans"};
181876 idx_t rejects_limit = 0;
181878 idx_t buffer_sample_size =
static_cast<idx_t>(STANDARD_VECTOR_SIZE * 50);
181880 vector<string> null_str = {""};
181883 FileCompressionType compression = FileCompressionType::AUTO_DETECT;
181885 bool allow_quoted_nulls = true;
181886 char comment = '\0';
181887
181889 char thousands_separator = '\0';
181890
181891
181892
181893
181895 case_insensitive_map_t<idx_t> sql_types_per_column;
181897 vector<LogicalType> sql_type_list;
181899 vector<string> name_list;
181901 bool columns_set = false;
181903 vector<LogicalType> auto_type_candidates = {
181904 LogicalType::VARCHAR, LogicalType::DOUBLE, LogicalType::BIGINT,
181905 LogicalType::TIMESTAMP_TZ, LogicalType::TIMESTAMP, LogicalType::DATE,
181906 LogicalType::TIME, LogicalType::BOOLEAN, LogicalType::SQLNULL};
181908 string sniffer_user_mismatch_error;
181910 vector<bool> was_type_manually_set;
181911
181912
181913
181916 static constexpr idx_t max_line_size_default = 2000000;
181917 CSVOption<idx_t> maximum_line_size = max_line_size_default;
181919 bool normalize_names = false;
181921 unordered_set<string> force_not_null_names;
181923 vector<bool> force_not_null;
181925 static constexpr idx_t sniff_size = 2048;
181926
181929 int64_t files_to_sniff = 10;
181930
181932 idx_t sample_size_chunks = 20480 / sniff_size;
181934 bool all_varchar = false;
181936 bool auto_detect = true;
181938 string file_path;
181940 CSVOption<idx_t> buffer_size_option = CSVBuffer::ROWS_PER_BUFFER * max_line_size_default;
181942 string decimal_separator = ".";
181944 bool null_padding = false;
181946 bool parallel = true;
181947
181949 string encoding = "utf-8";
181951 map<string, string> user_defined_parameters;
181952
181954 string GetUserDefinedParameters() const;
181955
181956
181957
181958
181960 vector<bool> force_quote;
181962 string prefix;
181963 string suffix;
181964 string write_newline;
181965
181967 map<LogicalTypeId, Value> write_date_format = {{LogicalTypeId::DATE, Value()}, {LogicalTypeId::TIMESTAMP, Value()}};
181969 map<LogicalTypeId, bool> has_format = {{LogicalTypeId::DATE, false}, {LogicalTypeId::TIMESTAMP, false}};
181971 bool multi_file_reader = false;
181972
181973 void SetCompression(const string &compression);
181974
181975 bool GetHeader() const;
181976 void SetHeader(bool has_header);
181977
181978 string GetEscape() const;
181979 void SetEscape(const string &escape);
181980
181981 idx_t GetSkipRows()
const;
181982 void SetSkipRows(int64_t
rows);
181983
181984 void SetQuote(const string "e);
181985 string GetQuote() const;
181986 void SetComment(const string &comment);
181987 string GetComment() const;
181988 void SetDelimiter(const string &delimiter);
181989 string GetDelimiter() const;
181990
181992 bool IgnoreErrors() const;
181993
181994 string GetNewline() const;
181995 void SetNewline(const string &input);
181996
181997 bool GetRFC4180() const;
181998 void SetRFC4180(bool rfc4180);
181999
182000 CSVOption<char> GetSingleByteDelimiter() const;
182001 CSVOption<string> GetMultiByteDelimiter() const;
182002
182005 bool SetBaseOption(const string &loption, const Value &value, bool write_option = false);
182006
182010 void SetReadOption(const string &loption, const Value &value, vector<string> &expected_names);
182011 void SetWriteOption(const string &loption, const Value &value);
182012 void SetDateFormat(LogicalTypeId type,
const string &
format,
bool read_format);
182013 void ToNamedParameters(named_parameter_map_t &out) const;
182014 void FromNamedParameters(const named_parameter_map_t &in, ClientContext &context, MultiFileOptions &file_options);
182015 void ParseOption(ClientContext &context, const string &key, const Value &val);
182017 void Verify(MultiFileOptions &file_options);
182018
182019 string ToString(
const String ¤t_file_path)
const;
182021 bool WasTypeManuallySet(idx_t i) const;
182022
182023 string NewLineIdentifierToString() const {
182024 switch (dialect_options.state_machine_options.new_line.GetValue()) {
182025 case NewLineIdentifier::SINGLE_N:
182026 return "\\n";
182027 case NewLineIdentifier::SINGLE_R:
182028 return "\\r";
182029 case NewLineIdentifier::CARRY_ON:
182030 return "\\r\\n";
182031 default:
182032 return "";
182033 }
182034 }
182035};
182036}
182037
182038
182039namespace duckdb {
182040
182041class Deserializer {
182042protected:
182043 bool deserialize_enum_from_string = false;
182044 SerializationData data;
182045
182046public:
182047 virtual ~Deserializer() {
182048 }
182049
182050 class List {
182051 friend Deserializer;
182052
182053 private:
182054 Deserializer &deserializer;
182055 explicit List(Deserializer &deserializer) : deserializer(deserializer) {
182056 }
182057
182058 public:
182059
182060 template <class T>
182061 T ReadElement();
182062
182064 template <class T>
182065 void ReadElement(data_ptr_t &ptr, idx_t size);
182066
182067
182068 template <class FUNC>
182069 void ReadObject(FUNC f);
182070 };
182071
182072public:
182073 virtual bool CanDeserializeProperty(const field_id_t field_id, const char *tag) = 0;
182074
182075
182076 template <typename T>
182077 inline void ReadProperty(const field_id_t field_id, const char *tag, T &ret) {
182078 OnPropertyBegin(field_id, tag);
182079 ret = Read<T>();
182080 OnPropertyEnd();
182081 }
182082
182083
182084 template <typename T>
182085 inline T ReadProperty(const field_id_t field_id, const char *tag) {
182086 OnPropertyBegin(field_id, tag);
182087 auto ret = Read<T>();
182088 OnPropertyEnd();
182089 return ret;
182090 }
182091
182092
182093 template <typename T>
182094 inline T ReadPropertyWithDefault(const field_id_t field_id, const char *tag) {
182095 if (!OnOptionalPropertyBegin(field_id, tag)) {
182096 OnOptionalPropertyEnd(false);
182097 return std::forward<T>(SerializationDefaultValue::GetDefault<T>());
182098 }
182099 auto ret = Read<T>();
182100 OnOptionalPropertyEnd(true);
182101 return ret;
182102 }
182103
182104 template <typename T>
182105 inline T ReadPropertyWithExplicitDefault(const field_id_t field_id, const char *tag, T default_value) {
182106 if (!OnOptionalPropertyBegin(field_id, tag)) {
182107 OnOptionalPropertyEnd(false);
182108 return std::forward<T>(default_value);
182109 }
182110 auto ret = Read<T>();
182111 OnOptionalPropertyEnd(true);
182112 return ret;
182113 }
182114
182115
182116 template <typename T>
182117 inline void ReadPropertyWithDefault(const field_id_t field_id, const char *tag, T &ret) {
182118 if (!OnOptionalPropertyBegin(field_id, tag)) {
182119 ret = std::forward<T>(SerializationDefaultValue::GetDefault<T>());
182120 OnOptionalPropertyEnd(false);
182121 return;
182122 }
182123 ret = Read<T>();
182124 OnOptionalPropertyEnd(true);
182125 }
182126
182127 template <typename T>
182128 inline void ReadPropertyWithExplicitDefault(const field_id_t field_id, const char *tag, T &ret, T default_value) {
182129 if (!OnOptionalPropertyBegin(field_id, tag)) {
182130 ret = std::forward<T>(default_value);
182131 OnOptionalPropertyEnd(false);
182132 return;
182133 }
182134 ret = Read<T>();
182135 OnOptionalPropertyEnd(true);
182136 }
182137
182138 template <typename T>
182139 inline void ReadPropertyWithExplicitDefault(const field_id_t field_id, const char *tag, CSVOption<T> &ret,
182140 T default_value) {
182141 if (!OnOptionalPropertyBegin(field_id, tag)) {
182142 ret = std::forward<T>(default_value);
182143 OnOptionalPropertyEnd(false);
182144 return;
182145 }
182146 ret = Read<T>();
182147 OnOptionalPropertyEnd(true);
182148 }
182149
182150
182151
182152 inline void ReadProperty(const field_id_t field_id, const char *tag, data_ptr_t ret, idx_t count) {
182153 OnPropertyBegin(field_id, tag);
182154 ReadDataPtr(ret, count);
182155 OnPropertyEnd();
182156 }
182157
182158
182159 template <typename T>
182160 inline void ReadDeletedProperty(const field_id_t field_id, const char *tag) {
182161
182162 if (!OnOptionalPropertyBegin(field_id, tag)) {
182163 OnOptionalPropertyEnd(false);
182164 return;
182165 }
182166
182167 (void)Read<T>();
182168 OnOptionalPropertyEnd(true);
182169 }
182170
182172 template <class T>
182173 void Set(T entry) {
182174 return data.Set<T>(entry);
182175 }
182176
182178 template <class T>
182179 T Get() {
182180 return data.Get<T>();
182181 }
182182
182183 template <class T>
182184 optional_ptr<T> TryGet() {
182185 return data.TryGet<T>();
182186 }
182187
182189 template <class T>
182190 void Unset() {
182191 return data.Unset<T>();
182192 }
182193
182194 SerializationData &GetSerializationData() {
182195 return data;
182196 }
182197
182198 void SetSerializationData(const SerializationData &other) {
182199 data = other;
182200 }
182201
182202 template <class FUNC>
182203 void ReadListInternal(FUNC func) {
182204 auto size = OnListBegin();
182205 List list {*this};
182206 for (idx_t i = 0; i <
size; i++) {
182207 func(list, i);
182208 }
182209 OnListEnd();
182210 }
182211
182212 template <class FUNC>
182213 void ReadList(const field_id_t field_id, const char *tag, FUNC func) {
182214 OnPropertyBegin(field_id, tag);
182215 ReadListInternal(func);
182216 OnPropertyEnd();
182217 }
182218
182219 template <class FUNC>
182220 void ReadOptionalList(const field_id_t field_id, const char *tag, FUNC func) {
182221 if (!OnOptionalPropertyBegin(field_id, tag)) {
182222 OnOptionalPropertyEnd(false);
182223 return;
182224 }
182225 ReadListInternal(func);
182226 OnOptionalPropertyEnd(true);
182227 }
182228
182229 template <class FUNC>
182230 void ReadObject(const field_id_t field_id, const char *tag, FUNC func) {
182231 OnPropertyBegin(field_id, tag);
182232 OnObjectBegin();
182233 func(*this);
182234 OnObjectEnd();
182235 OnPropertyEnd();
182236 }
182237
182238private:
182239
182240 template <typename T = void>
182241 inline typename std::enable_if<has_deserialize<T>::value, T>::type Read() {
182242 OnObjectBegin();
182243 auto val = T::Deserialize(*this);
182244 OnObjectEnd();
182245 return val;
182246 }
182247
182248
182249 template <class T, typename ELEMENT_TYPE = typename is_optionally_owned_ptr<T>::ELEMENT_TYPE>
182250 inline typename std::enable_if<is_optionally_owned_ptr<T>::value, T>::type Read() {
182251 return optionally_owned_ptr<ELEMENT_TYPE>(Read<unique_ptr<ELEMENT_TYPE>>());
182252 }
182253
182254
182255 template <class T, typename ELEMENT_TYPE = typename is_unique_ptr<T>::ELEMENT_TYPE>
182256 inline typename std::enable_if<is_unique_ptr<T>::value && has_deserialize<ELEMENT_TYPE>::value, T>::type Read() {
182257 unique_ptr<ELEMENT_TYPE> ptr = nullptr;
182258 auto is_present = OnNullableBegin();
182259 if (is_present) {
182260 OnObjectBegin();
182261 ptr = ELEMENT_TYPE::Deserialize(*this);
182262 OnObjectEnd();
182263 }
182264 OnNullableEnd();
182265 return ptr;
182266 }
182267
182268
182269 template <class T, typename ELEMENT_TYPE = typename is_unique_ptr<T>::ELEMENT_TYPE>
182270 inline typename std::enable_if<is_unique_ptr<T>::value && !has_deserialize<ELEMENT_TYPE>::value, T>::type Read() {
182271 unique_ptr<ELEMENT_TYPE> ptr = nullptr;
182272 auto is_present = OnNullableBegin();
182273 if (is_present) {
182274 OnObjectBegin();
182275 ptr = make_uniq<ELEMENT_TYPE>(Read<ELEMENT_TYPE>());
182276 OnObjectEnd();
182277 }
182278 OnNullableEnd();
182279 return ptr;
182280 }
182281
182282
182283 template <typename T = void>
182284 inline typename std::enable_if<is_shared_ptr<T>::value, T>::type Read() {
182285 using ELEMENT_TYPE = typename is_shared_ptr<T>::ELEMENT_TYPE;
182286 shared_ptr<ELEMENT_TYPE> ptr = nullptr;
182287 auto is_present = OnNullableBegin();
182288 if (is_present) {
182289 OnObjectBegin();
182290 ptr = ELEMENT_TYPE::Deserialize(*this);
182291 OnObjectEnd();
182292 }
182293 OnNullableEnd();
182294 return ptr;
182295 }
182296
182297
182298 template <typename T = void>
182299 inline typename std::enable_if<is_vector<T>::value, T>::type Read() {
182300 using ELEMENT_TYPE = typename is_vector<T>::ELEMENT_TYPE;
182301 T vec;
182302 auto size = OnListBegin();
182303 for (idx_t i = 0; i <
size; i++) {
182304 vec.push_back(Read<ELEMENT_TYPE>());
182305 }
182306 OnListEnd();
182307 return vec;
182308 }
182309
182310 template <typename T = void>
182311 inline typename std::enable_if<is_unsafe_vector<T>::value, T>::type Read() {
182312 using ELEMENT_TYPE = typename is_unsafe_vector<T>::ELEMENT_TYPE;
182313 T vec;
182314 auto size = OnListBegin();
182315 for (idx_t i = 0; i <
size; i++) {
182316 vec.push_back(Read<ELEMENT_TYPE>());
182317 }
182318 OnListEnd();
182319
182320 return vec;
182321 }
182322
182323
182324 template <typename T = void>
182325 inline typename std::enable_if<is_unordered_map<T>::value, T>::type Read() {
182326 using KEY_TYPE = typename is_unordered_map<T>::KEY_TYPE;
182327 using VALUE_TYPE = typename is_unordered_map<T>::VALUE_TYPE;
182328
182329 T map;
182330 auto size = OnListBegin();
182331 for (idx_t i = 0; i <
size; i++) {
182332 OnObjectBegin();
182333 auto key = ReadProperty<KEY_TYPE>(0, "key");
182334 auto value = ReadProperty<VALUE_TYPE>(1, "value");
182335 OnObjectEnd();
182336 map[std::move(key)] = std::move(value);
182337 }
182338 OnListEnd();
182339 return map;
182340 }
182341
182342 template <typename T = void>
182343 inline typename std::enable_if<is_map<T>::value, T>::type Read() {
182344 using KEY_TYPE = typename is_map<T>::KEY_TYPE;
182345 using VALUE_TYPE = typename is_map<T>::VALUE_TYPE;
182346
182347 T map;
182348 auto size = OnListBegin();
182349 for (idx_t i = 0; i <
size; i++) {
182350 OnObjectBegin();
182351 auto key = ReadProperty<KEY_TYPE>(0, "key");
182352 auto value = ReadProperty<VALUE_TYPE>(1, "value");
182353 OnObjectEnd();
182354 map[std::move(key)] = std::move(value);
182355 }
182356 OnListEnd();
182357 return map;
182358 }
182359
182360 template <typename T = void>
182361 inline typename std::enable_if<is_insertion_preserving_map<T>::value, T>::type Read() {
182362 using VALUE_TYPE = typename is_insertion_preserving_map<T>::VALUE_TYPE;
182363
182364 T map;
182365 auto size = OnListBegin();
182366 for (idx_t i = 0; i <
size; i++) {
182367 OnObjectBegin();
182368 auto key = ReadProperty<string>(0, "key");
182369 auto value = ReadProperty<VALUE_TYPE>(1, "value");
182370 OnObjectEnd();
182371 map[key] = std::move(value);
182372 }
182373 OnListEnd();
182374 return map;
182375 }
182376
182377
182378 template <typename T = void>
182379 inline typename std::enable_if<is_unordered_set<T>::value, T>::type Read() {
182380 using ELEMENT_TYPE = typename is_unordered_set<T>::ELEMENT_TYPE;
182381 auto size = OnListBegin();
182382 T set;
182383 for (idx_t i = 0; i <
size; i++) {
182384 set.insert(Read<ELEMENT_TYPE>());
182385 }
182386 OnListEnd();
182387 return set;
182388 }
182389
182390
182391 template <typename T = void>
182392 inline typename std::enable_if<is_set<T>::value, T>::type Read() {
182393 using ELEMENT_TYPE = typename is_set<T>::ELEMENT_TYPE;
182394 auto size = OnListBegin();
182395 T set;
182396 for (idx_t i = 0; i <
size; i++) {
182397 set.insert(Read<ELEMENT_TYPE>());
182398 }
182399 OnListEnd();
182400 return set;
182401 }
182402
182403
182404 template <typename T = void>
182405 inline typename std::enable_if<is_pair<T>::value, T>::type Read() {
182406 using FIRST_TYPE = typename is_pair<T>::FIRST_TYPE;
182407 using SECOND_TYPE = typename is_pair<T>::SECOND_TYPE;
182408 OnObjectBegin();
182409 auto first = ReadProperty<FIRST_TYPE>(0, "first");
182410 auto second = ReadProperty<SECOND_TYPE>(1, "second");
182411 OnObjectEnd();
182412 return std::make_pair(first, second);
182413 }
182414
182415
182416 template <typename T = void>
182417 inline typename std::enable_if<is_queue<T>::value, T>::type Read() {
182418 using ELEMENT_TYPE = typename is_queue<T>::ELEMENT_TYPE;
182419 T queue;
182420 auto size = OnListBegin();
182421 for (idx_t i = 0; i <
size; i++) {
182422 queue.emplace(Read<ELEMENT_TYPE>());
182423 }
182424 OnListEnd();
182425 return queue;
182426 }
182427
182428
182429
182430 template <typename T = void>
182431 inline typename std::enable_if<std::is_same<T, bool>::value, T>::type Read() {
182432 return ReadBool();
182433 }
182434
182435
182436 template <typename T = void>
182437 inline typename std::enable_if<std::is_same<T, char>::value, T>::type Read() {
182438 return ReadChar();
182439 }
182440
182441
182442 template <typename T = void>
182443 inline typename std::enable_if<std::is_same<T, int8_t>::value, T>::type Read() {
182444 return ReadSignedInt8();
182445 }
182446
182447
182448 template <typename T = void>
182449 inline typename std::enable_if<std::is_same<T, uint8_t>::value, T>::type Read() {
182450 return ReadUnsignedInt8();
182451 }
182452
182453
182454 template <typename T = void>
182455 inline typename std::enable_if<std::is_same<T, int16_t>::value, T>::type Read() {
182456 return ReadSignedInt16();
182457 }
182458
182459
182460 template <typename T = void>
182461 inline typename std::enable_if<std::is_same<T, uint16_t>::value, T>::type Read() {
182462 return ReadUnsignedInt16();
182463 }
182464
182465
182466 template <typename T = void>
182467 inline typename std::enable_if<std::is_same<T, int32_t>::value, T>::type Read() {
182468 return ReadSignedInt32();
182469 }
182470
182471
182472 template <typename T = void>
182473 inline typename std::enable_if<std::is_same<T, uint32_t>::value, T>::type Read() {
182474 return ReadUnsignedInt32();
182475 }
182476
182477
182478 template <typename T = void>
182479 inline typename std::enable_if<std::is_same<T, int64_t>::value, T>::type Read() {
182480 return ReadSignedInt64();
182481 }
182482
182483
182484 template <typename T = void>
182485 inline typename std::enable_if<std::is_same<T, uint64_t>::value, T>::type Read() {
182486 return ReadUnsignedInt64();
182487 }
182488
182489
182490 template <typename T = void>
182491 inline typename std::enable_if<std::is_same<T, float>::value, T>::type Read() {
182492 return ReadFloat();
182493 }
182494
182495
182496 template <typename T = void>
182497 inline typename std::enable_if<std::is_same<T, double>::value, T>::type Read() {
182498 return ReadDouble();
182499 }
182500
182501
182502 template <typename T = void>
182503 inline typename std::enable_if<std::is_same<T, string>::value, T>::type Read() {
182504 return ReadString();
182505 }
182506
182507
182508 template <typename T = void>
182509 inline typename std::enable_if<std::is_enum<T>::value, T>::type Read() {
182510 if (deserialize_enum_from_string) {
182511 auto str = ReadString();
182512 return EnumUtil::FromString<T>(str.c_str());
182513 } else {
182514 return (T)Read<typename std::underlying_type<T>::type>();
182515 }
182516 }
182517
182518
182519 template <typename T = void>
182520 inline typename std::enable_if<std::is_same<T, hugeint_t>::value, T>::type Read() {
182521 return ReadHugeInt();
182522 }
182523
182524
182525 template <typename T = void>
182526 inline typename std::enable_if<std::is_same<T, uhugeint_t>::value, T>::type Read() {
182527 return ReadUhugeInt();
182528 }
182529
182530
182531 template <typename T = void>
182532 inline typename std::enable_if<std::is_same<T, LogicalIndex>::value, T>::type Read() {
182533 return LogicalIndex(ReadUnsignedInt64());
182534 }
182535
182536
182537 template <typename T = void>
182538 inline typename std::enable_if<std::is_same<T, PhysicalIndex>::value, T>::type Read() {
182539 return PhysicalIndex(ReadUnsignedInt64());
182540 }
182541
182542
182543 template <typename T = void>
182544 inline typename std::enable_if<std::is_same<T, optional_idx>::value, T>::type Read() {
182545 auto idx = ReadUnsignedInt64();
182546 return idx == DConstants::INVALID_INDEX ? optional_idx() : optional_idx(idx);
182547 }
182548
182549protected:
182550
182551 virtual void OnPropertyBegin(const field_id_t field_id, const char *tag) = 0;
182552 virtual void OnPropertyEnd() = 0;
182553 virtual bool OnOptionalPropertyBegin(const field_id_t field_id, const char *tag) = 0;
182554 virtual void OnOptionalPropertyEnd(bool present) = 0;
182555
182556 virtual void OnObjectBegin() = 0;
182557 virtual void OnObjectEnd() = 0;
182558 virtual idx_t OnListBegin() = 0;
182559 virtual void OnListEnd() = 0;
182560 virtual bool OnNullableBegin() = 0;
182561 virtual void OnNullableEnd() = 0;
182562
182563
182564 virtual bool ReadBool() = 0;
182565 virtual char ReadChar() {
182566 throw NotImplementedException("ReadChar not implemented");
182567 }
182568 virtual int8_t ReadSignedInt8() = 0;
182569 virtual uint8_t ReadUnsignedInt8() = 0;
182570 virtual int16_t ReadSignedInt16() = 0;
182571 virtual uint16_t ReadUnsignedInt16() = 0;
182572 virtual int32_t ReadSignedInt32() = 0;
182573 virtual uint32_t ReadUnsignedInt32() = 0;
182574 virtual int64_t ReadSignedInt64() = 0;
182575 virtual uint64_t ReadUnsignedInt64() = 0;
182576 virtual hugeint_t ReadHugeInt() = 0;
182577 virtual uhugeint_t ReadUhugeInt() = 0;
182578 virtual float ReadFloat() = 0;
182579 virtual double ReadDouble() = 0;
182580 virtual string ReadString() = 0;
182581 virtual void ReadDataPtr(data_ptr_t &ptr, idx_t count) = 0;
182582};
182583
182584template <class FUNC>
182585void Deserializer::List::ReadObject(FUNC f) {
182586 deserializer.OnObjectBegin();
182587 f(deserializer);
182588 deserializer.OnObjectEnd();
182589}
182590
182591template <class T>
182592T Deserializer::List::ReadElement() {
182593 return deserializer.Read<T>();
182594}
182595
182596template <class T>
182597void Deserializer::List::ReadElement(data_ptr_t &ptr, idx_t size) {
182598 deserializer.ReadDataPtr(ptr, size);
182599}
182600
182601}
182602
182603
182604
182605
182606
182607
182608
182609
182610
182611
182612
182613
182614
182615
182616
182617
182618
182619
182620
182621
182622
182623
182624
182625
182626
182627
182628
182629
182630
182631
182632
182633
182634namespace duckdb {
182635
182637class Uhugeint {
182638public:
182640 static string ToString(uhugeint_t input);
182641
182642 template <class T>
182643 DUCKDB_API static bool TryCast(uhugeint_t input, T &result);
182644
182645 template <class T>
182646 static T Cast(uhugeint_t input) {
182647 T result = 0;
182648 TryCast(input, result);
182649 return result;
182650 }
182651
182652 template <class T>
182653 static bool TryConvert(T value, uhugeint_t &result);
182654
182655 template <class T>
182656 static uhugeint_t Convert(T value) {
182657 uhugeint_t result;
182658 if (!TryConvert(value, result)) {
182659 throw OutOfRangeException(double(value), GetTypeId<T>(), GetTypeId<uhugeint_t>());
182660 }
182661 return result;
182662 }
182663
182664 static bool TryNegate(uhugeint_t input, uhugeint_t &result);
182665
182666
182667
182668 template <bool CHECK_OVERFLOW = true>
182669 inline static void NegateInPlace(uhugeint_t &input) {
182670 if (!TryNegate(input, input)) {
182671 throw OutOfRangeException("UHUGEINT is out of range");
182672 }
182673 }
182674
182675 template <bool CHECK_OVERFLOW = true>
182676 inline static uhugeint_t Negate(uhugeint_t input) {
182677 NegateInPlace<CHECK_OVERFLOW>(input);
182678 return input;
182679 }
182680
182681 static bool TryMultiply(uhugeint_t lhs, uhugeint_t rhs, uhugeint_t &result);
182682
182683 template <bool CHECK_OVERFLOW = true>
182684 inline static uhugeint_t Multiply(uhugeint_t lhs, uhugeint_t rhs) {
182685 uhugeint_t result;
182686 if (!TryMultiply(lhs, rhs, result)) {
182687 throw OutOfRangeException("Overflow in UHUGEINT multiplication: %s * %s", lhs.ToString(), rhs.ToString());
182688 }
182689 return result;
182690 }
182691
182692 static bool TryDivMod(uhugeint_t lhs, uhugeint_t rhs, uhugeint_t &result, uhugeint_t &remainder);
182693
182694 template <bool CHECK_OVERFLOW = true>
182695 inline static uhugeint_t Divide(uhugeint_t lhs, uhugeint_t rhs) {
182696
182697 if (rhs == 0) {
182698 throw OutOfRangeException("Division of UHUGEINT by zero: %s / %s", lhs.ToString(), rhs.ToString());
182699 }
182700 return Divide<false>(lhs, rhs);
182701 }
182702
182703 template <bool CHECK_OVERFLOW = true>
182704 inline static uhugeint_t Modulo(uhugeint_t lhs, uhugeint_t rhs) {
182705 if (rhs == 0) {
182706 throw OutOfRangeException("Modulo of UHUGEINT by zero: %s %% %s", lhs.ToString(), rhs.ToString());
182707 }
182708 return Modulo<false>(lhs, rhs);
182709 }
182710
182711 static bool TryAddInPlace(uhugeint_t &lhs, uhugeint_t rhs);
182712
182713 template <bool CHECK_OVERFLOW = true>
182714 inline static uhugeint_t Add(uhugeint_t lhs, uhugeint_t rhs) {
182715 if (!TryAddInPlace(lhs, rhs)) {
182716 throw OutOfRangeException("Overflow in UHUGEINT addition: %s + %s", lhs.ToString(), rhs.ToString());
182717 }
182718 return lhs;
182719 }
182720
182721 static bool TrySubtractInPlace(uhugeint_t &lhs, uhugeint_t rhs);
182722
182723 template <bool CHECK_OVERFLOW = true>
182724 inline static uhugeint_t Subtract(uhugeint_t lhs, uhugeint_t rhs) {
182725 if (!TrySubtractInPlace(lhs, rhs)) {
182726 throw OutOfRangeException("Underflow in HUGEINT subtraction: %s - %s", lhs.ToString(), rhs.ToString());
182727 }
182728 return lhs;
182729 }
182730
182731
182732 static uhugeint_t DivMod(uhugeint_t lhs, uhugeint_t rhs, uhugeint_t &remainder);
182733
182734 static int Sign(hugeint_t n);
182735 static hugeint_t Abs(hugeint_t n);
182736
182737
182738 static bool Equals(uhugeint_t lhs, uhugeint_t rhs) {
182739 bool lower_equals = lhs.lower == rhs.lower;
182740 bool upper_equals = lhs.upper == rhs.upper;
182741 return lower_equals && upper_equals;
182742 }
182743
182744 static bool NotEquals(uhugeint_t lhs, uhugeint_t rhs) {
182745 return !Equals(lhs, rhs);
182746 }
182747
182748 static bool GreaterThan(uhugeint_t lhs, uhugeint_t rhs) {
182749 bool upper_bigger = lhs.upper > rhs.upper;
182750 bool upper_equal = lhs.upper == rhs.upper;
182751 bool lower_bigger = lhs.lower > rhs.lower;
182752 return upper_bigger || (upper_equal && lower_bigger);
182753 }
182754
182755 static bool GreaterThanEquals(uhugeint_t lhs, uhugeint_t rhs) {
182756 bool upper_bigger = lhs.upper > rhs.upper;
182757 bool upper_equal = lhs.upper == rhs.upper;
182758 bool lower_bigger_equals = lhs.lower >= rhs.lower;
182759 return upper_bigger || (upper_equal && lower_bigger_equals);
182760 }
182761
182762 static bool LessThan(uhugeint_t lhs, uhugeint_t rhs) {
182763 bool upper_smaller = lhs.upper < rhs.upper;
182764 bool upper_equal = lhs.upper == rhs.upper;
182765 bool lower_smaller = lhs.lower < rhs.lower;
182766 return upper_smaller || (upper_equal && lower_smaller);
182767 }
182768
182769 static bool LessThanEquals(uhugeint_t lhs, uhugeint_t rhs) {
182770 bool upper_smaller = lhs.upper < rhs.upper;
182771 bool upper_equal = lhs.upper == rhs.upper;
182772 bool lower_smaller_equals = lhs.lower <= rhs.lower;
182773 return upper_smaller || (upper_equal && lower_smaller_equals);
182774 }
182775
182776 static constexpr uint8_t CACHED_POWERS_OF_TEN = 39;
182777 static const uhugeint_t POWERS_OF_TEN[CACHED_POWERS_OF_TEN];
182778};
182779
182780template <>
182781DUCKDB_API bool Uhugeint::TryCast(uhugeint_t input, int8_t &result);
182782template <>
182783DUCKDB_API bool Uhugeint::TryCast(uhugeint_t input, int16_t &result);
182784template <>
182785DUCKDB_API bool Uhugeint::TryCast(uhugeint_t input, int32_t &result);
182786template <>
182787DUCKDB_API bool Uhugeint::TryCast(uhugeint_t input, int64_t &result);
182788template <>
182789DUCKDB_API bool Uhugeint::TryCast(uhugeint_t input, uint8_t &result);
182790template <>
182791DUCKDB_API bool Uhugeint::TryCast(uhugeint_t input, uint16_t &result);
182792template <>
182793DUCKDB_API bool Uhugeint::TryCast(uhugeint_t input, uint32_t &result);
182794template <>
182795DUCKDB_API bool Uhugeint::TryCast(uhugeint_t input, uint64_t &result);
182796template <>
182797DUCKDB_API bool Uhugeint::TryCast(uhugeint_t input, hugeint_t &result);
182798template <>
182799DUCKDB_API bool Uhugeint::TryCast(uhugeint_t input, uhugeint_t &result);
182800template <>
182801DUCKDB_API bool Uhugeint::TryCast(uhugeint_t input, float &result);
182802template <>
182803DUCKDB_API bool Uhugeint::TryCast(uhugeint_t input, double &result);
182804
182805template <>
182806bool Uhugeint::TryConvert(int8_t value, uhugeint_t &result);
182807template <>
182808bool Uhugeint::TryConvert(int16_t value, uhugeint_t &result);
182809template <>
182810bool Uhugeint::TryConvert(int32_t value, uhugeint_t &result);
182811template <>
182812bool Uhugeint::TryConvert(int64_t value, uhugeint_t &result);
182813template <>
182814bool Uhugeint::TryConvert(uint8_t value, uhugeint_t &result);
182815template <>
182816bool Uhugeint::TryConvert(uint16_t value, uhugeint_t &result);
182817template <>
182818bool Uhugeint::TryConvert(uint32_t value, uhugeint_t &result);
182819template <>
182820bool Uhugeint::TryConvert(uint64_t value, uhugeint_t &result);
182821template <>
182822bool Uhugeint::TryConvert(float value, uhugeint_t &result);
182823template <>
182824bool Uhugeint::TryConvert(double value, uhugeint_t &result);
182825template <>
182826bool Uhugeint::TryConvert(long double value, uhugeint_t &result);
182827template <>
182828bool Uhugeint::TryConvert(const char *value, uhugeint_t &result);
182829
182830}
182831
182832
182833
182834
182835
182836
182837
182838
182839
182840
182841
182842
182843
182844
182845
182846
182847
182848
182849namespace duckdb {
182850
182851struct ValueOperations {
182852
182853
182854
182855
182856 static bool Equals(const Value &left, const Value &right);
182857
182858 static bool NotEquals(const Value &left, const Value &right);
182859
182860 static bool GreaterThan(const Value &left, const Value &right);
182861
182862 static bool GreaterThanEquals(const Value &left, const Value &right);
182863
182864 static bool LessThan(const Value &left, const Value &right);
182865
182866 static bool LessThanEquals(const Value &left, const Value &right);
182867
182868
182869
182870
182871 static bool NotDistinctFrom(const Value &left, const Value &right);
182872
182873 static bool DistinctFrom(const Value &left, const Value &right);
182874
182875 static bool DistinctGreaterThan(const Value &left, const Value &right);
182876
182877 static bool DistinctGreaterThanEquals(const Value &left, const Value &right);
182878
182879 static bool DistinctLessThan(const Value &left, const Value &right);
182880
182881 static bool DistinctLessThanEquals(const Value &left, const Value &right);
182882};
182883}
182884
182885
182886
182887
182888
182889namespace duckdb {
182890
182891class SerializationOptions {
182892public:
182893 SerializationOptions() = default;
182894 explicit SerializationOptions(AttachedDatabase &db);
182895
182896 bool serialize_enum_as_string = false;
182897 bool serialize_default_values = false;
182898 SerializationCompatibility serialization_compatibility = SerializationCompatibility::Default();
182899};
182900
182901class Serializer {
182902protected:
182903 SerializationOptions options;
182904 SerializationData data;
182905
182906public:
182907 virtual ~Serializer() {
182908 }
182909
182910 bool ShouldSerialize(idx_t version_added) {
182911 return options.serialization_compatibility.Compare(version_added);
182912 }
182913
182914 class List {
182915 friend Serializer;
182916
182917 private:
182918 Serializer &serializer;
182919 explicit List(Serializer &serializer) : serializer(serializer) {
182920 }
182921
182922 public:
182923
182924 template <class T>
182925 void WriteElement(const T &value);
182926
182928 void WriteElement(data_ptr_t ptr, idx_t size);
182929
182930
182931 template <class FUNC>
182932 void WriteObject(FUNC f);
182933 };
182934
182935public:
182936 SerializationOptions GetOptions() {
182937 return options;
182938 }
182939 SerializationData &GetSerializationData() {
182940 return data;
182941 }
182942
182943 void SetSerializationData(const SerializationData &other) {
182944 data = other;
182945 }
182946
182947
182948 template <class T>
182949 void WriteProperty(const field_id_t field_id, const char *tag, const T &value) {
182950 OnPropertyBegin(field_id, tag);
182951 WriteValue(value);
182952 OnPropertyEnd();
182953 }
182954
182955
182956 template <class T>
182957 void WritePropertyWithDefault(const field_id_t field_id, const char *tag, const T &value) {
182958
182959 if (!options.serialize_default_values && SerializationDefaultValue::IsDefault<T>(value)) {
182960 OnOptionalPropertyBegin(field_id, tag, false);
182961 OnOptionalPropertyEnd(false);
182962 return;
182963 }
182964 OnOptionalPropertyBegin(field_id, tag, true);
182965 WriteValue(value);
182966 OnOptionalPropertyEnd(true);
182967 }
182968
182969 template <class T>
182970 void WritePropertyWithDefault(const field_id_t field_id, const char *tag, const T &value, const T &default_value) {
182971
182972 if (!options.serialize_default_values && (value == default_value)) {
182973 OnOptionalPropertyBegin(field_id, tag, false);
182974 OnOptionalPropertyEnd(false);
182975 return;
182976 }
182977 OnOptionalPropertyBegin(field_id, tag, true);
182978 WriteValue(value);
182979 OnOptionalPropertyEnd(true);
182980 }
182981
182982
182983 template <class T>
182984 void WritePropertyWithDefault(const field_id_t field_id, const char *tag, const CSVOption<T> &value,
182985 const T &default_value) {
182986
182987 if (!options.serialize_default_values && (value == default_value)) {
182988 OnOptionalPropertyBegin(field_id, tag, false);
182989 OnOptionalPropertyEnd(false);
182990 return;
182991 }
182992 OnOptionalPropertyBegin(field_id, tag, true);
182993 WriteValue(value.GetValue());
182994 OnOptionalPropertyEnd(true);
182995 }
182996
182997
182998 void WriteProperty(const field_id_t field_id, const char *tag, const_data_ptr_t ptr, idx_t count) {
182999 OnPropertyBegin(field_id, tag);
183000 WriteDataPtr(ptr, count);
183001 OnPropertyEnd();
183002 }
183003
183004
183005 template <class FUNC>
183006 void WriteObject(const field_id_t field_id, const char *tag, FUNC f) {
183007 OnPropertyBegin(field_id, tag);
183008 OnObjectBegin();
183009 f(*this);
183010 OnObjectEnd();
183011 OnPropertyEnd();
183012 }
183013
183014 template <class FUNC>
183015 void WriteList(const field_id_t field_id, const char *tag, idx_t count, FUNC func) {
183016 OnPropertyBegin(field_id, tag);
183017 OnListBegin(count);
183018 List list {*this};
183019 for (idx_t i = 0; i < count; i++) {
183020 func(list, i);
183021 }
183022 OnListEnd();
183023 OnPropertyEnd();
183024 }
183025
183026protected:
183027 template <typename T>
183028 typename std::enable_if<std::is_enum<T>::value, void>::type WriteValue(const T value) {
183029 if (options.serialize_enum_as_string) {
183030
183031 auto str = EnumUtil::ToChars(value);
183032 WriteValue(str);
183033 } else {
183034
183035 WriteValue(static_cast<typename std::underlying_type<T>::type>(value));
183036 }
183037 }
183038
183039
183040 template <typename T>
183041 void WriteValue(const optionally_owned_ptr<T> &ptr) {
183042 WriteValue(ptr.get());
183043 }
183044
183045
183046 template <typename T>
183047 void WriteValue(const unique_ptr<T> &ptr) {
183048 WriteValue(ptr.get());
183049 }
183050
183051
183052 template <typename T>
183053 void WriteValue(const shared_ptr<T> &ptr) {
183054 WriteValue(ptr.get());
183055 }
183056
183057
183058 template <typename T>
183059 void WriteValue(const T *ptr) {
183060 if (ptr == nullptr) {
183061 OnNullableBegin(false);
183062 OnNullableEnd();
183063 } else {
183064 OnNullableBegin(true);
183065 WriteValue(*ptr);
183066 OnNullableEnd();
183067 }
183068 }
183069
183070
183071 template <class K, class V>
183072 void WriteValue(const std::pair<K, V> &pair) {
183073 OnObjectBegin();
183074 WriteProperty(0, "first", pair.first);
183075 WriteProperty(1, "second", pair.second);
183076 OnObjectEnd();
183077 }
183078
183079
183080 template <class T>
183081 void WriteValue(const reference<T> ref) {
183082 WriteValue(ref.get());
183083 }
183084
183085
183086 template <class T>
183087 void WriteValue(const vector<T> &vec) {
183088 auto count = vec.size();
183089 OnListBegin(count);
183090 for (auto &item : vec) {
183091 WriteValue(item);
183092 }
183093 OnListEnd();
183094 }
183095
183096 template <class T>
183097 void WriteValue(const unsafe_vector<T> &vec) {
183098 auto count = vec.size();
183099 OnListBegin(count);
183100 for (auto &item : vec) {
183101 WriteValue(item);
183102 }
183103 OnListEnd();
183104 }
183105
183106
183107
183108 template <class T, class HASH, class CMP>
183109 void WriteValue(const duckdb::unordered_set<T, HASH, CMP> &set) {
183110 auto count = set.size();
183111 OnListBegin(count);
183112 for (auto &item : set) {
183113 WriteValue(item);
183114 }
183115 OnListEnd();
183116 }
183117
183118
183119
183120 template <class T, class HASH, class CMP>
183121 void WriteValue(const duckdb::set<T, HASH, CMP> &set) {
183122 auto count = set.size();
183123 OnListBegin(count);
183124 for (auto &item : set) {
183125 WriteValue(item);
183126 }
183127 OnListEnd();
183128 }
183129
183130
183131
183132 template <class K, class V, class HASH, class CMP>
183133 void WriteValue(const duckdb::unordered_map<K, V, HASH, CMP> &map) {
183134 auto count = map.size();
183135 OnListBegin(count);
183136 for (auto &item : map) {
183137 OnObjectBegin();
183138 WriteProperty(0, "key", item.first);
183139 WriteProperty(1, "value", item.second);
183140 OnObjectEnd();
183141 }
183142 OnListEnd();
183143 }
183144
183145
183146
183147 template <class K, class V, class HASH, class CMP>
183148 void WriteValue(const duckdb::map<K, V, HASH, CMP> &map) {
183149 auto count = map.size();
183150 OnListBegin(count);
183151 for (auto &item : map) {
183152 OnObjectBegin();
183153 WriteProperty(0, "key", item.first);
183154 WriteProperty(1, "value", item.second);
183155 OnObjectEnd();
183156 }
183157 OnListEnd();
183158 }
183159
183160
183161
183162 template <class V>
183163 void WriteValue(const duckdb::InsertionOrderPreservingMap<V> &map) {
183164 auto count = map.size();
183165 OnListBegin(count);
183166 for (auto &entry : map) {
183167 OnObjectBegin();
183168 WriteProperty(0, "key", entry.first);
183169 WriteProperty(1, "value", entry.second);
183170 OnObjectEnd();
183171 }
183172 OnListEnd();
183173 }
183174
183175
183176 template <typename T>
183177 void WriteValue(const std::priority_queue<T> &queue) {
183178 vector<T> placeholder;
183179 auto queue_copy = std::priority_queue<T>(queue);
183180 while (queue_copy.size() > 0) {
183181 placeholder.emplace_back(queue_copy.top());
183182 queue_copy.pop();
183183 }
183184 WriteValue(placeholder);
183185 }
183186
183187
183188 template <typename T>
183189 typename std::enable_if<has_serialize<T>::value>::type WriteValue(const T &value) {
183190 OnObjectBegin();
183191 value.Serialize(*this);
183192 OnObjectEnd();
183193 }
183194
183195protected:
183196
183197 virtual void OnPropertyBegin(const field_id_t field_id, const char *tag) = 0;
183198 virtual void OnPropertyEnd() = 0;
183199 virtual void OnOptionalPropertyBegin(const field_id_t field_id, const char *tag, bool present) = 0;
183200 virtual void OnOptionalPropertyEnd(bool present) = 0;
183201 virtual void OnObjectBegin() = 0;
183202 virtual void OnObjectEnd() = 0;
183203 virtual void OnListBegin(idx_t count) = 0;
183204 virtual void OnListEnd() = 0;
183205 virtual void OnNullableBegin(bool present) = 0;
183206 virtual void OnNullableEnd() = 0;
183207
183208
183209 virtual void WriteNull() = 0;
183210 virtual void WriteValue(char value) {
183211 throw NotImplementedException("Write char value not implemented");
183212 }
183213 virtual void WriteValue(bool value) = 0;
183214 virtual void WriteValue(uint8_t value) = 0;
183215 virtual void WriteValue(int8_t value) = 0;
183216 virtual void WriteValue(uint16_t value) = 0;
183217 virtual void WriteValue(int16_t value) = 0;
183218 virtual void WriteValue(uint32_t value) = 0;
183219 virtual void WriteValue(int32_t value) = 0;
183220 virtual void WriteValue(uint64_t value) = 0;
183221 virtual void WriteValue(int64_t value) = 0;
183222 virtual void WriteValue(hugeint_t value) = 0;
183223 virtual void WriteValue(uhugeint_t value) = 0;
183224 virtual void WriteValue(float value) = 0;
183225 virtual void WriteValue(double value) = 0;
183226 virtual void WriteValue(const string_t value) = 0;
183227 virtual void WriteValue(const string &value) = 0;
183228 virtual void WriteValue(const char *str) = 0;
183229 virtual void WriteDataPtr(const_data_ptr_t ptr, idx_t count) = 0;
183230 void WriteValue(LogicalIndex value) {
183231 WriteValue(value.index);
183232 }
183233 void WriteValue(PhysicalIndex value) {
183234 WriteValue(value.index);
183235 }
183236 void WriteValue(optional_idx value) {
183237 WriteValue(value.IsValid() ? value.GetIndex() : DConstants::INVALID_INDEX);
183238 }
183239};
183240
183241
183242template <>
183243void Serializer::WriteValue(const vector<bool> &vec);
183244
183245
183246template <>
183247void Serializer::WritePropertyWithDefault<Value>(const field_id_t field_id, const char *tag, const Value &value,
183248 const Value &default_value);
183249
183250
183251template <class FUNC>
183252void Serializer::List::WriteObject(FUNC f) {
183253 serializer.OnObjectBegin();
183254 f(serializer);
183255 serializer.OnObjectEnd();
183256}
183257
183258template <class T>
183259void Serializer::List::WriteElement(const T &value) {
183260 serializer.WriteValue(value);
183261}
183262
183263}
183264
183265
183266
183267namespace duckdb {
183268class BaseSecret;
183269struct SecretEntry;
183270struct FileOpenerInfo;
183271struct CreateSecretInfo;
183272
183275
183277struct CreateSecretInput {
183279 string type;
183281 string provider;
183283 string storage_type;
183285 string name;
183287 vector<string> scope;
183289 case_insensitive_map_t<Value> options;
183291 OnCreateConflict on_conflict;
183294};
183295
183296typedef unique_ptr<BaseSecret> (*secret_deserializer_t)(Deserializer &deserializer, BaseSecret base_secret);
183297typedef unique_ptr<BaseSecret> (*create_secret_function_t)(ClientContext &context, CreateSecretInput &input);
183298
183300class CreateSecretFunction {
183301public:
183302 string secret_type;
183303 string provider;
183304 create_secret_function_t function;
183305 named_parameter_type_map_t named_parameters;
183306};
183307
183310class CreateSecretFunctionSet {
183311public:
183312 explicit CreateSecretFunctionSet(string &name) : name(name) {};
183313
183314public:
183315 bool ProviderExists(const string &provider_name);
183316 void AddFunction(CreateSecretFunction &function, OnCreateConflict on_conflict);
183317 CreateSecretFunction &GetFunction(const string &provider);
183318
183319protected:
183321 string name;
183323 case_insensitive_map_t<CreateSecretFunction> functions;
183324};
183325
183328
183330struct SecretType {
183332 string name;
183334 secret_deserializer_t deserializer;
183336 string default_provider;
183338 string extension;
183339};
183340
183346};
183347
183349class BaseSecret {
183350 friend class SecretManager;
183351
183352public:
183353 BaseSecret(vector<string> prefix_paths_p, string type_p, string provider_p, string name_p)
183354 : prefix_paths(std::move(prefix_paths_p)), type(std::move(type_p)), provider(std::move(provider_p)),
183355 name(std::move(name_p)), serializable(false) {
183356 D_ASSERT(!type.empty());
183357 }
183358 BaseSecret(const BaseSecret &other)
183359 : prefix_paths(other.prefix_paths), type(other.type), provider(other.provider), name(other.name),
183360 serializable(other.serializable) {
183361 D_ASSERT(!type.empty());
183362 }
183363 virtual ~BaseSecret() = default;
183364
183367 virtual int64_t MatchScore(
const string &path)
const;
183369 virtual string ToString(SecretDisplayType mode = SecretDisplayType::REDACTED) const;
183371 virtual void Serialize(Serializer &serializer) const;
183372
183373 virtual unique_ptr<const BaseSecret> Clone() const {
183374 D_ASSERT(typeid(BaseSecret) == typeid(*this));
183375 return make_uniq<BaseSecret>(*this);
183376 }
183377
183379 const vector<string> &GetScope() const {
183380 return prefix_paths;
183381 }
183382 const string &GetType() const {
183383 return type;
183384 }
183385 const string &GetProvider() const {
183386 return provider;
183387 }
183388 const string &GetName() const {
183389 return name;
183390 }
183391 bool IsSerializable() const {
183392 return serializable;
183393 }
183394
183395protected:
183397 virtual void SerializeBaseSecret(Serializer &serializer) const final;
183398
183400 vector<string> prefix_paths;
183401
183403 string type;
183405 string provider;
183407 string name;
183409 bool serializable;
183410};
183411
183414class KeyValueSecret : public BaseSecret {
183415public:
183416 KeyValueSecret(const vector<string> &prefix_paths, const string &type, const string &provider, const string &name)
183417 : BaseSecret(prefix_paths, type, provider, name) {
183418 D_ASSERT(!type.empty());
183419 serializable = true;
183420 }
183421 explicit KeyValueSecret(const BaseSecret &secret)
183422 : BaseSecret(secret.GetScope(), secret.GetType(), secret.GetProvider(), secret.GetName()) {
183423 serializable = true;
183424 };
183425 KeyValueSecret(const KeyValueSecret &secret)
183426 : BaseSecret(secret.GetScope(), secret.GetType(), secret.GetProvider(), secret.GetName()) {
183427 secret_map = secret.secret_map;
183428 redact_keys = secret.redact_keys;
183429 serializable = true;
183430 };
183431 KeyValueSecret(KeyValueSecret &&secret) noexcept
183432 : BaseSecret(std::move(secret.prefix_paths), std::move(secret.type), std::move(secret.provider),
183433 std::move(secret.name)) {
183434 secret_map = std::move(secret.secret_map);
183435 redact_keys = std::move(secret.redact_keys);
183436 serializable = true;
183437 };
183438
183440 string ToString(SecretDisplayType mode = SecretDisplayType::REDACTED) const override;
183441 void Serialize(Serializer &serializer) const override;
183442
183444 Value TryGetValue(const string &key, bool error_on_missing = false) const;
183445
183446
183447 template <class TYPE>
183448 static unique_ptr<BaseSecret> Deserialize(Deserializer &deserializer, BaseSecret base_secret) {
183449 auto result = make_uniq<TYPE>(base_secret);
183450 Value secret_map_value;
183451 deserializer.ReadProperty(201, "secret_map", secret_map_value);
183452
183453 for (const auto &entry : ListValue::GetChildren(secret_map_value)) {
183454 auto kv_struct = StructValue::GetChildren(entry);
183455 result->secret_map[kv_struct[0].ToString()] = kv_struct[1];
183456 }
183457
183458 Value redact_set_value;
183459 deserializer.ReadProperty(202, "redact_keys", redact_set_value);
183460 for (const auto &entry : ListValue::GetChildren(redact_set_value)) {
183461 result->redact_keys.insert(entry.ToString());
183462 }
183463
183464 return duckdb::unique_ptr_cast<TYPE, BaseSecret>(std::move(result));
183465 }
183466
183467 unique_ptr<const BaseSecret> Clone() const override {
183468 return make_uniq<KeyValueSecret>(*this);
183469 }
183470
183471
183472 bool TryGetValue(const string &key, Value &result) const {
183473 auto lookup = secret_map.find(key);
183474 if (lookup == secret_map.end()) {
183475 return false;
183476 }
183477 result = lookup->second;
183478 return true;
183479 }
183480
183481 bool TrySetValue(const string &key, const CreateSecretInput &input) {
183482 auto lookup = input.options.find(key);
183483 if (lookup != input.options.end()) {
183484 secret_map[key] = lookup->second;
183485 return true;
183486 }
183487 return false;
183488 }
183489
183491 case_insensitive_tree_t<Value> secret_map;
183493 case_insensitive_set_t redact_keys;
183494};
183495
183496
183497
183498
183499
183500
183501
183502class KeyValueSecretReader {
183503public:
183505 KeyValueSecretReader(const KeyValueSecret &secret_p, FileOpener &opener_p);
183506
183508 KeyValueSecretReader(FileOpener &opener_p, optional_ptr<FileOpenerInfo> info, const char **secret_types,
183509 idx_t secret_types_len);
183510 KeyValueSecretReader(FileOpener &opener_p, optional_ptr<FileOpenerInfo> info, const char *secret_type);
183511
183513 KeyValueSecretReader(DatabaseInstance &db, const char **secret_types, idx_t secret_types_len, string path);
183514 KeyValueSecretReader(DatabaseInstance &db, const char *secret_type, string path);
183515
183516
183517 KeyValueSecretReader(ClientContext &context, const char **secret_types, idx_t secret_types_len, string path);
183518 KeyValueSecretReader(ClientContext &context, const char *secret_type, string path);
183519
183520 ~KeyValueSecretReader();
183521
183523 SettingLookupResult TryGetSecretKey(const string &secret_key, Value &result);
183525 SettingLookupResult TryGetSecretKeyOrSetting(const string &secret_key, const string &setting_name, Value &result);
183527 Value GetSecretKey(const string &secret_key);
183529 Value GetSecretKeyOrSetting(const string &secret_key, const string &setting_name);
183530
183532 template <class TYPE>
183533 SettingLookupResult TryGetSecretKey(const string &secret_key, TYPE &value_out) {
183534 Value result;
183535 auto lookup_result = TryGetSecretKey(secret_key, result);
183536 if (lookup_result) {
183537 value_out = result.GetValue<
TYPE>();
183538 }
183539 return lookup_result;
183540 }
183541
183543 template <class TYPE>
183544 SettingLookupResult TryGetSecretKeyOrSetting(const string &secret_key, const string &setting_name,
183545 TYPE &value_out) {
183546 Value result;
183547 auto lookup_result = TryGetSecretKeyOrSetting(secret_key, setting_name, result);
183548 if (lookup_result) {
183549 if (!result.IsNull()) {
183550 value_out = result.GetValue<
TYPE>();
183551 }
183552 }
183553 return lookup_result;
183554 }
183555
183556
183557 template <class TYPE>
183558 TYPE GetSecretKeyOrSettingOrDefault(
const string &secret_key,
const string &setting_name, TYPE default_value) {
183560 if (TryGetSecretKeyOrSetting(secret_key, setting_name, result)) {
183561 return result;
183562 }
183563 return default_value;
183564 }
183565
183566protected:
183567 void Initialize(const char **secret_types, idx_t secret_types_len);
183568
183569 [[noreturn]] void ThrowNotFoundError(const string &secret_key);
183570 [[noreturn]] void ThrowNotFoundError(const string &secret_key, const string &setting_name);
183571
183573 optional_ptr<const KeyValueSecret> secret;
183575 shared_ptr<SecretEntry> secret_entry;
183576
183579 optional_ptr<DatabaseInstance>
db;
183580 optional_ptr<ClientContext> context;
183581
183582 string path;
183583};
183584
183585}
183586
183587
183588
183589
183590
183591
183592
183593
183594
183595
183596
183597
183598
183599
183600
183601
183602
183603
183604
183605
183606
183607
183608
183609
183610
183611
183612
183613
183614
183615
183616
183617
183618
183619
183620
183621
183622
183623
183624
183625
183626
183627
183628
183629
183630
183631
183632
183633
183634
183635
183636
183637
183638
183639
183640
183641
183642
183643namespace duckdb {
183644
183645enum class CTEMaterialize :
uint8_t {
183646 CTE_MATERIALIZE_DEFAULT = 1,
183647 CTE_MATERIALIZE_ALWAYS = 2,
183648 CTE_MATERIALIZE_NEVER = 3
183649};
183650
183651}
183652
183653
183654namespace duckdb {
183655
183656class SelectStatement;
183657
183658struct CommonTableExpressionInfo {
183659 ~CommonTableExpressionInfo();
183660
183661 vector<string> aliases;
183662 vector<unique_ptr<ParsedExpression>> key_targets;
183663 unique_ptr<SelectStatement> query;
183664 CTEMaterialize materialized = CTEMaterialize::CTE_MATERIALIZE_DEFAULT;
183665
183666public:
183667 void Serialize(Serializer &serializer) const;
183668 static unique_ptr<CommonTableExpressionInfo> Deserialize(Deserializer &deserializer);
183669 unique_ptr<CommonTableExpressionInfo> Copy();
183670
183671private:
183672 CTEMaterialize GetMaterializedForSerialization(Serializer &serializer) const;
183673};
183674
183675}
183676
183677
183678
183679
183680namespace duckdb {
183681
183682class Deserializer;
183683class Serializer;
183684
183685enum class QueryNodeType :
uint8_t {
183686 SELECT_NODE = 1,
183687 SET_OPERATION_NODE = 2,
183688 BOUND_SUBQUERY_NODE = 3,
183689 RECURSIVE_CTE_NODE = 4,
183690 CTE_NODE = 5,
183691 STATEMENT_NODE = 6
183692};
183693
183694struct CommonTableExpressionInfo;
183695
183696class CommonTableExpressionMap {
183697public:
183698 CommonTableExpressionMap();
183699
183700 InsertionOrderPreservingMap<unique_ptr<CommonTableExpressionInfo>> map;
183701
183702public:
183703 string ToString() const;
183704 CommonTableExpressionMap Copy() const;
183705
183706 void Serialize(Serializer &serializer) const;
183707 static CommonTableExpressionMap Deserialize(Deserializer &deserializer);
183708};
183709
183710class QueryNode {
183711public:
183712 explicit QueryNode(QueryNodeType type) : type(type) {
183713 }
183714 virtual ~QueryNode() {
183715 }
183716
183718 QueryNodeType type;
183720 vector<unique_ptr<ResultModifier>> modifiers;
183722 CommonTableExpressionMap cte_map;
183723
183724public:
183726 virtual string ToString() const = 0;
183727
183728 virtual bool Equals(const QueryNode *other) const;
183729
183731 virtual unique_ptr<QueryNode> Copy() const = 0;
183732
183733 string ResultModifiersToString() const;
183734
183736 void AddDistinct();
183737
183738 virtual void Serialize(Serializer &serializer) const;
183739 static unique_ptr<QueryNode> Deserialize(Deserializer &deserializer);
183740
183741protected:
183744 void CopyProperties(QueryNode &other) const;
183745
183746public:
183747 template <class TARGET>
183748 TARGET &Cast() {
183749 if (type != TARGET::TYPE) {
183750 throw InternalException("Failed to cast query node to type - query node type mismatch");
183751 }
183752 return reinterpret_cast<TARGET &>(*this);
183753 }
183754
183755 template <class TARGET>
183756 const TARGET &Cast() const {
183757 if (type != TARGET::TYPE) {
183758 throw InternalException("Failed to cast query node to type - query node type mismatch");
183759 }
183760 return reinterpret_cast<const TARGET &>(*this);
183761 }
183762};
183763
183764}
183765
183766
183767
183768
183769
183770
183771
183772
183773
183774
183775
183776
183777
183778
183779
183780
183781
183782
183783
183784
183785
183786
183787
183788
183789
183790
183791namespace duckdb {
183792
183793
183794
183795
183796enum class TableReferenceType :
uint8_t {
183797 INVALID = 0,
183798 BASE_TABLE = 1,
183799 SUBQUERY = 2,
183800 JOIN = 3,
183801 TABLE_FUNCTION = 5,
183802 EXPRESSION_LIST = 6,
183803 CTE = 7,
183804 EMPTY_FROM = 8,
183805 PIVOT = 9,
183806 SHOW_REF = 10,
183807 COLUMN_DATA = 11,
183808 DELIM_GET = 12,
183809 BOUND_TABLE_REF = 13
183810};
183811
183812}
183813
183814
183815
183816
183817
183818
183819
183820
183821
183822
183823
183824
183825
183826
183827namespace duckdb {
183828
183829
183830
183831enum class SampleMethod :
uint8_t { SYSTEM_SAMPLE = 0, BERNOULLI_SAMPLE = 1, RESERVOIR_SAMPLE = 2, INVALID = 255 };
183832
183833
183834string SampleMethodToString(SampleMethod method);
183835
183836class SampleOptions {
183837public:
183838
183839 static constexpr idx_t MAX_SAMPLE_ROWS = 1000000000;
183840
183841public:
183842 explicit SampleOptions(int64_t seed_ = -1);
183843
183844 Value sample_size;
183845 bool is_percentage;
183846 SampleMethod method;
183847 optional_idx seed = optional_idx::Invalid();
183848 bool repeatable;
183849
183850 unique_ptr<SampleOptions> Copy();
183851 void SetSeed(idx_t new_seed);
183852 static bool Equals(SampleOptions *a, SampleOptions *b);
183853 void Serialize(Serializer &serializer) const;
183854 static unique_ptr<SampleOptions> Deserialize(Deserializer &deserializer);
183856};
183857
183858}
183859
183860
183861
183862namespace duckdb {
183863
183865class TableRef {
183866public:
183867 static constexpr const TableReferenceType
TYPE = TableReferenceType::INVALID;
183868
183869public:
183870 explicit TableRef(TableReferenceType type) : type(type) {
183871 }
183872 virtual ~TableRef() {
183873 }
183874
183875 TableReferenceType type;
183876 string alias;
183878 unique_ptr<SampleOptions> sample;
183880 optional_idx query_location;
183882 shared_ptr<ExternalDependency> external_dependency;
183884 vector<string> column_name_alias;
183885
183886public:
183888 virtual string ToString() const = 0;
183889 void Print();
183890
183891 virtual bool Equals(const TableRef &other) const;
183892 static bool Equals(const unique_ptr<TableRef> &left, const unique_ptr<TableRef> &right);
183893
183894 virtual unique_ptr<TableRef> Copy() = 0;
183895
183897 void CopyProperties(TableRef &target) const;
183898
183899 virtual void Serialize(Serializer &serializer) const;
183900 static unique_ptr<TableRef> Deserialize(Deserializer &deserializer);
183901
183902public:
183903 template <class TARGET>
183904 TARGET &Cast() {
183905 if (type != TARGET::TYPE && TARGET::TYPE != TableReferenceType::INVALID) {
183906 throw InternalException("Failed to cast constraint to type - constraint type mismatch");
183907 }
183908 return reinterpret_cast<TARGET &>(*this);
183909 }
183910
183911 template <class TARGET>
183912 const TARGET &Cast() const {
183913 if (type != TARGET::TYPE && TARGET::TYPE != TableReferenceType::INVALID) {
183914 throw InternalException("Failed to cast constraint to type - constraint type mismatch");
183915 }
183916 return reinterpret_cast<const TARGET &>(*this);
183917 }
183918
183919protected:
183920 string BaseToString(string result) const;
183921 string BaseToString(string result, const vector<string> &column_name_alias) const;
183922 string AliasToString(const vector<string> &column_name_alias) const;
183923 string SampleToString() const;
183924};
183925}
183926
183927
183928namespace duckdb {
183929
183930class QueryNode;
183931class Serializer;
183932class Deserializer;
183933
183935class SelectStatement : public SQLStatement {
183936public:
183937 static constexpr const StatementType
TYPE = StatementType::SELECT_STATEMENT;
183938
183939public:
183940 SelectStatement() : SQLStatement(StatementType::SELECT_STATEMENT) {
183941 }
183942
183944 unique_ptr<QueryNode> node;
183945
183946protected:
183947 SelectStatement(const SelectStatement &other);
183948
183949public:
183951
183952 DUCKDB_API string ToString() const override;
183954 DUCKDB_API unique_ptr<SQLStatement> Copy() const override;
183956 bool Equals(const SQLStatement &other) const;
183957
183958 void Serialize(Serializer &serializer) const;
183959 static unique_ptr<SelectStatement> Deserialize(Deserializer &deserializer);
183960};
183961}
183962
183963
183964namespace duckdb {
183965
183966class TypeArgument {
183967public:
183968 TypeArgument(string name_p, Value value_p) : name(std::move(name_p)), value(std::move(value_p)) {
183969 }
183970 const string &GetName() const {
183971 return name;
183972 }
183973 const Value &GetValue() const {
183974 return value;
183975 }
183976 bool HasName() const {
183977 return !name.empty();
183978 }
183979 bool IsNamed(const char *name_to_check) const {
183981 }
183982 bool IsNotNull() const {
183983 return !value.IsNull();
183984 }
183985 const LogicalType &GetType() const {
183986 return value.type();
183987 }
183988
183989private:
183990 string name;
183991 Value value;
183992};
183993
183994struct BindLogicalTypeInput {
183995 optional_ptr<ClientContext> context;
183996 const LogicalType &base_type;
183997 const vector<TypeArgument> &modifiers;
183998};
183999
184001typedef LogicalType (*bind_logical_type_function_t)(BindLogicalTypeInput &input);
184002
184003struct CreateTypeInfo : public CreateInfo {
184004 CreateTypeInfo();
184005 CreateTypeInfo(string name_p, LogicalType type_p, bind_logical_type_function_t bind_function_p = nullptr);
184006
184008 string name;
184010 LogicalType type;
184012 unique_ptr<SQLStatement> query;
184015
184016public:
184017 unique_ptr<CreateInfo> Copy() const override;
184018
184019 DUCKDB_API void Serialize(Serializer &serializer) const override;
184020 DUCKDB_API static unique_ptr<CreateInfo> Deserialize(Deserializer &deserializer);
184021
184022 string ToString() const override;
184023};
184024
184025}
184026
184027
184028
184029
184030
184031
184032
184033
184034
184035
184036
184037
184038
184039
184040namespace duckdb {
184041class FileSystem;
184042
184044
184045 UNKNOWN = 0,
184053 NOT_INSTALLED = 4
184054};
184055
184056struct ExtensionLoadedInfo {
184057 string description;
184058};
184059
184060class ExtensionInstallInfo {
184061public:
184065 string full_path;
184067 string repository_url;
184069 string version;
184071 string etag;
184072
184073 void Serialize(Serializer &serializer) const;
184074
184076 static unique_ptr<ExtensionInstallInfo> TryReadInfoFile(FileSystem &fs, const string &info_file_path,
184077 const string &extension_name);
184078
184079 static unique_ptr<ExtensionInstallInfo> Deserialize(Deserializer &deserializer);
184080};
184081
184082struct ExtensionRepository {
184084 static constexpr const char *CORE_REPOSITORY_URL = "http://extensions.duckdb.org";
184085 static constexpr const char *CORE_NIGHTLY_REPOSITORY_URL = "http://nightly-extensions.duckdb.org";
184086 static constexpr const char *COMMUNITY_REPOSITORY_URL = "http://community-extensions.duckdb.org";
184087
184089 static constexpr const char *BUILD_DEBUG_REPOSITORY_PATH = "./build/debug/repository";
184090 static constexpr const char *BUILD_RELEASE_REPOSITORY_PATH = "./build/release/repository";
184091
184093 static constexpr const char *DEFAULT_REPOSITORY_URL = CORE_REPOSITORY_URL;
184094
184096 static string GetRepository(const string &repository_url);
184098 static string TryGetRepositoryUrl(const string &repository);
184100 static string TryConvertUrlToKnownRepository(const string &url);
184101
184103 static ExtensionRepository GetDefaultRepository(optional_ptr<DBConfig> config);
184104 static ExtensionRepository GetDefaultRepository(ClientContext &context);
184105
184106 static ExtensionRepository GetCoreRepository();
184107 static ExtensionRepository GetRepositoryByUrl(const string &url);
184108
184109 ExtensionRepository();
184110 ExtensionRepository(const string &name, const string &url);
184111
184113 string ToReadableString();
184114
184116 string name;
184118 string path;
184119};
184120
184121}
184122
184123
184124
184125
184126
184127
184128
184129
184130
184131
184132
184133
184134
184135
184136namespace duckdb {
184137class ErrorData;
184138
184139class ExtensionInfo {
184140public:
184141 ExtensionInfo();
184142
184143 mutex lock;
184144 atomic<bool> is_loaded;
184145 unique_ptr<ExtensionInstallInfo> install_info;
184146 unique_ptr<ExtensionLoadedInfo> load_info;
184147};
184148
184149class ExtensionActiveLoad {
184150public:
184151 ExtensionActiveLoad(DatabaseInstance &db, ExtensionInfo &info, string extension_name);
184152
184153 DatabaseInstance &
db;
184154 unique_lock<mutex> load_lock;
184155 ExtensionInfo &info;
184156 string extension_name;
184157
184158public:
184159 void FinishLoad(ExtensionInstallInfo &install_info);
184160 void LoadFail(const ErrorData &error);
184161};
184162
184163class ExtensionManager {
184164public:
184165 explicit ExtensionManager(DatabaseInstance &db);
184166
184167 DUCKDB_API bool ExtensionIsLoaded(const string &name);
184168 DUCKDB_API vector<string> GetExtensions();
184169 DUCKDB_API optional_ptr<ExtensionInfo> GetExtensionInfo(const string &name);
184170 DUCKDB_API unique_ptr<ExtensionActiveLoad> BeginLoad(const string &extension);
184171
184172 DUCKDB_API static ExtensionManager &Get(DatabaseInstance &db);
184173 DUCKDB_API static ExtensionManager &Get(ClientContext &context);
184174
184175private:
184176 DatabaseInstance &
db;
184177 mutex lock;
184178 unordered_map<string, unique_ptr<ExtensionInfo>> loaded_extensions_info;
184179};
184180
184181}
184182
184183
184184namespace duckdb {
184185
184186class DatabaseInstance;
184187struct CreateMacroInfo;
184188struct CreateCollationInfo;
184189struct CreateAggregateFunctionInfo;
184190struct CreateScalarFunctionInfo;
184191struct CreateTableFunctionInfo;
184192
184193class ExtensionLoader {
184194 friend class DuckDB;
184195 friend class ExtensionHelper;
184196
184197public:
184198 explicit ExtensionLoader(ExtensionActiveLoad &load_info);
184199 ExtensionLoader(DatabaseInstance &db, const string &extension_name);
184200
184202 DUCKDB_API DatabaseInstance &GetDatabaseInstance();
184203
184204public:
184206 DUCKDB_API void SetDescription(const string &description);
184207
184208public:
184210 DUCKDB_API void RegisterFunction(ScalarFunction function);
184211 DUCKDB_API void RegisterFunction(ScalarFunctionSet function);
184212 DUCKDB_API void RegisterFunction(CreateScalarFunctionInfo info);
184213
184215 DUCKDB_API void RegisterFunction(AggregateFunction function);
184216 DUCKDB_API void RegisterFunction(AggregateFunctionSet function);
184217 DUCKDB_API void RegisterFunction(CreateAggregateFunctionInfo info);
184218
184220 DUCKDB_API void RegisterFunction(TableFunction function);
184221 DUCKDB_API void RegisterFunction(TableFunctionSet function);
184222 DUCKDB_API void RegisterFunction(CreateTableFunctionInfo info);
184223
184225 DUCKDB_API void RegisterFunction(PragmaFunction function);
184226
184228 DUCKDB_API void RegisterFunction(PragmaFunctionSet function);
184229
184231 DUCKDB_API void RegisterFunction(CreateSecretFunction function);
184232
184234 DUCKDB_API void RegisterFunction(CopyFunction function);
184236 DUCKDB_API void RegisterFunction(CreateMacroInfo &info);
184237
184239 DUCKDB_API void RegisterCollation(CreateCollationInfo &info);
184240
184242 DUCKDB_API void RegisterCoordinateSystem(CreateCoordinateSystemInfo &info);
184243
184245 DUCKDB_API ScalarFunctionCatalogEntry &GetFunction(const string &name);
184246 DUCKDB_API TableFunctionCatalogEntry &GetTableFunction(const string &name);
184247 DUCKDB_API optional_ptr<CatalogEntry> TryGetFunction(const string &name);
184248 DUCKDB_API optional_ptr<CatalogEntry> TryGetTableFunction(const string &name);
184249
184251 DUCKDB_API void AddFunctionOverload(ScalarFunction function);
184252 DUCKDB_API void AddFunctionOverload(ScalarFunctionSet function);
184253 DUCKDB_API void AddFunctionOverload(TableFunctionSet function);
184254
184256 DUCKDB_API void RegisterType(string type_name, LogicalType type,
184257 bind_logical_type_function_t bind_function = nullptr);
184258
184260 DUCKDB_API void RegisterSecretType(SecretType secret_type);
184261
184263 DUCKDB_API void RegisterCastFunction(const LogicalType &source, const LogicalType &target,
184264 bind_cast_function_t function, int64_t implicit_cast_cost = -1);
184265 DUCKDB_API void RegisterCastFunction(const LogicalType &source, const LogicalType &target, BoundCastInfo function,
184266 int64_t implicit_cast_cost = -1);
184267
184268private:
184269 void FinalizeLoad();
184270
184271private:
184272 DatabaseInstance &
db;
184273 string extension_name;
184274 string extension_description;
184275 optional_ptr<ExtensionInfo> extension_info;
184276};
184277
184278}
184279
184287#define DUCKDB_CPP_EXTENSION_ENTRY(EXTENSION_NAME, LOADER_NAME) \
184288 DUCKDB_EXTENSION_API void EXTENSION_NAME##_duckdb_cpp_init(duckdb::ExtensionLoader &LOADER_NAME)
184289
184290
184291
184292namespace duckdb {
184293
184294class BufferManager;
184295class DatabaseManager;
184296class StorageManager;
184297class Catalog;
184298class TransactionManager;
184299class ConnectionManager;
184300class ExtensionManager;
184301class FileSystem;
184302class TaskScheduler;
184303class ObjectCache;
184304struct AttachInfo;
184305struct AttachOptions;
184306class DatabaseFileSystem;
184307struct DatabaseCacheEntry;
184308class LogManager;
184309class ExternalFileCache;
184310class ResultSetManager;
184311
184312class DatabaseInstance : public enable_shared_from_this<DatabaseInstance> {
184313 friend class DuckDB;
184314
184315public:
184316 DUCKDB_API DatabaseInstance();
184317 DUCKDB_API ~DatabaseInstance();
184318
184319 DBConfig config;
184320
184321public:
184322 BufferPool &GetBufferPool() const;
184323 DUCKDB_API SecretManager &GetSecretManager();
184324 DUCKDB_API BufferManager &GetBufferManager();
184325 DUCKDB_API const BufferManager &GetBufferManager() const;
184326 DUCKDB_API DatabaseManager &GetDatabaseManager();
184327 DUCKDB_API FileSystem &GetFileSystem();
184328 DUCKDB_API ExternalFileCache &GetExternalFileCache();
184329 DUCKDB_API ResultSetManager &GetResultSetManager();
184330 DUCKDB_API TaskScheduler &GetScheduler();
184331 DUCKDB_API ObjectCache &GetObjectCache();
184332 DUCKDB_API ConnectionManager &GetConnectionManager();
184333 DUCKDB_API ExtensionManager &GetExtensionManager();
184334 DUCKDB_API ValidChecker &GetValidChecker();
184335 DUCKDB_API LogManager &GetLogManager() const;
184336
184337 DUCKDB_API const duckdb_ext_api_v1 GetExtensionAPIV1();
184338
184339 idx_t NumberOfThreads();
184340
184341 DUCKDB_API static DatabaseInstance &GetDatabase(ClientContext &context);
184342 DUCKDB_API static const DatabaseInstance &GetDatabase(const ClientContext &context);
184343
184344 DUCKDB_API bool ExtensionIsLoaded(const string &name);
184345
184346 DUCKDB_API SettingLookupResult TryGetCurrentSetting(const string &key, Value &result) const;
184347
184348 DUCKDB_API shared_ptr<EncryptionUtil> GetEncryptionUtil(bool read_only = false);
184349 shared_ptr<EncryptionUtil> GetMbedTLSUtil(bool force_mbedtls) const;
184350
184351 shared_ptr<AttachedDatabase> CreateAttachedDatabase(ClientContext &context, AttachInfo &info,
184352 AttachOptions &options);
184353
184354private:
184355 void Initialize(const char *path, DBConfig *config);
184356 void LoadExtensionSettings();
184357 void CreateMainDatabase();
184358
184359 void Configure(DBConfig &config, const char *path);
184360
184361private:
184362 shared_ptr<BufferManager> buffer_manager;
184363 unique_ptr<DatabaseManager> db_manager;
184364 unique_ptr<TaskScheduler> scheduler;
184365 unique_ptr<ObjectCache> object_cache;
184366 unique_ptr<ConnectionManager> connection_manager;
184367 unique_ptr<ExtensionManager> extension_manager;
184368 ValidChecker db_validity;
184369 unique_ptr<DatabaseFileSystem> db_file_system;
184370 unique_ptr<LogManager> log_manager;
184371 unique_ptr<ExternalFileCache> external_file_cache;
184372 unique_ptr<ResultSetManager> result_set_manager;
184373
184374 duckdb_ext_api_v1 (*create_api_v1)();
184375};
184376
184379class DuckDB {
184380public:
184381 DUCKDB_API explicit DuckDB(const char *path = nullptr, DBConfig *config = nullptr);
184382 DUCKDB_API explicit DuckDB(const string &path, DBConfig *config = nullptr);
184383 DUCKDB_API explicit DuckDB(DatabaseInstance &instance);
184384
184385 DUCKDB_API ~DuckDB();
184386
184388 shared_ptr<DatabaseInstance> instance;
184389
184390public:
184391
184392 template <class T>
184393 void LoadStaticExtension() {
184394 T extension;
184395 auto &manager = ExtensionManager::Get(*instance);
184396 auto load_info = manager.BeginLoad(extension.Name());
184397 if (!load_info) {
184398
184399 return;
184400 }
184401
184402
184403 ExtensionLoader loader(*load_info);
184404
184405
184406 extension.Load(loader);
184407
184408
184409 loader.FinalizeLoad();
184410
184411 ExtensionInstallInfo install_info;
184412 install_info.mode = ExtensionInstallMode::STATICALLY_LINKED;
184413 install_info.version = extension.Version();
184414 load_info->FinishLoad(install_info);
184415 }
184416
184417 DUCKDB_API FileSystem &GetFileSystem();
184418
184419 DUCKDB_API
idx_t NumberOfThreads();
184420 DUCKDB_API static const char *SourceID();
184421 DUCKDB_API static const char *LibraryVersion();
184422 DUCKDB_API static const char *ReleaseCodename();
184423 DUCKDB_API
static idx_t StandardVectorSize();
184424 DUCKDB_API static string Platform();
184425 DUCKDB_API bool ExtensionIsLoaded(const string &name);
184426};
184427
184428}
184429
184430
184431
184432
184433
184434
184435
184436
184437
184438
184439
184440
184441
184442
184443
184444
184445namespace duckdb {
184446
184447class ClientContext;
184448class ColumnDataCollection;
184449class Connection;
184450class DuckDB;
184451class SQLStatement;
184452class TableCatalogEntry;
184453
184454enum class AppenderType :
uint8_t {
184455 LOGICAL,
184456 PHYSICAL
184457};
184458
184460class BaseAppender {
184461public:
184463 static constexpr const idx_t DEFAULT_FLUSH_COUNT = STANDARD_VECTOR_SIZE * 100ULL;
184464
184465public:
184467 static unique_ptr<TableRef> GetColumnDataTableRef(ColumnDataCollection &collection, const string &table_name,
184468 const vector<string> &expected_names);
184470 static unique_ptr<SQLStatement> ParseStatement(unique_ptr<TableRef> table_ref, const string &query,
184471 const string &table_name);
184472
184473protected:
184475 Allocator &allocator;
184477 vector<LogicalType> types;
184479 vector<LogicalType> active_types;
184481 unique_ptr<ColumnDataCollection> collection;
184483 DataChunk chunk;
184487 AppenderType appender_type;
184489 idx_t flush_count = DEFAULT_FLUSH_COUNT;
184491 optional_idx flush_memory_threshold;
184492
184493protected:
184494 DUCKDB_API BaseAppender(Allocator &allocator, const AppenderType type);
184495 DUCKDB_API BaseAppender(Allocator &allocator, vector<LogicalType> types, const AppenderType type,
184496 const idx_t flush_count = DEFAULT_FLUSH_COUNT);
184497
184498public:
184499 DUCKDB_API virtual ~BaseAppender();
184500
184504 DUCKDB_API void BeginRow();
184506 DUCKDB_API void EndRow();
184507
184508
184509 template <class T>
184510 void Append(T value) = delete;
184511 DUCKDB_API void Append(DataChunk &target, const Value &value, idx_t col, idx_t row);
184512
184513 DUCKDB_API void Append(const char *value, uint32_t length);
184514
184515
184516 template <typename... ARGS>
184517 void AppendRow(ARGS... args) {
184518 BeginRow();
184519 AppendRowRecursive(args...);
184520 }
184521
184523 DUCKDB_API void Flush();
184525 DUCKDB_API void Close();
184527 DUCKDB_API void Clear();
184529 const vector<LogicalType> &GetActiveTypes() const;
184530
184531 idx_t CurrentColumn()
const {
184532 return column;
184533 }
184534 DUCKDB_API void AppendDataChunk(DataChunk &value);
184535
184536 virtual void AppendDefault();
184537 virtual void AppendDefault(DataChunk &chunk, idx_t col, idx_t row);
184540 virtual void AddColumn(const string &name);
184543 virtual void ClearColumns();
184544
184545protected:
184546 void Destructor();
184547 virtual void FlushInternal(ColumnDataCollection &collection) = 0;
184548 void InitializeChunk();
184549 void FlushChunk();
184550
184551 bool ShouldFlushChunk() const;
184552 bool ShouldFlush() const;
184553
184554 template <class T>
184555 void AppendValueInternal(T value);
184556 template <class SRC, class DST>
184557 void AppendValueInternal(Vector &vector, SRC input);
184558 template <class SRC, class DST>
184559 void AppendDecimalValueInternal(Vector &vector, SRC input);
184560
184561 void AppendRowRecursive() {
184562 EndRow();
184563 }
184564
184565 template <typename T, typename... ARGS>
184566 void AppendRowRecursive(T value, ARGS... args) {
184567 Append<T>(value);
184568 AppendRowRecursive(args...);
184569 }
184570
184571 void AppendValue(const Value &value);
184572 void AppendValue(DataChunk target, const Value &value);
184573};
184574
184575class Appender : public BaseAppender {
184576public:
184577 DUCKDB_API Appender(Connection &con, const string &database_name, const string &schema_name,
184578 const string &table_name, const idx_t flush_memory_threshold = DConstants::INVALID_INDEX);
184579 DUCKDB_API Appender(Connection &con, const string &schema_name, const string &table_name,
184580 const idx_t flush_memory_threshold = DConstants::INVALID_INDEX);
184581 DUCKDB_API Appender(Connection &con, const string &table_name,
184582 const idx_t flush_memory_threshold = DConstants::INVALID_INDEX);
184583 DUCKDB_API ~Appender() override;
184584
184585public:
184586 void AppendDefault() override;
184587 void AppendDefault(DataChunk &chunk, idx_t col, idx_t row) override;
184588 void AddColumn(const string &name) override;
184589 void ClearColumns() override;
184591 vector<string> GetExpectedNames();
184593 static string ConstructQuery(TableDescription &description_p, const string &table_name,
184594 const vector<string> &expected_names);
184595
184596private:
184598 weak_ptr<ClientContext> context;
184600 unique_ptr<TableDescription> description;
184602 unordered_map<column_t, Value> default_values;
184603
184606 vector<LogicalIndex> column_ids;
184607
184608protected:
184609 void FlushInternal(ColumnDataCollection &collection) override;
184610 Value GetDefaultValue(idx_t column);
184611};
184612
184613class QueryAppender : public BaseAppender {
184614public:
184615 DUCKDB_API QueryAppender(Connection &con, string query, vector<LogicalType> types,
184616 vector<string> names = vector<string>(), string table_name = string(),
184617 const idx_t flush_memory_threshold = DConstants::INVALID_INDEX);
184618 DUCKDB_API ~QueryAppender() override;
184619
184620private:
184622 weak_ptr<ClientContext> context;
184624 string query;
184626 vector<string> names;
184628 string table_name;
184629
184630protected:
184631 void FlushInternal(ColumnDataCollection &collection) override;
184632};
184633
184634class InternalAppender : public BaseAppender {
184636 ClientContext &context;
184638 TableCatalogEntry &table;
184639
184640public:
184641 DUCKDB_API InternalAppender(ClientContext &context, TableCatalogEntry &table,
184642 const idx_t flush_count = DEFAULT_FLUSH_COUNT,
184643 const idx_t flush_memory_threshold = DConstants::INVALID_INDEX);
184644 DUCKDB_API ~InternalAppender() override;
184645
184646protected:
184647 void FlushInternal(ColumnDataCollection &collection) override;
184648};
184649
184650template <>
184651DUCKDB_API void BaseAppender::Append(bool value);
184652template <>
184653DUCKDB_API void BaseAppender::Append(int8_t value);
184654template <>
184655DUCKDB_API void BaseAppender::Append(int16_t value);
184656template <>
184657DUCKDB_API void BaseAppender::Append(int32_t value);
184658template <>
184659DUCKDB_API void BaseAppender::Append(int64_t value);
184660template <>
184661DUCKDB_API void BaseAppender::Append(hugeint_t value);
184662template <>
184663DUCKDB_API void BaseAppender::Append(uhugeint_t value);
184664template <>
184665DUCKDB_API void BaseAppender::Append(uint8_t value);
184666template <>
184667DUCKDB_API void BaseAppender::Append(uint16_t value);
184668template <>
184669DUCKDB_API void BaseAppender::Append(uint32_t value);
184670template <>
184671DUCKDB_API void BaseAppender::Append(uint64_t value);
184672template <>
184673DUCKDB_API void BaseAppender::Append(float value);
184674template <>
184675DUCKDB_API void BaseAppender::Append(double value);
184676template <>
184677DUCKDB_API void BaseAppender::Append(date_t value);
184678template <>
184679DUCKDB_API void BaseAppender::Append(dtime_t value);
184680template <>
184681DUCKDB_API void BaseAppender::Append(timestamp_t value);
184682template <>
184683DUCKDB_API void BaseAppender::Append(interval_t value);
184684template <>
184685DUCKDB_API void BaseAppender::Append(const char *value);
184686template <>
184687DUCKDB_API void BaseAppender::Append(string_t value);
184688template <>
184689DUCKDB_API void BaseAppender::Append(Value value);
184690template <>
184691DUCKDB_API void BaseAppender::Append(std::nullptr_t value);
184692
184693}
184694
184697
184700
184701
184702
184703
184704
184705
184706
184707
184708
184709
184710
184711
184712
184713
184714
184715
184716
184717
184739
184740
184741
184742#include <stddef.h>
184743#include <stdint.h>
184744
184745
184752
184754#ifdef __cplusplus
184755extern "C" {
184756#endif
184757
184758
184759#ifndef ARROW_FLAG_DICTIONARY_ORDERED
184760
184761#ifndef ARROW_C_DATA_INTERFACE
184762#define ARROW_C_DATA_INTERFACE
184763
184764#define ARROW_FLAG_DICTIONARY_ORDERED 1
184765#define ARROW_FLAG_NULLABLE 2
184766#define ARROW_FLAG_MAP_KEYS_SORTED 4
184767
184768struct ArrowSchema {
184769
184771 const char *name;
184772 const char *metadata;
184775 struct ArrowSchema **children;
184776 struct ArrowSchema *dictionary;
184777
184778
184779 void (*release)(struct ArrowSchema *);
184780
184781 void *private_data;
184782};
184783
184784struct ArrowArray {
184785
184791 const void **buffers;
184792 struct ArrowArray **children;
184793 struct ArrowArray *dictionary;
184794
184795
184796 void (*release)(struct ArrowArray *);
184797
184798 void *private_data;
184799};
184800
184801#endif
184802
184803#ifndef ARROW_C_STREAM_INTERFACE
184804#define ARROW_C_STREAM_INTERFACE
184805
184806struct ArrowArrayStream {
184807
184808
184809
184810
184811
184812
184813 int (*get_schema)(struct ArrowArrayStream *, struct ArrowSchema *out);
184814
184815
184816
184817
184818
184819
184820
184821 int (*get_next)(struct ArrowArrayStream *, struct ArrowArray *out);
184822
184823
184824
184825
184826
184827
184828
184829
184830
184831
184832 const char *(*get_last_error)(struct ArrowArrayStream *);
184833
184834
184835
184836 void (*release)(struct ArrowArrayStream *);
184837
184838
184839 void *private_data;
184840};
184841
184842#endif
184843#endif
184844
184846
184848
184849#ifndef ADBC_EXPORTING
184850#define ADBC_EXPORTING
184851
184852
184853
184854#if !defined(ADBC_EXPORT)
184855#if defined(_WIN32)
184856#if defined(ADBC_EXPORTING)
184857#define ADBC_EXPORT __declspec(dllexport)
184858#else
184859#define ADBC_EXPORT __declspec(dllimport)
184860#endif
184861#else
184862#define ADBC_EXPORT
184863#endif
184864#endif
184865
184874
184877
184879#define ADBC_STATUS_OK 0
184883#define ADBC_STATUS_UNKNOWN 1
184887#define ADBC_STATUS_NOT_IMPLEMENTED 2
184891#define ADBC_STATUS_NOT_FOUND 3
184895#define ADBC_STATUS_ALREADY_EXISTS 4
184901#define ADBC_STATUS_INVALID_ARGUMENT 5
184909#define ADBC_STATUS_INVALID_STATE 6
184916#define ADBC_STATUS_INVALID_DATA 7
184923#define ADBC_STATUS_INTEGRITY 8
184927#define ADBC_STATUS_INTERNAL 9
184933#define ADBC_STATUS_IO 10
184937#define ADBC_STATUS_CANCELLED 11
184941#define ADBC_STATUS_TIMEOUT 12
184945#define ADBC_STATUS_UNAUTHENTICATED 13
184949#define ADBC_STATUS_UNAUTHORIZED 14
184950
184957#define ADBC_ERROR_VENDOR_CODE_PRIVATE_DATA INT32_MIN
184958
184969struct ADBC_EXPORT AdbcError {
184971 char *message;
184972
184975
184979 char sqlstate[5];
184980
184985 void (*release)(struct AdbcError *error);
184986
184994 void *private_data;
184995
185003 struct AdbcDriver *private_driver;
185004};
185005
185006#ifdef __cplusplus
185010#define ADBC_ERROR_INIT \
185011 (AdbcError {nullptr, ADBC_ERROR_VENDOR_CODE_PRIVATE_DATA, {0, 0, 0, 0, 0}, nullptr, nullptr, nullptr})
185012#else
185016#define ADBC_ERROR_INIT \
185017 ((struct AdbcError) {NULL, ADBC_ERROR_VENDOR_CODE_PRIVATE_DATA, {0, 0, 0, 0, 0}, NULL, NULL, NULL})
185018#endif
185019
185027#define ADBC_ERROR_1_0_0_SIZE (offsetof(struct AdbcError, private_data))
185035#define ADBC_ERROR_1_1_0_SIZE (sizeof(struct AdbcError))
185036
185044struct ADBC_EXPORT AdbcErrorDetail {
185046 const char *key;
185050 size_t value_length;
185051};
185052
185056ADBC_EXPORT
185058
185065ADBC_EXPORT
185067
185082ADBC_EXPORT
185084
185086
185089
185094#define ADBC_VERSION_1_0_0 1000000
185095
185102#define ADBC_VERSION_1_1_0 1001000
185103
185107#define ADBC_OPTION_VALUE_ENABLED "true"
185111#define ADBC_OPTION_VALUE_DISABLED "false"
185112
185121#define ADBC_OPTION_URI "uri"
185130#define ADBC_OPTION_USERNAME "username"
185139#define ADBC_OPTION_PASSWORD "password"
185140
185145#define ADBC_INFO_VENDOR_NAME 0
185149#define ADBC_INFO_VENDOR_VERSION 1
185154#define ADBC_INFO_VENDOR_ARROW_VERSION 2
185155
185159#define ADBC_INFO_DRIVER_NAME 100
185163#define ADBC_INFO_DRIVER_VERSION 101
185167#define ADBC_INFO_DRIVER_ARROW_VERSION 102
185176#define ADBC_INFO_DRIVER_ADBC_VERSION 103
185177
185181#define ADBC_OBJECT_DEPTH_ALL 0
185185#define ADBC_OBJECT_DEPTH_CATALOGS 1
185189#define ADBC_OBJECT_DEPTH_DB_SCHEMAS 2
185193#define ADBC_OBJECT_DEPTH_TABLES 3
185197#define ADBC_OBJECT_DEPTH_COLUMNS ADBC_OBJECT_DEPTH_ALL
185198
185202
185204#define ADBC_STATISTIC_AVERAGE_BYTE_WIDTH_KEY 0
185210#define ADBC_STATISTIC_AVERAGE_BYTE_WIDTH_NAME "adbc.statistic.byte_width"
185212#define ADBC_STATISTIC_DISTINCT_COUNT_KEY 1
185216#define ADBC_STATISTIC_DISTINCT_COUNT_NAME "adbc.statistic.distinct_count"
185218#define ADBC_STATISTIC_MAX_BYTE_WIDTH_KEY 2
185224#define ADBC_STATISTIC_MAX_BYTE_WIDTH_NAME "adbc.statistic.byte_width"
185226#define ADBC_STATISTIC_MAX_VALUE_KEY 3
185228#define ADBC_STATISTIC_MAX_VALUE_NAME "adbc.statistic.byte_width"
185230#define ADBC_STATISTIC_MIN_VALUE_KEY 4
185232#define ADBC_STATISTIC_MIN_VALUE_NAME "adbc.statistic.byte_width"
185234#define ADBC_STATISTIC_NULL_COUNT_KEY 5
185238#define ADBC_STATISTIC_NULL_COUNT_NAME "adbc.statistic.null_count"
185240#define ADBC_STATISTIC_ROW_COUNT_KEY 6
185244#define ADBC_STATISTIC_ROW_COUNT_NAME "adbc.statistic.row_count"
185246
185253#define ADBC_CONNECTION_OPTION_AUTOCOMMIT "adbc.connection.autocommit"
185254
185261#define ADBC_CONNECTION_OPTION_READ_ONLY "adbc.connection.readonly"
185262
185270#define ADBC_CONNECTION_OPTION_CURRENT_CATALOG "adbc.connection.catalog"
185271
185279#define ADBC_CONNECTION_OPTION_CURRENT_DB_SCHEMA "adbc.connection.db_schema"
185280
185296#define ADBC_STATEMENT_OPTION_INCREMENTAL "adbc.statement.exec.incremental"
185297
185311#define ADBC_STATEMENT_OPTION_PROGRESS "adbc.statement.exec.progress"
185312
185324#define ADBC_STATEMENT_OPTION_MAX_PROGRESS "adbc.statement.exec.max_progress"
185325
185337#define ADBC_CONNECTION_OPTION_ISOLATION_LEVEL "adbc.connection.transaction.isolation_level"
185338
185342#define ADBC_OPTION_ISOLATION_LEVEL_DEFAULT "adbc.connection.transaction.isolation.default"
185343
185348#define ADBC_OPTION_ISOLATION_LEVEL_READ_UNCOMMITTED "adbc.connection.transaction.isolation.read_uncommitted"
185349
185363#define ADBC_OPTION_ISOLATION_LEVEL_READ_COMMITTED "adbc.connection.transaction.isolation.read_committed"
185364
185372#define ADBC_OPTION_ISOLATION_LEVEL_REPEATABLE_READ "adbc.connection.transaction.isolation.repeatable_read"
185373
185380#define ADBC_OPTION_ISOLATION_LEVEL_SNAPSHOT "adbc.connection.transaction.isolation.snapshot"
185381
185388#define ADBC_OPTION_ISOLATION_LEVEL_SERIALIZABLE "adbc.connection.transaction.isolation.serializable"
185389
185400#define ADBC_OPTION_ISOLATION_LEVEL_LINEARIZABLE "adbc.connection.transaction.isolation.linearizable"
185401
185413
185422#define ADBC_INGEST_OPTION_TARGET_TABLE "adbc.ingest.target_table"
185426#define ADBC_INGEST_OPTION_MODE "adbc.ingest.mode"
185428#define ADBC_INGEST_OPTION_MODE_CREATE "adbc.ingest.mode.create"
185432#define ADBC_INGEST_OPTION_MODE_APPEND "adbc.ingest.mode.append"
185436#define ADBC_INGEST_OPTION_MODE_REPLACE "adbc.ingest.mode.replace"
185441#define ADBC_INGEST_OPTION_MODE_CREATE_APPEND "adbc.ingest.mode.create_append"
185442
185444
185446
185453
185457struct ADBC_EXPORT AdbcDatabase {
185460 void *private_data;
185463 struct AdbcDriver *private_driver;
185464};
185465
185467
185471
185480struct ADBC_EXPORT AdbcConnection {
185483 void *private_data;
185486 struct AdbcDriver *private_driver;
185487};
185488
185490
185499
185518struct ADBC_EXPORT AdbcStatement {
185521 void *private_data;
185522
185525 struct AdbcDriver *private_driver;
185526};
185527
185544
185546struct AdbcPartitions {
185548 size_t num_partitions;
185549
185554
185556 const size_t *partition_lengths;
185557
185560 void *private_data;
185561
185566 void (*release)(struct AdbcPartitions *partitions);
185567};
185568
185570
185572
185578
185585struct ADBC_EXPORT AdbcDriver {
185589 void *private_data;
185593 void *private_manager;
185594
185599 AdbcStatusCode (*release)(
struct AdbcDriver *driver,
struct AdbcError *error);
185600
185601 AdbcStatusCode (*DatabaseInit)(
struct AdbcDatabase *,
struct AdbcError *);
185602 AdbcStatusCode (*DatabaseNew)(
struct AdbcDatabase *,
struct AdbcError *);
185603 AdbcStatusCode (*DatabaseSetOption)(
struct AdbcDatabase *,
const char *,
const char *,
struct AdbcError *);
185604 AdbcStatusCode (*DatabaseRelease)(
struct AdbcDatabase *,
struct AdbcError *);
185605
185606 AdbcStatusCode (*ConnectionCommit)(
struct AdbcConnection *,
struct AdbcError *);
185607 AdbcStatusCode (*ConnectionGetInfo)(
struct AdbcConnection *,
const uint32_t *, size_t,
struct ArrowArrayStream *,
185608 struct AdbcError *);
185609 AdbcStatusCode (*ConnectionGetObjects)(
struct AdbcConnection *, int,
const char *,
const char *,
const char *,
185610 const char **, const char *, struct ArrowArrayStream *, struct AdbcError *);
185611 AdbcStatusCode (*ConnectionGetTableSchema)(
struct AdbcConnection *,
const char *,
const char *,
const char *,
185612 struct ArrowSchema *, struct AdbcError *);
185613 AdbcStatusCode (*ConnectionGetTableTypes)(
struct AdbcConnection *,
struct ArrowArrayStream *,
struct AdbcError *);
185614 AdbcStatusCode (*ConnectionInit)(
struct AdbcConnection *,
struct AdbcDatabase *,
struct AdbcError *);
185615 AdbcStatusCode (*ConnectionNew)(
struct AdbcConnection *,
struct AdbcError *);
185616 AdbcStatusCode (*ConnectionSetOption)(
struct AdbcConnection *,
const char *,
const char *,
struct AdbcError *);
185618 struct ArrowArrayStream *, struct AdbcError *);
185619 AdbcStatusCode (*ConnectionRelease)(
struct AdbcConnection *,
struct AdbcError *);
185620 AdbcStatusCode (*ConnectionRollback)(
struct AdbcConnection *,
struct AdbcError *);
185621
185622 AdbcStatusCode (*StatementBind)(
struct AdbcStatement *,
struct ArrowArray *,
struct ArrowSchema *,
185623 struct AdbcError *);
185624 AdbcStatusCode (*StatementBindStream)(
struct AdbcStatement *,
struct ArrowArrayStream *,
struct AdbcError *);
185625 AdbcStatusCode (*StatementExecuteQuery)(
struct AdbcStatement *,
struct ArrowArrayStream *,
int64_t *,
185626 struct AdbcError *);
185627 AdbcStatusCode (*StatementExecutePartitions)(
struct AdbcStatement *,
struct ArrowSchema *,
struct AdbcPartitions *,
185628 int64_t *,
struct AdbcError *);
185629 AdbcStatusCode (*StatementGetParameterSchema)(
struct AdbcStatement *,
struct ArrowSchema *,
struct AdbcError *);
185630 AdbcStatusCode (*StatementNew)(
struct AdbcConnection *,
struct AdbcStatement *,
struct AdbcError *);
185631 AdbcStatusCode (*StatementPrepare)(
struct AdbcStatement *,
struct AdbcError *);
185632 AdbcStatusCode (*StatementRelease)(
struct AdbcStatement *,
struct AdbcError *);
185633 AdbcStatusCode (*StatementSetOption)(
struct AdbcStatement *,
const char *,
const char *,
struct AdbcError *);
185634 AdbcStatusCode (*StatementSetSqlQuery)(
struct AdbcStatement *,
const char *,
struct AdbcError *);
185635 AdbcStatusCode (*StatementSetSubstraitPlan)(
struct AdbcStatement *,
const uint8_t *, size_t,
struct AdbcError *);
185636
185658
185659 int (*ErrorGetDetailCount)(const struct AdbcError *error);
185660 struct AdbcErrorDetail (*ErrorGetDetail)(const struct AdbcError *error, int index);
185661 const struct AdbcError *(*ErrorFromArrayStream)(
struct ArrowArrayStream *stream,
AdbcStatusCode *status);
185662
185663 AdbcStatusCode (*DatabaseGetOption)(
struct AdbcDatabase *,
const char *,
char *,
size_t *,
struct AdbcError *);
185664 AdbcStatusCode (*DatabaseGetOptionBytes)(
struct AdbcDatabase *,
const char *,
uint8_t *,
size_t *,
185665 struct AdbcError *);
185666 AdbcStatusCode (*DatabaseGetOptionDouble)(
struct AdbcDatabase *,
const char *,
double *,
struct AdbcError *);
185667 AdbcStatusCode (*DatabaseGetOptionInt)(
struct AdbcDatabase *,
const char *,
int64_t *,
struct AdbcError *);
185668 AdbcStatusCode (*DatabaseSetOptionBytes)(
struct AdbcDatabase *,
const char *,
const uint8_t *, size_t,
185669 struct AdbcError *);
185670 AdbcStatusCode (*DatabaseSetOptionDouble)(
struct AdbcDatabase *,
const char *, double,
struct AdbcError *);
185671 AdbcStatusCode (*DatabaseSetOptionInt)(
struct AdbcDatabase *,
const char *,
int64_t,
struct AdbcError *);
185672
185673 AdbcStatusCode (*ConnectionCancel)(
struct AdbcConnection *,
struct AdbcError *);
185674 AdbcStatusCode (*ConnectionGetOption)(
struct AdbcConnection *,
const char *,
char *,
size_t *,
struct AdbcError *);
185675 AdbcStatusCode (*ConnectionGetOptionBytes)(
struct AdbcConnection *,
const char *,
uint8_t *,
size_t *,
185676 struct AdbcError *);
185677 AdbcStatusCode (*ConnectionGetOptionDouble)(
struct AdbcConnection *,
const char *,
double *,
struct AdbcError *);
185678 AdbcStatusCode (*ConnectionGetOptionInt)(
struct AdbcConnection *,
const char *,
int64_t *,
struct AdbcError *);
185679 AdbcStatusCode (*ConnectionGetStatistics)(
struct AdbcConnection *,
const char *,
const char *,
const char *, char,
185680 struct ArrowArrayStream *, struct AdbcError *);
185681 AdbcStatusCode (*ConnectionGetStatisticNames)(
struct AdbcConnection *,
struct ArrowArrayStream *,
185682 struct AdbcError *);
185683 AdbcStatusCode (*ConnectionSetOptionBytes)(
struct AdbcConnection *,
const char *,
const uint8_t *, size_t,
185684 struct AdbcError *);
185685 AdbcStatusCode (*ConnectionSetOptionDouble)(
struct AdbcConnection *,
const char *, double,
struct AdbcError *);
185686 AdbcStatusCode (*ConnectionSetOptionInt)(
struct AdbcConnection *,
const char *,
int64_t,
struct AdbcError *);
185687
185688 AdbcStatusCode (*StatementCancel)(
struct AdbcStatement *,
struct AdbcError *);
185689 AdbcStatusCode (*StatementExecuteSchema)(
struct AdbcStatement *,
struct ArrowSchema *,
struct AdbcError *);
185690 AdbcStatusCode (*StatementGetOption)(
struct AdbcStatement *,
const char *,
char *,
size_t *,
struct AdbcError *);
185691 AdbcStatusCode (*StatementGetOptionBytes)(
struct AdbcStatement *,
const char *,
uint8_t *,
size_t *,
185692 struct AdbcError *);
185693 AdbcStatusCode (*StatementGetOptionDouble)(
struct AdbcStatement *,
const char *,
double *,
struct AdbcError *);
185694 AdbcStatusCode (*StatementGetOptionInt)(
struct AdbcStatement *,
const char *,
int64_t *,
struct AdbcError *);
185695 AdbcStatusCode (*StatementSetOptionBytes)(
struct AdbcStatement *,
const char *,
const uint8_t *, size_t,
185696 struct AdbcError *);
185697 AdbcStatusCode (*StatementSetOptionDouble)(
struct AdbcStatement *,
const char *, double,
struct AdbcError *);
185698 AdbcStatusCode (*StatementSetOptionInt)(
struct AdbcStatement *,
const char *,
int64_t,
struct AdbcError *);
185699
185701};
185702
185709#define ADBC_DRIVER_1_0_0_SIZE (offsetof(struct AdbcDriver, ErrorGetDetailCount))
185710
185717#define ADBC_DRIVER_1_1_0_SIZE (sizeof(struct AdbcDriver))
185718
185720
185723
185731ADBC_EXPORT
185733
185770ADBC_EXPORT
185772 struct AdbcError *error);
185773
185809ADBC_EXPORT
185811 size_t *length, struct AdbcError *error);
185812
185832ADBC_EXPORT
185834 struct AdbcError *error);
185835
185855ADBC_EXPORT
185857 struct AdbcError *error);
185858
185870ADBC_EXPORT
185872 struct AdbcError *error);
185873
185884ADBC_EXPORT
185886 size_t length, struct AdbcError *error);
185887
185897ADBC_EXPORT
185899 struct AdbcError *error);
185900
185910ADBC_EXPORT
185912 struct AdbcError *error);
185913
185918ADBC_EXPORT
185920
185925ADBC_EXPORT
185927
185929
185932
185940ADBC_EXPORT
185942
185954ADBC_EXPORT
185956 struct AdbcError *error);
185957
185968ADBC_EXPORT
185970 size_t length, struct AdbcError *error);
185971
185984ADBC_EXPORT
185986 struct AdbcError *error);
185987
186000ADBC_EXPORT
186002 struct AdbcError *error);
186003
186008ADBC_EXPORT
186010 struct AdbcError *error);
186011
186017ADBC_EXPORT
186019
186040ADBC_EXPORT
186042
186066
186103ADBC_EXPORT
186105 size_t info_codes_length, struct ArrowArrayStream *out, struct AdbcError *error);
186106
186211ADBC_EXPORT
186213 const char *db_schema, const char *table_name, const char **table_type,
186214 const char *column_name, struct ArrowArrayStream *out, struct AdbcError *error);
186215
186244ADBC_EXPORT
186246 struct AdbcError *error);
186247
186283ADBC_EXPORT
186285 size_t *length, struct AdbcError *error);
186286
186306ADBC_EXPORT
186308 struct AdbcError *error);
186309
186329ADBC_EXPORT
186331 struct AdbcError *error);
186332
186393ADBC_EXPORT
186395 const char *db_schema, const char *table_name, char approximate,
186396 struct ArrowArrayStream *out, struct AdbcError *error);
186397
186411ADBC_EXPORT
186413 struct AdbcError *error);
186414
186423ADBC_EXPORT
186425 const char *db_schema, const char *table_name, struct ArrowSchema *schema,
186426 struct AdbcError *error);
186427
186441ADBC_EXPORT
186443 struct AdbcError *error);
186444
186446
186459
186473ADBC_EXPORT
186475 size_t serialized_length, struct ArrowArrayStream *out,
186476 struct AdbcError *error);
186477
186479
186487
186493ADBC_EXPORT
186495
186501ADBC_EXPORT
186503
186505
186507
186510
186518ADBC_EXPORT
186520 struct AdbcError *error);
186521
186526ADBC_EXPORT
186528
186544ADBC_EXPORT
186546 int64_t *rows_affected, struct AdbcError *error);
186547
186564ADBC_EXPORT
186566 struct AdbcError *error);
186567
186572ADBC_EXPORT
186574
186581
186591ADBC_EXPORT
186593
186595
186602
186613ADBC_EXPORT
186615 struct AdbcError *error);
186616
186618
186629ADBC_EXPORT
186631 struct AdbcError *error);
186632
186641ADBC_EXPORT
186643 struct AdbcError *error);
186644
186665ADBC_EXPORT
186667
186704ADBC_EXPORT
186706 struct AdbcError *error);
186707
186743ADBC_EXPORT
186745 size_t *length, struct AdbcError *error);
186746
186766ADBC_EXPORT
186768 struct AdbcError *error);
186769
186789ADBC_EXPORT
186791 struct AdbcError *error);
186792
186808ADBC_EXPORT
186810 struct AdbcError *error);
186811
186819ADBC_EXPORT
186821 struct AdbcError *error);
186822
186833ADBC_EXPORT
186835 size_t length, struct AdbcError *error);
186836
186846ADBC_EXPORT
186848 struct AdbcError *error);
186849
186859ADBC_EXPORT
186861 struct AdbcError *error);
186862
186865
186878ADBC_EXPORT
186880 struct AdbcPartitions *partitions, int64_t *rows_affected,
186881 struct AdbcError *error);
186882
186884
186886
186889
186917
186919
186920#endif
186921
186922#ifdef __cplusplus
186923}
186924#endif
186925
186926
186927
186928
186929
186930
186931
186932
186933
186934
186935
186936
186937
186938
186939
186940
186941
186942
186943
186944
186945
186946
186947
186948
186949
186950
186951
186952
186953
186954
186955
186956
186957
186958
186959
186960
186961
186962
186963
186964
186965
186966
186967
186968
186969
186970
186971
186972
186973
186974
186975
186976
186977
186978
186979
186980namespace duckdb {
186981class ClientContext;
186982class DatabaseInstance;
186983class Connection;
186984
186985class ConnectionManager {
186986public:
186987 ConnectionManager();
186988
186989 void AddConnection(ClientContext &context);
186990 void RemoveConnection(ClientContext &context);
186991
186992 vector<shared_ptr<ClientContext>> GetConnectionList();
186993 const reference_map_t<ClientContext, weak_ptr<ClientContext>> &GetConnectionListReference() const {
186994 return connections;
186995 }
186996 idx_t GetConnectionCount()
const;
186997
186998 void AssignConnectionId(Connection &connection);
186999
187000 static ConnectionManager &Get(DatabaseInstance &db);
187001 static ConnectionManager &Get(ClientContext &context);
187002
187003private:
187004 mutex connections_lock;
187005 reference_map_t<ClientContext, weak_ptr<ClientContext>> connections;
187006 atomic<idx_t> connection_count;
187007 atomic<connection_t> current_connection_id;
187008};
187009
187010}
187011
187012
187013
187014#include <functional>
187015
187016namespace duckdb {
187017class DBInstanceCache;
187018class DatabaseFilePathManager;
187019
187020struct DatabaseCacheEntry {
187021 DatabaseCacheEntry();
187022 explicit DatabaseCacheEntry(const shared_ptr<DuckDB> &database);
187023 ~DatabaseCacheEntry();
187024
187025 weak_ptr<DuckDB> database;
187026 mutex update_database_mutex;
187027};
187028
187029enum class CacheBehavior { AUTOMATIC, ALWAYS_CACHE, NEVER_CACHE };
187030
187031class DBInstanceCache {
187032public:
187033 DBInstanceCache();
187034 ~DBInstanceCache();
187035
187037 shared_ptr<DuckDB> GetInstance(const string &database, const DBConfig &config_dict);
187038
187040 shared_ptr<DuckDB> CreateInstance(const string &database, DBConfig &config_dict, bool cache_instance = true,
187041 const std::function<void(DuckDB &)> &on_create = nullptr);
187042
187044 shared_ptr<DuckDB> GetOrCreateInstance(const string &database, DBConfig &config_dict, bool cache_instance,
187045 const std::function<void(DuckDB &)> &on_create = nullptr);
187046 shared_ptr<DuckDB> GetOrCreateInstance(const string &database, DBConfig &config_dict,
187047 CacheBehavior cache_behavior = CacheBehavior::AUTOMATIC,
187048 const std::function<void(DuckDB &)> &on_create = nullptr);
187049
187050private:
187051 shared_ptr<DatabaseFilePathManager> path_manager;
187053 unordered_map<string, weak_ptr<DatabaseCacheEntry>> db_instances;
187054
187056 mutex cache_lock;
187057
187058private:
187059 shared_ptr<DuckDB> GetInstanceInternal(const string &database, const DBConfig &config,
187060 std::unique_lock<std::mutex> &db_instances_lock);
187061 shared_ptr<DuckDB> CreateInstanceInternal(const string &database, DBConfig &config_dict, bool cache_instance,
187062 std::unique_lock<std::mutex> db_instances_lock,
187063 const std::function<void(DuckDB &)> &on_create);
187064};
187065}
187066
187067
187068#include <cstring>
187069#include <cassert>
187070
187071#ifdef _WIN32
187072#ifndef strdup
187073#define strdup _strdup
187074#endif
187075#endif
187076
187077namespace duckdb {
187078
187079struct DBInstanceCacheWrapper {
187080 unique_ptr<DBInstanceCache> instance_cache;
187081};
187082
187083struct DatabaseWrapper {
187084 shared_ptr<DuckDB> database;
187085};
187086
187087struct CClientContextWrapper {
187088 explicit CClientContextWrapper(ClientContext &context) : context(context) {};
187089 ClientContext &context;
187090};
187091
187092struct CClientArrowOptionsWrapper {
187093 explicit CClientArrowOptionsWrapper(ClientProperties &properties) : properties(properties) {};
187094 ClientProperties properties;
187095};
187096
187097struct PreparedStatementWrapper {
187099 case_insensitive_map_t<BoundParameterData> values;
187100 unique_ptr<PreparedStatement> statement;
187101 bool success = true;
187102 ErrorData error_data;
187103 unordered_map<idx_t, string> param_index_to_name;
187104};
187105
187106struct ExtractStatementsWrapper {
187107 vector<unique_ptr<SQLStatement>> statements;
187108 string error;
187109};
187110
187111struct PendingStatementWrapper {
187112 unique_ptr<PendingQueryResult> statement;
187113 bool allow_streaming;
187114};
187115
187116struct ArrowResultWrapper {
187117 unique_ptr<MaterializedQueryResult> result;
187118 unique_ptr<DataChunk> current_chunk;
187119};
187120
187121struct AppenderWrapper {
187122 unique_ptr<BaseAppender> appender;
187123 ErrorData error_data;
187124};
187125
187126struct TableDescriptionWrapper {
187127 unique_ptr<TableDescription> description;
187128 string error;
187129};
187130
187131struct ErrorDataWrapper {
187132 ErrorData error_data;
187133};
187134
187135struct ExpressionWrapper {
187136 unique_ptr<Expression> expr;
187137};
187138
187139enum class CAPIResultSetType :
uint8_t {
187140 CAPI_RESULT_TYPE_NONE = 0,
187141 CAPI_RESULT_TYPE_MATERIALIZED,
187142 CAPI_RESULT_TYPE_STREAMING,
187143 CAPI_RESULT_TYPE_DEPRECATED
187144};
187145
187146struct DuckDBResultData {
187148 unique_ptr<QueryResult> result;
187149
187150
187151 CAPIResultSetType result_set_type;
187152};
187153
187154duckdb_type LogicalTypeIdToC(const LogicalTypeId type);
187156idx_t GetCTypeSize(
const duckdb_type type);
187157duckdb_statement_type StatementTypeToC(const StatementType type);
187158duckdb_error_type ErrorTypeToC(const ExceptionType type);
187159ExceptionType ErrorTypeFromC(const duckdb_error_type type);
187160
187161duckdb_state DuckDBTranslateResult(unique_ptr<QueryResult> result, duckdb_result *out);
187162bool DeprecatedMaterializeResult(duckdb_result *result);
187163
187164}
187165
187166
187167#include <string>
187168
187169namespace duckdb_adbc {
187170
187171class AppenderWrapper {
187172public:
187173 AppenderWrapper(duckdb_connection conn, const char *catalog, const char *schema, const char *table)
187174 : appender(nullptr) {
187175
187176
187177 auto created = duckdb_appender(nullptr);
187179 if (created) {
187181 }
187182 return;
187183 }
187184 appender = created;
187185 }
187186 ~AppenderWrapper() {
187187 if (appender) {
187189 }
187190 }
187191
187192 duckdb_appender Get() const {
187193 return appender;
187194 }
187195 bool Valid() const {
187196 return appender != nullptr;
187197 }
187198
187199private:
187200 duckdb_appender appender;
187201};
187202
187203class DataChunkWrapper {
187204public:
187205 DataChunkWrapper() : chunk(nullptr) {
187206 }
187207
187208 ~DataChunkWrapper() {
187209 if (chunk) {
187211 }
187212 }
187213
187214 explicit operator duckdb_data_chunk() const {
187215 return chunk;
187216 }
187217
187218 duckdb_data_chunk chunk;
187219};
187220
187221class ConvertedSchemaWrapper {
187222public:
187223 ConvertedSchemaWrapper() : schema(nullptr) {
187224 }
187225 ~ConvertedSchemaWrapper() {
187226 if (schema) {
187228 }
187229 }
187230 duckdb_arrow_converted_schema *GetPtr() {
187231 return &schema;
187232 }
187233
187234 explicit operator duckdb_arrow_converted_schema() const {
187235 return schema;
187236 }
187237 duckdb_arrow_converted_schema Get() const {
187238 return schema;
187239 }
187240
187241private:
187242 duckdb_arrow_converted_schema schema;
187243};
187244
187245AdbcStatusCode DatabaseNew(
struct AdbcDatabase *database,
struct AdbcError *error);
187246
187247AdbcStatusCode DatabaseSetOption(
struct AdbcDatabase *database,
const char *key,
const char *value,
187248 struct AdbcError *error);
187249
187250AdbcStatusCode DatabaseInit(
struct AdbcDatabase *database,
struct AdbcError *error);
187251
187252AdbcStatusCode DatabaseRelease(
struct AdbcDatabase *database,
struct AdbcError *error);
187253
187254AdbcStatusCode ConnectionNew(
struct AdbcConnection *connection,
struct AdbcError *error);
187255
187256AdbcStatusCode ConnectionSetOption(
struct AdbcConnection *connection,
const char *key,
const char *value,
187257 struct AdbcError *error);
187258
187259AdbcStatusCode ConnectionInit(
struct AdbcConnection *connection,
struct AdbcDatabase *database,
187260 struct AdbcError *error);
187261
187262AdbcStatusCode ConnectionRelease(
struct AdbcConnection *connection,
struct AdbcError *error);
187263
187264AdbcStatusCode ConnectionGetInfo(
struct AdbcConnection *connection,
const uint32_t *info_codes,
187265 size_t info_codes_length, struct ArrowArrayStream *out, struct AdbcError *error);
187266
187267AdbcStatusCode ConnectionGetObjects(
struct AdbcConnection *connection,
int depth,
const char *catalog,
187268 const char *db_schema, const char *table_name, const char **table_type,
187269 const char *column_name, struct ArrowArrayStream *out, struct AdbcError *error);
187270
187271AdbcStatusCode ConnectionGetTableSchema(
struct AdbcConnection *connection,
const char *catalog,
const char *db_schema,
187272 const char *table_name, struct ArrowSchema *schema, struct AdbcError *error);
187273
187274AdbcStatusCode ConnectionGetTableTypes(
struct AdbcConnection *connection,
struct ArrowArrayStream *out,
187275 struct AdbcError *error);
187276
187277AdbcStatusCode ConnectionReadPartition(
struct AdbcConnection *connection,
const uint8_t *serialized_partition,
187278 size_t serialized_length, struct ArrowArrayStream *out, struct AdbcError *error);
187279
187280AdbcStatusCode ConnectionCommit(
struct AdbcConnection *connection,
struct AdbcError *error);
187281
187282AdbcStatusCode ConnectionRollback(
struct AdbcConnection *connection,
struct AdbcError *error);
187283
187284AdbcStatusCode ConnectionCancel(
struct AdbcConnection *connection,
struct AdbcError *error);
187285
187286
187287AdbcStatusCode DatabaseGetOption(
struct AdbcDatabase *database,
const char *key,
char *value,
size_t *length,
187288 struct AdbcError *error);
187289AdbcStatusCode DatabaseGetOptionBytes(
struct AdbcDatabase *database,
const char *key, uint8_t *value,
size_t *length,
187290 struct AdbcError *error);
187291AdbcStatusCode DatabaseGetOptionDouble(
struct AdbcDatabase *database,
const char *key,
double *value,
187292 struct AdbcError *error);
187293AdbcStatusCode DatabaseGetOptionInt(
struct AdbcDatabase *database,
const char *key, int64_t *value,
187294 struct AdbcError *error);
187295AdbcStatusCode DatabaseSetOptionBytes(
struct AdbcDatabase *database,
const char *key,
const uint8_t *value,
187296 size_t length, struct AdbcError *error);
187297AdbcStatusCode DatabaseSetOptionInt(
struct AdbcDatabase *database,
const char *key, int64_t value,
187298 struct AdbcError *error);
187299AdbcStatusCode DatabaseSetOptionDouble(
struct AdbcDatabase *database,
const char *key,
double value,
187300 struct AdbcError *error);
187301
187302
187303AdbcStatusCode ConnectionGetOption(
struct AdbcConnection *connection,
const char *key,
char *value,
size_t *length,
187304 struct AdbcError *error);
187305AdbcStatusCode ConnectionGetOptionBytes(
struct AdbcConnection *connection,
const char *key, uint8_t *value,
187306 size_t *length, struct AdbcError *error);
187307AdbcStatusCode ConnectionGetOptionDouble(
struct AdbcConnection *connection,
const char *key,
double *value,
187308 struct AdbcError *error);
187309AdbcStatusCode ConnectionGetOptionInt(
struct AdbcConnection *connection,
const char *key, int64_t *value,
187310 struct AdbcError *error);
187311AdbcStatusCode ConnectionSetOptionBytes(
struct AdbcConnection *connection,
const char *key,
const uint8_t *value,
187312 size_t length, struct AdbcError *error);
187313AdbcStatusCode ConnectionSetOptionInt(
struct AdbcConnection *connection,
const char *key, int64_t value,
187314 struct AdbcError *error);
187315AdbcStatusCode ConnectionSetOptionDouble(
struct AdbcConnection *connection,
const char *key,
double value,
187316 struct AdbcError *error);
187317
187318
187319AdbcStatusCode StatementGetOption(
struct AdbcStatement *statement,
const char *key,
char *value,
size_t *length,
187320 struct AdbcError *error);
187321AdbcStatusCode StatementGetOptionBytes(
struct AdbcStatement *statement,
const char *key, uint8_t *value,
size_t *length,
187322 struct AdbcError *error);
187323AdbcStatusCode StatementGetOptionDouble(
struct AdbcStatement *statement,
const char *key,
double *value,
187324 struct AdbcError *error);
187325AdbcStatusCode StatementGetOptionInt(
struct AdbcStatement *statement,
const char *key, int64_t *value,
187326 struct AdbcError *error);
187327AdbcStatusCode StatementSetOptionBytes(
struct AdbcStatement *statement,
const char *key,
const uint8_t *value,
187328 size_t length, struct AdbcError *error);
187329AdbcStatusCode StatementSetOptionInt(
struct AdbcStatement *statement,
const char *key, int64_t value,
187330 struct AdbcError *error);
187331AdbcStatusCode StatementSetOptionDouble(
struct AdbcStatement *statement,
const char *key,
double value,
187332 struct AdbcError *error);
187333
187334const AdbcError *ErrorFromArrayStream(
struct ArrowArrayStream *stream,
AdbcStatusCode *status);
187335
187336AdbcStatusCode StatementNew(
struct AdbcConnection *connection,
struct AdbcStatement *statement,
187337 struct AdbcError *error);
187338
187339AdbcStatusCode StatementRelease(
struct AdbcStatement *statement,
struct AdbcError *error);
187340
187341AdbcStatusCode StatementExecuteQuery(
struct AdbcStatement *statement,
struct ArrowArrayStream *out,
187342 int64_t *rows_affected, struct AdbcError *error);
187343
187344AdbcStatusCode StatementCancel(
struct AdbcStatement *statement,
struct AdbcError *error);
187345
187346AdbcStatusCode StatementPrepare(
struct AdbcStatement *statement,
struct AdbcError *error);
187347
187348AdbcStatusCode StatementSetSqlQuery(
struct AdbcStatement *statement,
const char *query,
struct AdbcError *error);
187349
187350AdbcStatusCode StatementSetSubstraitPlan(
struct AdbcStatement *statement,
const uint8_t *plan,
size_t length,
187351 struct AdbcError *error);
187352
187353AdbcStatusCode StatementBind(
struct AdbcStatement *statement,
struct ArrowArray *values,
struct ArrowSchema *schema,
187354 struct AdbcError *error);
187355
187356AdbcStatusCode StatementBindStream(
struct AdbcStatement *statement,
struct ArrowArrayStream *stream,
187357 struct AdbcError *error);
187358
187359AdbcStatusCode StatementGetParameterSchema(
struct AdbcStatement *statement,
struct ArrowSchema *schema,
187360 struct AdbcError *error);
187361
187362AdbcStatusCode StatementSetOption(
struct AdbcStatement *statement,
const char *key,
const char *value,
187363 struct AdbcError *error);
187364
187365AdbcStatusCode StatementExecutePartitions(
struct AdbcStatement *statement,
struct ArrowSchema *schema,
187366 struct AdbcPartitions *partitions, int64_t *rows_affected,
187367 struct AdbcError *error);
187368
187369void InitializeADBCError(AdbcError *error);
187370
187371}
187372
187374void SetError(
struct AdbcError *error,
const std::string &message);
187375
187376
187377
187378
187379
187380
187381
187382
187383
187384
187385
187386
187387
187388#include <list>
187389
187390namespace duckdb {
187391class ArrowTypeExtensionData;
187392struct DBConfig;
187393struct ArrowConverter {
187394 DUCKDB_API static void ToArrowSchema(ArrowSchema *out_schema, const vector<LogicalType> &types,
187395 const vector<string> &names, ClientProperties &options);
187396 DUCKDB_API static void
187397 ToArrowArray(DataChunk &input, ArrowArray *out_array, ClientProperties options,
187398 const unordered_map<idx_t, const shared_ptr<ArrowTypeExtensionData>> &extension_type_cast);
187399};
187400
187401
187402
187403
187404struct DuckDBArrowSchemaHolder {
187405
187406 vector<ArrowSchema> children;
187407
187408 vector<ArrowSchema *> children_ptrs;
187410 std::list<vector<ArrowSchema>> nested_children;
187411 std::list<vector<ArrowSchema *>> nested_children_ptr;
187413 vector<unsafe_unique_array<char>> owned_type_names;
187414 vector<unsafe_unique_array<char>> owned_column_names;
187416 vector<unsafe_unique_array<char>> metadata_info;
187417 vector<unsafe_unique_array<char>> extension_format;
187418};
187419
187420}
187421
187422
187423
187424
187425
187426
187427
187428
187429
187430
187431
187432
187433
187434namespace duckdb {
187435struct CastParameters;
187436
187438class Blob {
187439public:
187440
187441 static constexpr const char *HEX_TABLE = "0123456789ABCDEF";
187442
187443 static const int HEX_MAP[256];
187445 static constexpr const char *BASE64_MAP = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
187447 static constexpr const char BASE64_PADDING = '=';
187448
187449public:
187451 DUCKDB_API
static idx_t GetStringSize(string_t blob);
187454 DUCKDB_API static void ToString(string_t blob, char *output);
187456 DUCKDB_API static string ToString(string_t blob);
187457
187459 DUCKDB_API static bool TryGetBlobSize(string_t str, idx_t &result_size, CastParameters ¶meters);
187460 DUCKDB_API
static idx_t GetBlobSize(string_t str);
187461 DUCKDB_API
static idx_t GetBlobSize(string_t str, CastParameters ¶meters);
187464 DUCKDB_API static void ToBlob(string_t str, data_ptr_t output);
187466 DUCKDB_API static string ToBlob(string_t str);
187467 DUCKDB_API static string ToBlob(string_t str, CastParameters ¶meters);
187468
187469
187470 DUCKDB_API static string ToBase64(string_t blob);
187472 DUCKDB_API
static idx_t ToBase64Size(string_t blob);
187474 DUCKDB_API static void ToBase64(string_t blob, char *output);
187475
187476 DUCKDB_API static string FromBase64(string_t blob);
187478 DUCKDB_API
static idx_t FromBase64Size(string_t str);
187480 DUCKDB_API static void FromBase64(string_t str, data_ptr_t output, idx_t output_size);
187481};
187482}
187483
187484
187485
187486
187487
187488
187489
187490
187491
187492
187493
187494
187495namespace duckdb {
187496
187497template <class PHYSICAL_TYPE>
187498struct DecimalWidth {};
187499
187500template <>
187501struct DecimalWidth<
int16_t> {
187503};
187504
187505template <>
187506struct DecimalWidth<
int32_t> {
187508};
187509
187510template <>
187511struct DecimalWidth<
int64_t> {
187513};
187514
187515template <>
187516struct DecimalWidth<hugeint_t> {
187518};
187519
187521class Decimal {
187522public:
187523 static constexpr uint8_t MAX_WIDTH_INT16 = DecimalWidth<int16_t>::max;
187524 static constexpr uint8_t MAX_WIDTH_INT32 = DecimalWidth<int32_t>::max;
187525 static constexpr uint8_t MAX_WIDTH_INT64 = DecimalWidth<int64_t>::max;
187526 static constexpr uint8_t MAX_WIDTH_INT128 = DecimalWidth<hugeint_t>::max;
187527 static constexpr uint8_t MAX_WIDTH_DECIMAL = MAX_WIDTH_INT128;
187528
187529public:
187530 static string ToString(int16_t value, uint8_t width, uint8_t scale);
187531 static string ToString(int32_t value, uint8_t width, uint8_t scale);
187532 static string ToString(int64_t value, uint8_t width, uint8_t scale);
187533 static string ToString(hugeint_t value, uint8_t width, uint8_t scale);
187534};
187535}
187536
187537
187538
187539
187540
187541
187542
187543
187544
187545
187546#include <array>
187547
187548
187549
187550
187551namespace duckdb {
187552class RandomEngine;
187553
187555class BaseUUID {
187556public:
187557 constexpr static const uint8_t STRING_SIZE = 36;
187559 static bool FromString(const string &str, hugeint_t &result, bool strict = false);
187561 static bool FromCString(const char *str, idx_t len, hugeint_t &result) {
187562 return FromString(string(str, 0, len), result);
187563 }
187565 static void ToString(hugeint_t input, char *buf);
187566
187568 static hugeint_t FromUHugeint(uhugeint_t input);
187570 static uhugeint_t ToUHugeint(hugeint_t input);
187571
187573 static hugeint_t FromBlob(const_data_ptr_t input);
187575 static void ToBlob(hugeint_t input, data_ptr_t output);
187576
187578 static string ToString(hugeint_t input) {
187579 char buff[STRING_SIZE];
187580 ToString(input, buff);
187581 return string(buff, STRING_SIZE);
187582 }
187583
187584 static hugeint_t FromString(const string &str) {
187585 hugeint_t result;
187586 FromString(str, result);
187587 return result;
187588 }
187589
187590protected:
187592 static hugeint_t Convert(const std::array<uint8_t, 16> &bytes);
187593};
187594
187596class UUID : public BaseUUID {
187597public:
187599 static hugeint_t GenerateRandomUUID(RandomEngine &engine);
187600 static hugeint_t GenerateRandomUUID();
187601};
187602
187603using UUIDv4 = UUID;
187604
187606class UUIDv7 : public BaseUUID {
187607public:
187609 static hugeint_t GenerateRandomUUID(RandomEngine &engine);
187610 static hugeint_t GenerateRandomUUID();
187611};
187612
187613}
187614
187615
187616
187617
187618
187619
187620
187621
187622
187623
187624
187625
187626
187627
187628namespace duckdb {
187629
187630struct dtime_t;
187631struct dtime_tz_t;
187632
187635class Time {
187636public:
187638 DUCKDB_API static dtime_t FromString(const string &str, bool strict = false, optional_ptr<int32_t> nanos = nullptr);
187639 DUCKDB_API static dtime_t FromCString(const char *buf, idx_t len, bool strict = false,
187640 optional_ptr<int32_t> nanos = nullptr);
187641 DUCKDB_API static bool TryConvertTime(const char *buf, idx_t len, idx_t &pos, dtime_t &result, bool strict = false,
187642 optional_ptr<int32_t> nanos = nullptr);
187643 DUCKDB_API static bool TryConvertTimeTZ(const char *buf, idx_t len, idx_t &pos, dtime_tz_t &result,
187644 bool &has_offset, bool strict = false,
187645 optional_ptr<int32_t> nanos = nullptr);
187646
187647 DUCKDB_API static bool TryConvertInterval(const char *buf, idx_t len, idx_t &pos, dtime_t &result,
187648 bool strict = false, optional_ptr<int32_t> nanos = nullptr);
187649
187651 DUCKDB_API static string ToString(dtime_t time);
187653 DUCKDB_API static string ToUTCOffset(int hour_offset, int minute_offset);
187654
187655 DUCKDB_API static dtime_t FromTime(int32_t hour, int32_t minute, int32_t second, int32_t microseconds = 0);
187656 DUCKDB_API
static int64_t ToNanoTime(int32_t hour, int32_t minute, int32_t second, int32_t nanoseconds = 0);
187657
187659 DUCKDB_API static dtime_t NormalizeTimeTZ(dtime_tz_t timetz);
187660
187662 DUCKDB_API static void Convert(dtime_t time, int32_t &out_hour, int32_t &out_min, int32_t &out_sec,
187663 int32_t &out_micros);
187664
187665 DUCKDB_API static string ConversionError(const string &str);
187666 DUCKDB_API static string ConversionError(string_t str);
187667
187668 DUCKDB_API static dtime_t FromTimeMs(int64_t time_ms);
187669 DUCKDB_API static dtime_t FromTimeNs(int64_t time_ns);
187670
187671 DUCKDB_API static bool IsValidTime(int32_t hour, int32_t minute, int32_t second, int32_t microseconds);
187672
187673private:
187674 static bool TryConvertInternal(const char *buf, idx_t len, idx_t &pos, dtime_t &result, bool strict,
187675 optional_ptr<int32_t> nanos = nullptr);
187676};
187677
187678}
187679
187680
187681
187682
187683
187684
187685
187686
187687
187688
187689
187690
187691
187692
187693
187694
187695
187696
187697
187698
187699
187700
187701
187702
187703
187704
187705
187706#include <type_traits>
187707
187708namespace duckdb {
187709
187710class ReadStream {
187711public:
187712
187713 virtual void ReadData(data_ptr_t buffer, idx_t read_size) = 0;
187714 virtual void ReadData(QueryContext context, data_ptr_t buffer, idx_t read_size) = 0;
187715
187716
187717
187718 template <class T>
187719 T Read() {
187720 return Read<T>(QueryContext());
187721 }
187722
187723 template <class T>
187724 T Read(QueryContext context) {
187725 static_assert(std::is_standard_layout<T>(), "Read element must be a standard layout data type");
187726 T value;
187727 ReadData(context, data_ptr_cast(&value), sizeof(T));
187728 return value;
187729 }
187730
187731 virtual ~ReadStream() {
187732 }
187733};
187734
187735}
187736
187737
187738
187739namespace duckdb {
187740class Allocator;
187741
187742class MemoryStream : public WriteStream, public ReadStream {
187743private:
187744 optional_ptr<Allocator> allocator;
187747 data_ptr_t data;
187748
187749public:
187750 static constexpr idx_t DEFAULT_INITIAL_CAPACITY = 512;
187751
187754 explicit MemoryStream(Allocator &allocator, idx_t capacity = DEFAULT_INITIAL_CAPACITY);
187755
187758 explicit MemoryStream(idx_t capacity = DEFAULT_INITIAL_CAPACITY);
187759
187763 explicit MemoryStream(data_ptr_t buffer, idx_t capacity);
187764
187766 MemoryStream(const MemoryStream &) = delete;
187767 MemoryStream &
operator=(
const MemoryStream &) =
delete;
187768
187769 MemoryStream(MemoryStream &&other) noexcept;
187770 MemoryStream &
operator=(MemoryStream &&other)
noexcept;
187771
187772 ~MemoryStream() override;
187773
187776 void WriteData(const_data_ptr_t buffer, idx_t write_size) override;
187777 void GrowCapacity(idx_t write_size);
187778
187781 void ReadData(data_ptr_t buffer, idx_t read_size) override;
187782 void ReadData(QueryContext context, data_ptr_t buffer, idx_t read_size) override;
187783
187785 void Rewind();
187786
187790 void Release();
187791
187793 data_ptr_t GetData() const;
187794
187796 idx_t GetPosition()
const;
187797
187799 idx_t GetCapacity()
const;
187800
187802 void SetPosition(idx_t position);
187803};
187804
187805}
187806
187807
187808
187809
187810
187811
187812
187813
187814
187815
187816
187817
187818
187819
187820
187821
187822
187823
187824
187825
187826
187827
187828namespace duckdb {
187829
187830struct FunctionDescription {
187832 vector<LogicalType> parameter_types;
187834 vector<string> parameter_names;
187836 string description;
187838 vector<string> examples;
187840 vector<string> categories;
187841};
187842
187843struct CreateFunctionInfo : public CreateInfo {
187844 explicit CreateFunctionInfo(CatalogType type, string schema = DEFAULT_SCHEMA);
187845
187847 string name;
187849 string alias_of;
187851 vector<FunctionDescription> descriptions;
187852
187853 DUCKDB_API void CopyFunctionProperties(CreateFunctionInfo &other) const;
187854};
187855
187856}
187857
187858
187859
187860namespace duckdb {
187861
187862struct CreateTableFunctionInfo : public CreateFunctionInfo {
187863 DUCKDB_API explicit CreateTableFunctionInfo(TableFunction function);
187864 DUCKDB_API explicit CreateTableFunctionInfo(TableFunctionSet set);
187865
187867 TableFunctionSet functions;
187868
187869public:
187870 DUCKDB_API unique_ptr<CreateInfo> Copy() const override;
187871 DUCKDB_API unique_ptr<AlterInfo> GetAlterInfo() const override;
187872};
187873
187874}
187875
187876
187877
187878
187879
187880
187881
187882
187883
187884
187885
187886
187887
187888
187889
187890
187891
187892
187893
187894
187895
187896
187897
187898
187899
187900
187901
187902
187903
187904
187905
187906
187907
187908
187909
187910
187911
187912
187913
187914
187915namespace duckdb {
187916
187917class QueryNode;
187918
187919struct CopyInfo : public ParseInfo {
187920public:
187921 static constexpr const ParseInfoType
TYPE = ParseInfoType::COPY_INFO;
187922
187923public:
187924 CopyInfo();
187925
187927 string catalog;
187929 string schema;
187931 string table;
187933 vector<string> select_list;
187935 bool is_from;
187939 bool is_format_auto_detected;
187941 unique_ptr<ParsedExpression> file_path_expression;
187943 string file_path;
187945 case_insensitive_map_t<unique_ptr<ParsedExpression>> parsed_options;
187947 case_insensitive_map_t<vector<Value>> options;
187949 unique_ptr<QueryNode> select_statement;
187950
187951public:
187952 string CopyOptionsToString() const;
187953
187954public:
187955 unique_ptr<CopyInfo> Copy() const;
187956 string ToString() const;
187957 string TablePartToString() const;
187958
187959 void Serialize(Serializer &serializer) const override;
187960 static unique_ptr<ParseInfo> Deserialize(Deserializer &deserializer);
187961};
187962
187963}
187964
187965
187966
187967
187968
187969
187970
187971
187972
187973
187974
187975
187976
187977
187978
187979namespace duckdb {
187980
187981enum class CopyToType :
uint8_t { COPY_TO_FILE, EXPORT_DATABASE };
187982
187983class CopyStatement : public SQLStatement {
187984public:
187985 static constexpr const StatementType
TYPE = StatementType::COPY_STATEMENT;
187986
187987public:
187988 CopyStatement();
187989
187990 unique_ptr<CopyInfo> info;
187991
187992 string ToString() const override;
187993
187994protected:
187995 CopyStatement(const CopyStatement &other);
187996
187997public:
187998 DUCKDB_API unique_ptr<SQLStatement> Copy() const override;
187999
188000private:
188001};
188002}
188003
188004
188005
188006
188007
188008
188009
188010
188011
188012
188013
188014
188015
188016namespace duckdb {
188017
188018enum class CopyOptionMode { WRITE_ONLY, READ_ONLY, READ_WRITE };
188019
188020}
188021
188022
188023namespace duckdb {
188024
188025struct BoundStatement;
188026struct CopyFunctionFileStatistics;
188027class Binder;
188028class ColumnDataCollection;
188029class ExecutionContext;
188030class PhysicalOperatorLogger;
188031
188032struct CopyFunctionInfo {
188033 virtual ~CopyFunctionInfo() = default;
188034
188035 template <class TARGET>
188036 TARGET &Cast() {
188037 DynamicCastCheck<TARGET>(this);
188038 return reinterpret_cast<TARGET &>(*this);
188039 }
188040 template <class TARGET>
188041 const TARGET &Cast() const {
188042 DynamicCastCheck<TARGET>(this);
188043 return reinterpret_cast<const TARGET &>(*this);
188044 }
188045};
188046
188047struct LocalFunctionData {
188048 virtual ~LocalFunctionData() = default;
188049
188050 template <class TARGET>
188051 TARGET &Cast() {
188052 DynamicCastCheck<TARGET>(this);
188053 return reinterpret_cast<TARGET &>(*this);
188054 }
188055 template <class TARGET>
188056 const TARGET &Cast() const {
188057 DynamicCastCheck<TARGET>(this);
188058 return reinterpret_cast<const TARGET &>(*this);
188059 }
188060};
188061
188062struct GlobalFunctionData {
188063 virtual ~GlobalFunctionData() = default;
188064
188065 template <class TARGET>
188066 TARGET &Cast() {
188067 DynamicCastCheck<TARGET>(this);
188068 return reinterpret_cast<TARGET &>(*this);
188069 }
188070 template <class TARGET>
188071 const TARGET &Cast() const {
188072 DynamicCastCheck<TARGET>(this);
188073 return reinterpret_cast<const TARGET &>(*this);
188074 }
188075};
188076
188077struct PreparedBatchData {
188078 virtual ~PreparedBatchData() = default;
188079
188080 template <class TARGET>
188081 TARGET &Cast() {
188082 DynamicCastCheck<TARGET>(this);
188083 return reinterpret_cast<TARGET &>(*this);
188084 }
188085 template <class TARGET>
188086 const TARGET &Cast() const {
188087 DynamicCastCheck<TARGET>(this);
188088 return reinterpret_cast<const TARGET &>(*this);
188089 }
188090};
188091
188092struct CopyFunctionBindInput {
188093 explicit CopyFunctionBindInput(const CopyInfo &info_p, shared_ptr<CopyFunctionInfo> function_info = nullptr)
188094 : info(info_p), function_info(std::move(function_info)) {
188095 }
188096
188097 const CopyInfo &info;
188098 shared_ptr<CopyFunctionInfo> function_info;
188099 string file_extension;
188100};
188101
188102struct CopyFromFunctionBindInput {
188103 explicit CopyFromFunctionBindInput(const CopyInfo &info_p, TableFunction &tf_p) : info(info_p), tf(tf_p) {
188104 }
188105
188106 const CopyInfo &info;
188107 TableFunction &tf;
188108};
188109
188110struct CopyToSelectInput {
188111 ClientContext &context;
188112 case_insensitive_map_t<vector<Value>> &options;
188113 vector<unique_ptr<Expression>> select_list;
188114 CopyToType copy_to_type;
188115};
188116
188117struct CopyOption {
188118 CopyOption();
188119 explicit CopyOption(LogicalType type_p, CopyOptionMode mode = CopyOptionMode::READ_WRITE);
188120
188121 LogicalType type;
188122 CopyOptionMode mode;
188123};
188124
188125struct CopyOptionsInput {
188126 explicit CopyOptionsInput(case_insensitive_map_t<CopyOption> &options) : options(options) {
188127 }
188128
188129 case_insensitive_map_t<CopyOption> &options;
188130};
188131
188132enum class CopyFunctionExecutionMode { REGULAR_COPY_TO_FILE, PARALLEL_COPY_TO_FILE, BATCH_COPY_TO_FILE };
188133
188134typedef BoundStatement (*copy_to_plan_t)(Binder &binder, CopyStatement &stmt);
188135typedef void (*copy_options_t)(ClientContext &context, CopyOptionsInput &input);
188136typedef unique_ptr<FunctionData> (*copy_to_bind_t)(ClientContext &context, CopyFunctionBindInput &input,
188137 const vector<string> &names, const vector<LogicalType> &sql_types);
188138typedef unique_ptr<LocalFunctionData> (*copy_to_initialize_local_t)(ExecutionContext &context, FunctionData &bind_data);
188139typedef unique_ptr<GlobalFunctionData> (*copy_to_initialize_global_t)(ClientContext &context, FunctionData &bind_data,
188140 const string &file_path);
188141typedef void (*copy_to_sink_t)(ExecutionContext &context, FunctionData &bind_data, GlobalFunctionData &gstate,
188142 LocalFunctionData &lstate, DataChunk &input);
188143typedef void (*copy_to_combine_t)(ExecutionContext &context, FunctionData &bind_data, GlobalFunctionData &gstate,
188144 LocalFunctionData &lstate);
188145typedef void (*copy_to_finalize_t)(ClientContext &context, FunctionData &bind_data, GlobalFunctionData &gstate);
188146
188147typedef void (*copy_to_serialize_t)(Serializer &serializer, const FunctionData &bind_data,
188148 const CopyFunction &function);
188149
188150typedef unique_ptr<FunctionData> (*copy_to_deserialize_t)(Deserializer &deserializer, CopyFunction &function);
188151
188152typedef unique_ptr<FunctionData> (*copy_from_bind_t)(ClientContext &context, CopyFromFunctionBindInput &info,
188153 vector<string> &expected_names,
188154 vector<LogicalType> &expected_types);
188155typedef CopyFunctionExecutionMode (*copy_to_execution_mode_t)(bool preserve_insertion_order, bool supports_batch_index);
188156
188157typedef unique_ptr<PreparedBatchData> (*copy_prepare_batch_t)(ClientContext &context, FunctionData &bind_data,
188158 GlobalFunctionData &gstate,
188159 unique_ptr<ColumnDataCollection> collection);
188160typedef void (*copy_flush_batch_t)(ClientContext &context, FunctionData &bind_data, GlobalFunctionData &gstate,
188161 PreparedBatchData &batch);
188162typedef idx_t (*copy_desired_batch_size_t)(ClientContext &context, FunctionData &bind_data);
188163
188164typedef bool (*copy_rotate_files_t)(FunctionData &bind_data, const optional_idx &file_size_bytes);
188165
188166typedef bool (*copy_rotate_next_file_t)(GlobalFunctionData &gstate, FunctionData &bind_data,
188167 const optional_idx &file_size_bytes);
188168
188169typedef void (*copy_to_get_written_statistics_t)(ClientContext &context, FunctionData &bind_data,
188170 GlobalFunctionData &gstate, CopyFunctionFileStatistics &statistics);
188171
188172typedef vector<unique_ptr<Expression>> (*copy_to_select_t)(CopyToSelectInput &input);
188173
188174typedef void (*copy_to_initialize_operator_t)(GlobalFunctionData &gstate, const PhysicalOperator &op);
188175
188176enum class CopyFunctionReturnType :
uint8_t {
188177 CHANGED_ROWS = 0,
188178 CHANGED_ROWS_AND_FILE_LIST = 1,
188179 WRITTEN_FILE_STATISTICS = 2
188180};
188181vector<string> GetCopyFunctionReturnNames(CopyFunctionReturnType return_type);
188183
188184struct CopyFunctionFileStatistics {
188185 idx_t row_count = 0;
188186 idx_t file_size_bytes = 0;
188187 Value footer_size_bytes;
188188
188189 case_insensitive_map_t<case_insensitive_map_t<Value>> column_statistics;
188190};
188191
188192class CopyFunction : public Function {
188193public:
188194 explicit CopyFunction(const string &name);
188195
188197 copy_to_plan_t plan;
188198 copy_to_select_t copy_to_select;
188199 copy_to_bind_t copy_to_bind;
188200 copy_options_t copy_options;
188201 copy_to_initialize_local_t copy_to_initialize_local;
188202 copy_to_initialize_global_t copy_to_initialize_global;
188203 copy_to_get_written_statistics_t copy_to_get_written_statistics;
188204 copy_to_sink_t copy_to_sink;
188205 copy_to_combine_t copy_to_combine;
188206 copy_to_finalize_t copy_to_finalize;
188207 copy_to_execution_mode_t execution_mode;
188208 copy_to_initialize_operator_t initialize_operator;
188209
188210 copy_prepare_batch_t prepare_batch;
188211 copy_flush_batch_t flush_batch;
188212 copy_desired_batch_size_t desired_batch_size;
188213
188214 copy_rotate_files_t rotate_files;
188215 copy_rotate_next_file_t rotate_next_file;
188216
188219
188220 copy_from_bind_t copy_from_bind;
188221 TableFunction copy_from_function;
188222
188223 string extension;
188224
188226 shared_ptr<CopyFunctionInfo> function_info;
188227};
188228
188229}
188230
188231
188232namespace duckdb {
188233
188234struct CreateCopyFunctionInfo : public CreateInfo {
188235 DUCKDB_API explicit CreateCopyFunctionInfo(CopyFunction function);
188236
188238 string name;
188240 CopyFunction function;
188241
188242public:
188243 unique_ptr<CreateInfo> Copy() const override;
188244};
188245
188246}
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 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
static string ToString(uhugeint_t input)
Convert a uhugeint object to a string.
Definition duckdb.cpp:130182
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