diff --git a/CMakeLists.txt b/CMakeLists.txt index e6b2b45a4..cece6e18e 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -680,11 +680,13 @@ add_library(duckdb_java SHARED src/jni/refs.cpp src/jni/types.cpp src/jni/util.cpp + src/duckdb/tools/cpp/duckdb_cpp.cpp ${DUCKDB_SRC_FILES}) target_include_directories(duckdb_java PRIVATE ${JAVA_INCLUDE_PATH} ${JAVA_INCLUDE_PATH2} + src/duckdb/tools/cpp ${DUCKDB_INCLUDE_DIRS}) if(JEMALLOC_ENABLED) diff --git a/CMakeLists.txt.in b/CMakeLists.txt.in index ddbd6cce8..9527629df 100644 --- a/CMakeLists.txt.in +++ b/CMakeLists.txt.in @@ -159,11 +159,13 @@ add_library(duckdb_java SHARED src/jni/refs.cpp src/jni/types.cpp src/jni/util.cpp + src/duckdb/tools/cpp/duckdb_cpp.cpp ${DUCKDB_SRC_FILES}) target_include_directories(duckdb_java PRIVATE ${JAVA_INCLUDE_PATH} ${JAVA_INCLUDE_PATH2} + src/duckdb/tools/cpp ${DUCKDB_INCLUDE_DIRS}) if(JEMALLOC_ENABLED) diff --git a/data/asan/appender_asan_failure.patch b/data/asan/appender_asan_failure.patch index 1795be47a..246273227 100644 --- a/data/asan/appender_asan_failure.patch +++ b/data/asan/appender_asan_failure.patch @@ -1,16 +1,16 @@ diff --git a/src/jni/bindings_appender.cpp b/src/jni/bindings_appender.cpp -index be36ab82..f82a7a56 100644 +index bd82e3a3c..e320b43a8 100644 --- a/src/jni/bindings_appender.cpp +++ b/src/jni/bindings_appender.cpp -@@ -60,6 +60,11 @@ JNIEXPORT jint JNICALL Java_org_duckdb_DuckDBBindings_duckdb_1appender_1create_1 - duckdb_appender appender = nullptr; +@@ -172,6 +172,11 @@ JNIEXPORT jint JNICALL Java_org_duckdb_DuckDBBindings_duckdb_1appender_1create_1 + return CAPI_STATE_ERROR; + } - duckdb_state state = duckdb_appender_create_ext(conn, catalog_ptr, schema_ptr, table_ptr, &appender); -+ + // asan failure snippet + int *x = reinterpret_cast(malloc(10 * sizeof(int*))); + free(x); + x[5] = 42; ++ + jobject appender_ref_buf = env->NewDirectByteBuffer(holder.release(), 0); + set_out_param(env, out_appender, appender_ref_buf); - if (state == DuckDBSuccess) { - jobject appender_ref_buf = env->NewDirectByteBuffer(appender, 0); diff --git a/src/duckdb/src/include/duckdb/main/capi_v2/extension_api_v2.hpp b/src/duckdb/src/include/duckdb/main/capi_v2/extension_api_v2.hpp index 405f0bd0b..80741a7d5 100644 --- a/src/duckdb/src/include/duckdb/main/capi_v2/extension_api_v2.hpp +++ b/src/duckdb/src/include/duckdb/main/capi_v2/extension_api_v2.hpp @@ -1713,6 +1713,8 @@ typedef struct { DUCKDB_V2_ERROR(*duckdb_v2_connection_get_profiling_information) (duckdb_v2_connection_handle conn, const char *format, idx_t format_length, duckdb_v2_text_sink_fn sink, void *user_data, duckdb_v2_error_info_handle *err); + DUCKDB_V2_ERROR(*duckdb_v2_value_variant_to_value) + (duckdb_v2_value_handle value, duckdb_v2_value_handle *out_value, duckdb_v2_error_info_handle *err); } duckdb_ext_api_v2; //===--------------------------------------------------------------------===// @@ -2482,6 +2484,7 @@ inline duckdb_ext_api_v2 CreateAPIv2(void) { result.duckdb_v2_table_function_to_string_set = duckdb_v2_table_function_to_string_set; result.duckdb_v2_instance_open_shared = duckdb_v2_instance_open_shared; result.duckdb_v2_connection_get_profiling_information = duckdb_v2_connection_get_profiling_information; + result.duckdb_v2_value_variant_to_value = duckdb_v2_value_variant_to_value; return result; } diff --git a/src/duckdb/src/include/duckdb_extension_v2.h b/src/duckdb/src/include/duckdb_extension_v2.h index 39ee5458d..012074a33 100644 --- a/src/duckdb/src/include/duckdb_extension_v2.h +++ b/src/duckdb/src/include/duckdb_extension_v2.h @@ -1787,6 +1787,8 @@ typedef struct { DUCKDB_V2_ERROR(*duckdb_v2_connection_get_profiling_information) (duckdb_v2_connection_handle conn, const char *format, idx_t format_length, duckdb_v2_text_sink_fn sink, void *user_data, duckdb_v2_error_info_handle *err); + DUCKDB_V2_ERROR(*duckdb_v2_value_variant_to_value) + (duckdb_v2_value_handle value, duckdb_v2_value_handle *out_value, duckdb_v2_error_info_handle *err); #endif // capigen:end appended } duckdb_ext_api_v2; @@ -4066,6 +4068,9 @@ typedef struct { #if DUCKDB_V2_API_ALLOW_UNSTABLE #define duckdb_v2_connection_get_profiling_information duckdb_ext_api.duckdb_v2_connection_get_profiling_information #endif +#if DUCKDB_V2_API_ALLOW_UNSTABLE +#define duckdb_v2_value_variant_to_value duckdb_ext_api.duckdb_v2_value_variant_to_value +#endif // capigen:end appended #endif // DUCKDB_BUILD_STATIC_EXTENSION diff --git a/src/duckdb/src/include/duckdb_v2.h b/src/duckdb/src/include/duckdb_v2.h index 0ff4262d7..7f0330ad6 100644 --- a/src/duckdb/src/include/duckdb_v2.h +++ b/src/duckdb/src/include/duckdb_v2.h @@ -18990,6 +18990,31 @@ DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_value_get_child(duckdb_v2_value_handle va duckdb_v2_error_info_handle *err); #endif +#if DUCKDB_V2_API_ALLOW_UNSTABLE +/*! + * Returns the value that a VARIANT value holds, as a value of its own type. + * + * A VARIANT holds a value of any other type, e.g. a TINYINT, a VARCHAR or a LIST of STRUCTs, that is only known per + * value: this reads it back, with the type that it was stored with. The value is built with the content of the variant, + * so a stored list gives a LIST with its elements, and a stored object a STRUCT with its fields. The elements of a list + * that were stored with different types, which a LIST cannot hold, stay VARIANT values: a LIST of VARIANT. Convert + * those with this function in turn. A NULL VARIANT gives a NULL value. A value that is not a VARIANT returns + * ERROR_INPUT_INVALID. The inverse is value_cast to a VARIANT type, which factory_create_type_from_text gives. The + * returned value is caller-owned; destroy it via value_destroy. + * + * history: + * - unstable: v2.0.0 + * + * @param value The VARIANT value to convert. + * @param out_value Receives the owned value. + * @param err Optional. On failure, receives an opaque info handle the caller must destroy via error_info_destroy. + * @return DUCKDB_V2_ERROR + */ +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_value_variant_to_value(duckdb_v2_value_handle value, + duckdb_v2_value_handle *out_value, + duckdb_v2_error_info_handle *err); +#endif + #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! * Casts a value to a target type, using a factory. diff --git a/src/duckdb/src/main/capi/v2/capi_v2_value.cpp b/src/duckdb/src/main/capi/v2/capi_v2_value.cpp index 649703a1f..90270952e 100644 --- a/src/duckdb/src/main/capi/v2/capi_v2_value.cpp +++ b/src/duckdb/src/main/capi/v2/capi_v2_value.cpp @@ -7,6 +7,7 @@ #include "duckdb/common/types/interval.hpp" #include "duckdb/common/types/uuid.hpp" #include "duckdb/common/types/value.hpp" +#include "duckdb/function/scalar/variant_utils.hpp" #include @@ -919,6 +920,29 @@ DUCKDB_V2_ERROR duckdb_v2_value_get_child_count(duckdb_v2_value_handle value, id return WithErrorHandler(err, [&]() { *out_count = CompositeChildCount(*Convert(value)); }); } +DUCKDB_V2_ERROR duckdb_v2_value_variant_to_value(duckdb_v2_value_handle value, duckdb_v2_value_handle *out_value, + duckdb_v2_error_info_handle *err) { + DUCKDB_CHECK_ARG(value); + DUCKDB_CHECK_ARG(out_value); + *out_value = nullptr; + return WithErrorHandler(err, [&]() { + auto &v = *Convert(value); + if (v.type().id() != duckdb::LogicalTypeId::VARIANT) { + throw duckdb::InvalidInputException("duckdb_v2_value_variant_to_value expects a VARIANT value"); + } + if (v.IsNull()) { + *out_value = Emit(duckdb::Value()); + return; + } + duckdb::Vector vec(v.type()); + vec.SetValue(0, v); + duckdb::RecursiveUnifiedVectorFormat format; + duckdb::Vector::RecursiveToUnifiedFormat(vec, format); + duckdb::UnifiedVariantVectorData data(format); + *out_value = Emit(duckdb::VariantUtils::ConvertVariantToValue(data, 0, 0)); + }); +} + DUCKDB_V2_ERROR duckdb_v2_value_get_child(duckdb_v2_value_handle value, idx_t index, duckdb_v2_value_handle *out_child, duckdb_v2_error_info_handle *err) { DUCKDB_CHECK_ARG(value); diff --git a/src/duckdb/tools/cpp/duckdb_cpp.cpp b/src/duckdb/tools/cpp/duckdb_cpp.cpp new file mode 100644 index 000000000..656c519be --- /dev/null +++ b/src/duckdb/tools/cpp/duckdb_cpp.cpp @@ -0,0 +1,7723 @@ +// Include the C++ API header (which includes the C API header) +#include "duckdb_cpp.hpp" + +#include +#include +#include +#include + +// The V2 extension header. By default, (client library, or extension statically linked into DuckDB) this library binds +// duckdb_v2_* symbols at link time and only needs the header for the loader-interface types of the extension +// entrypoint. The loadable flavor (DUCKDB_CPP_API_LOADABLE) instead routes every call through the extension vtable +// populated by the entrypoint, so a dynamically loaded extension carries no undefined engine symbols. Users of the +// C++ API never include this header. +#if !defined(DUCKDB_CPP_API_LOADABLE) && !defined(DUCKDB_BUILD_STATIC_EXTENSION) +#define DUCKDB_BUILD_STATIC_EXTENSION +#endif +// The parts of the C++ API marked "Unstable API" wrap the not yet stabilized part of the C API. +#ifndef DUCKDB_V2_API_ALLOW_UNSTABLE +#define DUCKDB_V2_API_ALLOW_UNSTABLE 1 +#endif +#include "duckdb_extension_v2.h" + +// The vtable global the redirects reference. It is *defined* by the extension's entrypoint, which is what populates it, +// so this archive only declares it. Outside the loadable flavor nothing references it and the declaration is inert. +// NOLINTNEXTLINE(cppcoreguidelines-avoid-non-const-global-variables) +DUCKDB_EXTENSION_EXTERN + +#include + +namespace duckdb { +namespace cxx { + +//---------------------------------------------------------------------------------------------------------------------- +// Internal Implementation Details +//---------------------------------------------------------------------------------------------------------------------- + +namespace detail { + +// Map each C++ wrapper to its underlying C-API handle type. Declared here in the .cpp (not the header). +// This makes handle types stay private to the implementation and consumed by Handle::handle(). + +template <> +struct HandleTraits { + using handle = duckdb_v2_option_handle; +}; +template <> +struct HandleTraits { + using handle = duckdb_v2_context_handle; +}; +template <> +struct HandleTraits { + using handle = duckdb_v2_factory_handle; +}; +template <> +struct HandleTraits { + using handle = duckdb_v2_custom_option_handle; +}; +template <> +struct HandleTraits { + using handle = duckdb_v2_config_handle; +}; +template <> +struct HandleTraits { + using handle = duckdb_v2_extension_handle; +}; +template <> +struct HandleTraits { + using handle = duckdb_v2_connection_handle; +}; +template <> +struct HandleTraits { + using handle = duckdb_v2_sql_statement_handle; +}; +template <> +struct HandleTraits { + using handle = duckdb_v2_statement_iterator_handle; +}; +template <> +struct HandleTraits { + using handle = duckdb_v2_prepared_statement_handle; +}; +template <> +struct HandleTraits { + using handle = duckdb_v2_schema_handle; +}; +template <> +struct HandleTraits { + using handle = duckdb_v2_environment_handle; +}; +template <> +struct HandleTraits { + using handle = duckdb_v2_instance_handle; +}; +template <> +struct HandleTraits { + using handle = duckdb_v2_logical_type_handle; +}; +template <> +struct HandleTraits { + using handle = duckdb_v2_value_handle; +}; +template <> +struct HandleTraits { + using handle = duckdb_v2_vector_handle; +}; +template <> +struct HandleTraits { + using handle = duckdb_v2_arena_handle; +}; +template <> +struct HandleTraits { + using handle = duckdb_v2_data_chunk_handle; +}; +template <> +struct HandleTraits { + using handle = duckdb_v2_expression_handle; +}; +template <> +struct HandleTraits { + using handle = duckdb_v2_column_data_collection_handle; +}; +template <> +struct HandleTraits { + using handle = duckdb_v2_column_data_collection_append_state_handle; +}; +template <> +struct HandleTraits { + using handle = duckdb_v2_column_data_collection_shared_scan_state_handle; +}; +template <> +struct HandleTraits { + using handle = duckdb_v2_column_data_collection_worker_scan_state_handle; +}; +template <> +struct HandleTraits { + using handle = duckdb_v2_result_handle; +}; +template <> +struct HandleTraits { + using handle = duckdb_v2_arrow_importer_handle; +}; +template <> +struct HandleTraits { + using handle = duckdb_v2_arrow_exporter_handle; +}; +template <> +struct HandleTraits { + using handle = duckdb_v2_arrow_result_handle; +}; +template <> +struct HandleTraits { + using handle = duckdb_v2_function_signature_handle; +}; +template <> +struct HandleTraits { + using handle = duckdb_v2_function_docs_handle; +}; +template <> +struct HandleTraits { + using handle = duckdb_v2_scalar_function_handle; +}; +template <> +struct HandleTraits { + using handle = duckdb_v2_aggregate_function_handle; +}; +template <> +struct HandleTraits { + using handle = duckdb_v2_table_function_handle; +}; +template <> +struct HandleTraits { + using handle = duckdb_v2_copy_function_handle; +}; +template <> +struct HandleTraits { + using handle = duckdb_v2_multi_file_function_handle; +}; +template <> +struct HandleTraits { + using handle = duckdb_v2_custom_type_handle; +}; +template <> +struct HandleTraits { + using handle = duckdb_v2_macro_function_handle; +}; +template <> +struct HandleTraits { + using handle = duckdb_v2_log_sink_handle; +}; +template <> +struct HandleTraits { + using handle = duckdb_v2_pragma_function_handle; +}; +template <> +struct HandleTraits { + using handle = duckdb_v2_cast_function_handle; +}; +template <> +struct HandleTraits { + using handle = duckdb_v2_replacement_scan_handle; +}; +template <> +struct HandleTraits { + using handle = duckdb_v2_qname_handle; +}; +template <> +struct HandleTraits { + using handle = duckdb_v2_table_description_handle; +}; +template <> +struct HandleTraits { + using handle = duckdb_v2_column_description_handle; +}; +template <> +struct HandleTraits { + using handle = duckdb_v2_query_metrics_handle; +}; +template <> +struct HandleTraits { + using handle = duckdb_v2_query_metrics_node_handle; +}; +template <> +struct HandleTraits { + using handle = duckdb_v2_file_system_handle; +}; +template <> +struct HandleTraits { + using handle = duckdb_v2_file_handle; +}; +template <> +struct HandleTraits { + using handle = duckdb_v2_file_open_options_handle; +}; +template <> +struct HandleTraits { + using handle = duckdb_v2_stats_handle; +}; + +} // namespace detail + +//---------------------------------------------------------------------------------------------------------------------- +// Exceptions +//---------------------------------------------------------------------------------------------------------------------- + +InvalidInputException::InvalidInputException(const std::string &message, std::string raw_message) + : Exception(DUCKDB_V2_ERROR_INPUT_INVALID, message, std::move(raw_message)) { +} + +InterruptException::InterruptException(const std::string &message, std::string raw_message) + : Exception(DUCKDB_V2_ERROR_RUNTIME_INTERRUPT, message, std::move(raw_message)) { +} + +//---------------------------------------------------------------------------------------------------------------------- +// Error Handling Helpers +//---------------------------------------------------------------------------------------------------------------------- + +namespace { +// Perform a DuckDB C-API call, setup an error info object, and throw an exception if it fails. +// This is used to simplify error handling in the C++ wrapper. +// Raise a failed call's error info as the matching exception type, consuming the info handle. +[[noreturn]] void ThrowAPIError(DUCKDB_V2_ERROR code, duckdb_v2_error_info_handle err) { + const char *message_view = nullptr; + idx_t message_view_length = 0; + const char *raw_view = nullptr; + idx_t raw_view_length = 0; + if (err) { + duckdb_v2_error_info_get_text(err, &message_view, &message_view_length); + duckdb_v2_error_info_get_raw_text(err, &raw_view, &raw_view_length); + } + std::string message = message_view ? std::string(message_view, message_view_length) : "unknown error"; + std::string raw = raw_view ? std::string(raw_view, raw_view_length) : ""; + duckdb_v2_error_info_destroy(&err); + // Map error codes with a dedicated exception type to that type so callers can catch it directly. + switch (code) { + case DUCKDB_V2_ERROR_INPUT_INVALID: + throw InvalidInputException(message, std::move(raw)); + case DUCKDB_V2_ERROR_RUNTIME_INTERRUPT: + throw InterruptException(message, std::move(raw)); + default: + throw Exception(code, message, std::move(raw)); + } +} + +template +auto CheckedAPICall(F &&func, ARGS &&...args) -> void { + duckdb_v2_error_info_handle err = nullptr; + const auto code = func(std::forward(args)..., &err); + if (code != DUCKDB_V2_ERROR_NONE) { + ThrowAPIError(code, err); + } +} + +// Borrows the factory of an instance, connection or context handle. +template +auto GetFactoryHandle(GETTER getter, void *source) -> duckdb_v2_factory_handle { + duckdb_v2_factory_handle factory = nullptr; + CheckedAPICall(getter, static_cast(source), &factory); + return factory; +} + +// Borrows the config of an instance, connection or context handle. +template +auto GetConfigHandle(GETTER getter, void *source) -> duckdb_v2_config_handle { + duckdb_v2_config_handle config = nullptr; + CheckedAPICall(getter, static_cast(source), &config); + return config; +} + +// Borrow a string as a length-delimited view for the C API. +auto ToStr(const std::string &s) -> std::string_view { + return s; +} +auto ToStr(std::string_view s) -> std::string_view { + return s; +} +// Borrow a storage token's bytes. Covers varchar_t through its blob_t base. +auto ToStr(const blob_t &bytes) -> std::string_view { + return std::string_view(bytes.data(), bytes.size()); +} + +// Borrows strings as the C API's parallel pointer and length arrays; both are NULL when empty. +class StringArrays { +public: + explicit StringArrays(size_t capacity) + : string_ptrs(capacity ? std::make_unique(capacity) : nullptr), + string_lengths(capacity ? std::make_unique(capacity) : nullptr) { + } + + void Push(std::string_view str) { + string_ptrs[count] = str.data(); + string_lengths[count] = str.size(); + count++; + } + auto ptrs() const -> const char *const * { + return string_ptrs.get(); + } + auto lengths() const -> const idx_t * { + return string_lengths.get(); + } + auto size() const -> idx_t { + return count; + } + +private: + std::unique_ptr string_ptrs; + std::unique_ptr string_lengths; + idx_t count = 0; +}; + +// The 128-bit mirrors carry the same halves as their C counterparts, converted +// field-wise rather than by reinterpretation so the compiler checks them. +auto ToC(int128_t value) -> duckdb_v2_hugeint_t { + return duckdb_v2_hugeint_t {value.lower, value.upper}; +} +auto ToC(uint128_t value) -> duckdb_v2_uhugeint_t { + return duckdb_v2_uhugeint_t {value.lower, value.upper}; +} +auto FromC(duckdb_v2_hugeint_t value) -> int128_t { + return int128_t {value.lower, value.upper}; +} +auto FromC(duckdb_v2_uhugeint_t value) -> uint128_t { + return uint128_t {value.lower, value.upper}; +} +// View a borrowed C-API string as a std::string_view (NULL -> empty). +auto FromStr(const char *ptr, idx_t length) -> std::string_view { + return ptr ? std::string_view(ptr, length) : std::string_view(); +} + +// Splits type parameters into the C API's parallel arrays; a TypeParam with an +// empty name crosses as a positional empty entry. The arrays borrow from +// `params`, so this must outlive the call it feeds. +class TypeParamArrays { +public: + explicit TypeParamArrays(const std::vector ¶ms) : name_arrays(params.size()) { + value_handles.reserve(params.size()); + for (const auto ¶m : params) { + name_arrays.Push(param.GetName()); + value_handles.push_back(param.GetValue().handle()); + } + } + + auto names() const -> const char *const * { + return name_arrays.ptrs(); + } + auto names_lengths() const -> const idx_t * { + return name_arrays.lengths(); + } + auto values() const -> const duckdb_v2_value_handle * { + return value_handles.empty() ? nullptr : value_handles.data(); + } + +private: + StringArrays name_arrays; + std::vector value_handles; +}; + +// Splits statement parameters into the C API's parallel arrays; a NamedParam +// with an empty name crosses as a positional empty entry. The arrays +// borrow from the parameters, so this must outlive the call it feeds. +class ParameterArrays { +public: + // A null pointer with a nonzero count produces no handles, so the C API reports the null argument. + ParameterArrays(const Value *parameters, idx_t parameter_count) : name_arrays(0) { + if (!parameters) { + return; + } + value_handles.reserve(parameter_count); + for (idx_t i = 0; i < parameter_count; i++) { + value_handles.push_back(parameters[i].handle()); + } + } + ParameterArrays(const NamedParam *parameters, idx_t parameter_count) + : name_arrays(parameters ? parameter_count : 0) { + if (!parameters) { + return; + } + value_handles.reserve(parameter_count); + for (idx_t i = 0; i < parameter_count; i++) { + name_arrays.Push(parameters[i].name); + value_handles.push_back(parameters[i].value.handle()); + } + } + + auto names() const -> const char *const * { + return name_arrays.ptrs(); + } + auto names_lengths() const -> const idx_t * { + return name_arrays.lengths(); + } + auto values() const -> const duckdb_v2_value_handle * { + return value_handles.empty() ? nullptr : value_handles.data(); + } + +private: + StringArrays name_arrays; + std::vector value_handles; +}; + +auto ExecuteStatementArrow(duckdb_v2_connection_handle conn, duckdb_v2_sql_statement_handle statement, + const ParameterArrays &split, idx_t parameter_count, ArrowFormat format) -> ArrowResult { + duckdb_v2_arrow_result_handle result = nullptr; + CheckedAPICall(duckdb_v2_statement_execute_arrow, conn, statement, split.names(), split.names_lengths(), + split.values(), parameter_count, format.batch_size, &result); + return detail::HandleFactory::Make(result); +} + +auto ExecutePreparedArrow(duckdb_v2_prepared_statement_handle prepared, const ParameterArrays &split, + idx_t parameter_count, ArrowFormat format) -> ArrowResult { + duckdb_v2_arrow_result_handle result = nullptr; + CheckedAPICall(duckdb_v2_prepared_statement_execute_arrow, prepared, split.names(), split.names_lengths(), + split.values(), parameter_count, format.batch_size, &result); + return detail::HandleFactory::Make(result); +} + +// Runs the C API's two-call text protocol: a null buffer reports the length, +// then a buffer with room for the terminator receives the text. The library +// never allocates, so there is nothing to free. +template +auto RenderText(F &&func, ARGS &&...args) -> std::string { + idx_t length = 0; + CheckedAPICall(func, args..., static_cast(nullptr), static_cast(0), &length); + std::string out; + out.resize(length); + // resize() guarantees length + 1 writable bytes, the last being the terminator. + CheckedAPICall(func, args..., &out[0], length + 1, &length); + return out; +} + +// Catch any exceptions and propagate them via the error info out-parameter, returning an appropriate error code. +template +auto WithExceptionGuard(duckdb_v2_error_info_handle *err, T callback) -> DUCKDB_V2_ERROR { + auto code = static_cast(DUCKDB_V2_ERROR_NONE); + auto text = std::string(); + + try { + // Invoke the callback + callback(); + } catch (const Exception &ex) { + code = static_cast(ex.GetCode()); + // An error raised by the engine carries its error-type prefix in what(); the engine adds that prefix again when + // it reports the error, so pass on the message without it. + text = ex.GetRawMessage().empty() ? ex.what() : ex.GetRawMessage(); + } catch (const std::exception &ex) { + code = DUCKDB_V2_ERROR_API; + text = ex.what(); + } catch (...) { + code = DUCKDB_V2_ERROR_API; + text = "An unknown error occurred."; + } + + // Pass up to the caller via the out-parameter if they provided one; otherwise swallow. + if (err && *err) { + duckdb_v2_error_info_set_code(*err, code); + auto text_str = ToStr(text); + duckdb_v2_error_info_set_text(*err, text_str.data(), text_str.size()); + } + + return code; +} + +} // namespace + +//---------------------------------------------------------------------------------------------------------------------- +// Free Functions +//---------------------------------------------------------------------------------------------------------------------- + +auto LibraryVersion() -> std::string { + const char *version = nullptr; + idx_t version_length = 0; + CheckedAPICall(duckdb_v2_library_version, &version, &version_length); + return std::string(version, version_length); +} + +auto RenderQuotedIdentifier(std::string_view name) -> std::string { + std::string_view name_str(name.data(), name.size()); + return RenderText(duckdb_v2_identifier_render_quoted, name_str.data(), name_str.size()); +} + +//--------------------------------------------------------------------------- +// Environment +//--------------------------------------------------------------------------- + +Environment::Environment() { + duckdb_v2_environment_handle _h = nullptr; + CheckedAPICall(duckdb_v2_environment_create, &_h); + impl = _h; +} + +Environment::~Environment() { + auto _h = handle(); + // Refused while instances are alive, which leaves the environment leaked rather than throwing from a destructor. + duckdb_v2_environment_destroy(&_h); +} + +auto Environment::Default() -> Environment & { + // Deliberately never destroyed, so it outlives every instance. + static auto *env = new Environment(); + return *env; +} + +auto Environment::GetInstanceCount() const -> size_t { + idx_t count = 0; + CheckedAPICall(duckdb_v2_environment_get_instance_count, handle(), &count); + return static_cast(count); +} + +namespace { + +auto CreateInstanceHandle(Environment &env, const std::vector> &options) -> void * { + StringArrays names(options.size()); + StringArrays values(options.size()); + for (auto &[name, value] : options) { + names.Push(name); + values.Push(value); + } + duckdb_v2_instance_handle instance = nullptr; + CheckedAPICall(duckdb_v2_instance_create_with_options, env.handle(), names.ptrs(), names.lengths(), values.ptrs(), + values.lengths(), static_cast(options.size()), &instance); + return instance; +} + +auto BoolText(bool value) -> std::string { + return value ? "true" : "false"; +} + +} // namespace + +Instance::Instance() : Instance(Environment::Default()) { +} + +auto Instance::StartupOptionPairs(const StartupOptions &options) -> std::vector> { + std::vector> result; + if (options.allow_community_extensions) { + result.emplace_back("allow_community_extensions", BoolText(*options.allow_community_extensions)); + } + if (options.allow_unsigned_extensions) { + result.emplace_back("allow_unsigned_extensions", BoolText(*options.allow_unsigned_extensions)); + } + if (options.allow_unredacted_secrets) { + result.emplace_back("allow_unredacted_secrets", BoolText(*options.allow_unredacted_secrets)); + } + if (options.disable_database_invalidation) { + result.emplace_back("disable_database_invalidation", BoolText(*options.disable_database_invalidation)); + } + if (options.custom_user_agent) { + result.emplace_back("custom_user_agent", *options.custom_user_agent); + } + result.insert(result.end(), options.options.begin(), options.options.end()); + return result; +} + +Instance::Instance(const StartupOptions &options) : Instance(Environment::Default(), options) { +} + +Instance::Instance(const std::string &path, const StartupOptions &options) + : Instance(Environment::Default(), path, options) { +} + +Instance::Instance(Environment &env, const StartupOptions &options) + : Instance(CreateInstanceHandle(env, StartupOptionPairs(options))) { +} + +Instance::Instance(Environment &env, const std::string &path, const StartupOptions &options) : Instance(env, options) { + Attach(path, true); +} + +auto Instance::OpenShared(const std::string &path, const StartupOptions &options) -> Instance { + return OpenShared(Environment::Default(), path, options); +} + +auto Instance::OpenShared(Environment &env, const std::string &path, const StartupOptions &options) -> Instance { + return OpenShared(env, path, options, nullptr); +} + +auto Instance::OpenShared(const std::string &path, const StartupOptions &options, const InitCallback &init) + -> Instance { + return OpenShared(Environment::Default(), path, options, init); +} + +auto Instance::OpenShared(Environment &env, const std::string &path, const StartupOptions &options, + const InitCallback &init) -> Instance { + duckdb_v2_instance_init_callback_fn init_fn = nullptr; + // a copy, as the callback's user data is not const + InitCallback init_copy = init; + if (init_copy) { + init_fn = [](duckdb_v2_instance_handle created, void *user_data, duckdb_v2_error_info_handle *err) { + WithExceptionGuard(err, [&]() { + // borrowed: released rather than destroyed when the callback returns + Instance borrowed(static_cast(created)); + try { + (*static_cast(user_data))(borrowed); + } catch (...) { + borrowed.release(); + throw; + } + borrowed.release(); + }); + }; + } + auto pairs = StartupOptionPairs(options); + StringArrays names(pairs.size()); + StringArrays values(pairs.size()); + for (auto &[name, value] : pairs) { + names.Push(name); + values.Push(value); + } + auto path_str = ToStr(path); + duckdb_v2_instance_handle instance = nullptr; + CheckedAPICall(duckdb_v2_instance_open_shared, env.handle(), path_str.data(), path_str.size(), names.ptrs(), + names.lengths(), values.ptrs(), values.lengths(), static_cast(pairs.size()), init_fn, + init_fn ? static_cast(&init_copy) : nullptr, &instance); + return Instance(instance); +} + +//--------------------------------------------------------------------------- +// Custom Option +//--------------------------------------------------------------------------- + +namespace { + +// The callback table for one registered option: rides the C user_data slot so +// the trampoline can find it; the user's own slot (SetUserData) rides inside +// it. Owned by the registered option, freed at database teardown. +struct CustomOptionInfo { + CustomOption::UpdateCallback update_callback = nullptr; + detail::UserData user_data; + + CustomOptionInfo(CustomOption::UpdateCallback update_callback, detail::UserData user_data) + : update_callback(update_callback), user_data(std::move(user_data)) { + } +}; + +auto UpdateInfo(void *args) -> duckdb_v2_custom_option_update_info_handle { + return static_cast(args); +} + +auto GetCustomOptionInfo(duckdb_v2_custom_option_update_info_handle info) -> const CustomOptionInfo & { + void *user_data = nullptr; + CheckedAPICall(duckdb_v2_custom_option_update_get_user_data, info, &user_data); + return *static_cast(user_data); +} + +} // namespace + +CustomOption::CustomOption(void *impl) : detail::Handle(impl) { +} + +CustomOption::~CustomOption() { + auto _h = handle(); + duckdb_v2_custom_option_destroy(&_h); +} + +auto CustomOption::Create(Factory &factory) -> CustomOption { + duckdb_v2_custom_option_handle _h = nullptr; + CheckedAPICall(duckdb_v2_custom_option_create, factory.handle(), &_h); + return detail::HandleFactory::Make(_h); +} + +auto CustomOption::SetName(const std::string &name) & -> CustomOption & { + auto view = ToStr(name); + CheckedAPICall(duckdb_v2_custom_option_set_name, handle(), view.data(), view.size()); + return *this; +} + +auto CustomOption::SetType(const LogicalType &type) & -> CustomOption & { + CheckedAPICall(duckdb_v2_custom_option_set_type, handle(), type.handle()); + return *this; +} + +auto CustomOption::SetDefaultValue(const Value &value) & -> CustomOption & { + CheckedAPICall(duckdb_v2_custom_option_set_default_value, handle(), value.handle()); + return *this; +} + +auto CustomOption::SetDescription(std::string_view description) & -> CustomOption & { + auto view = ToStr(description); + CheckedAPICall(duckdb_v2_custom_option_set_description, handle(), view.data(), view.size()); + return *this; +} + +auto CustomOption::SetDefaultScope(SettingScope scope) & -> CustomOption & { + CheckedAPICall(duckdb_v2_custom_option_set_default_scope, handle(), static_cast(scope)); + return *this; +} + +auto CustomOption::SetSupportsScope(SettingScope scope, bool supported) & -> CustomOption & { + CheckedAPICall(duckdb_v2_custom_option_set_supports_scope, handle(), static_cast(scope), + supported); + return *this; +} + +auto CustomOption::SetUserDataInternal(void *data, void (*destructor)(void *)) -> void { + user_data = detail::UserData(data, destructor); +} + +auto CustomOption::SetUpdateCallback(UpdateCallback callback) & -> CustomOption & { + if (!callback) { + CheckedAPICall(duckdb_v2_custom_option_set_update_callback, handle(), nullptr); + update_callback = nullptr; + return *this; + } + + // The C-side callback is one shared trampoline; the user's callback is looked + // up through the info table riding the user_data slot (set by Register). + static auto trampoline = [](duckdb_v2_custom_option_update_info_handle info, duckdb_v2_context_handle context, + duckdb_v2_error_info_handle *err) { + WithExceptionGuard(err, [&]() { + const auto &option = GetCustomOptionInfo(info); + auto input = + detail::HandleFactory::Make(static_cast(info), static_cast(context)); + option.update_callback(input); + }); + }; + + CheckedAPICall(duckdb_v2_custom_option_set_update_callback, handle(), trampoline); + update_callback = callback; + return *this; +} + +auto CustomOption::PrepareRegistration() -> void { + // The callback table rides the C user_data slot so the trampoline can find + // it; the user's own data (SetUserData, moved out here) rides inside it. + auto info = std::unique_ptr(new CustomOptionInfo(update_callback, std::move(user_data))); + duckdb_v2_opaque opaque {info.get(), detail::TypedDelete, nullptr}; + CheckedAPICall(duckdb_v2_custom_option_set_user_data, handle(), &opaque); + // The option owns the table now. + info.release(); // NOLINT(bugprone-unused-return-value) +} + +void *CustomOption::UpdateInput::GetUserDataInternal() const { + auto ptr = GetCustomOptionInfo(UpdateInfo(args)).user_data.get(); + if (!ptr) { + throw InvalidInputException("no user data was set; call CustomOption::SetUserData before Register"); + } + return ptr; +} + +auto CustomOption::UpdateInput::GetValue() const -> Value { + duckdb_v2_value_handle value = nullptr; + CheckedAPICall(duckdb_v2_custom_option_update_get_value, UpdateInfo(args), &value); + return detail::HandleFactory::Make(value); +} + +auto CustomOption::UpdateInput::SetValue(const Value &value) -> void { + CheckedAPICall(duckdb_v2_custom_option_update_set_value, UpdateInfo(args), value.handle()); +} + +auto CustomOption::UpdateInput::GetScope() const -> SettingScope { + auto scope = DUCKDB_V2_SETTING_SCOPE_DEFAULT; + CheckedAPICall(duckdb_v2_custom_option_update_get_scope, UpdateInfo(args), &scope); + return static_cast(scope); +} + +auto CustomOption::UpdateInput::IsReset() const -> bool { + bool is_reset = false; + CheckedAPICall(duckdb_v2_custom_option_update_is_reset, UpdateInfo(args), &is_reset); + return is_reset; +} + +auto CustomOption::UpdateInput::GetContext() -> Context & { + return context; +} + +//--------------------------------------------------------------------------- +// Instance Option +//--------------------------------------------------------------------------- + +OptionDescription::OptionDescription(void *impl) : detail::Handle(impl) { +} + +auto OptionDescription::GetName() const -> std::string_view { + const char *name = nullptr; + idx_t name_length = 0; + CheckedAPICall(duckdb_v2_option_get_name, handle(), &name, &name_length); + return FromStr(name, name_length); +} + +auto OptionDescription::GetDefaultValue() const -> Value { + duckdb_v2_value_handle value = nullptr; + CheckedAPICall(duckdb_v2_option_get_default_value, handle(), &value); + return detail::HandleFactory::Make(value); +} + +auto OptionDescription::GetDescription() const -> std::string_view { + const char *description = nullptr; + idx_t description_length = 0; + CheckedAPICall(duckdb_v2_option_get_description, handle(), &description, &description_length); + return FromStr(description, description_length); +} + +auto OptionDescription::GetAliasCount() const -> size_t { + idx_t count = 0; + CheckedAPICall(duckdb_v2_option_get_alias_count, handle(), &count); + return static_cast(count); +} + +auto OptionDescription::GetAliasByIndex(size_t index) const -> std::string_view { + const char *alias = nullptr; + idx_t alias_length = 0; + CheckedAPICall(duckdb_v2_option_get_alias, handle(), static_cast(index), &alias, &alias_length); + return FromStr(alias, alias_length); +} + +static_assert(static_cast(SettingScope::DEFAULT) == DUCKDB_V2_SETTING_SCOPE_DEFAULT && + static_cast(SettingScope::GLOBAL) == DUCKDB_V2_SETTING_SCOPE_GLOBAL && + static_cast(SettingScope::SESSION) == DUCKDB_V2_SETTING_SCOPE_SESSION, + "SettingScope must mirror DUCKDB_V2_SETTING_SCOPE"); + +auto OptionDescription::SupportsScope(SettingScope scope) const -> bool { + bool supported = false; + CheckedAPICall(duckdb_v2_option_supports_scope, handle(), static_cast(scope), &supported); + return supported; +} + +auto OptionDescription::GetDefaultScope() const -> SettingScope { + DUCKDB_V2_SETTING_SCOPE scope = DUCKDB_V2_SETTING_SCOPE_DEFAULT; + CheckedAPICall(duckdb_v2_option_get_default_scope, handle(), &scope); + return static_cast(scope); +} + +OptionDescription::~OptionDescription() { + auto _h = handle(); + duckdb_v2_option_destroy(&_h); +} + +//--------------------------------------------------------------------------- +// Instance +//--------------------------------------------------------------------------- + +Instance::Instance(void *impl) + : detail::Handle(impl), + factory(detail::HandleFactory::Make( + GetFactoryHandle(duckdb_v2_instance_get_factory, impl))), + config(detail::HandleFactory::Make( + GetConfigHandle(duckdb_v2_instance_get_config, impl))) { +} + +Instance::~Instance() { + auto _h = handle(); + duckdb_v2_instance_destroy(&_h); +} + +auto Instance::Attach(const std::string &path, bool make_default) -> void { + auto path_str = ToStr(path); + CheckedAPICall(duckdb_v2_instance_attach, handle(), nullptr, 0, path_str.data(), path_str.size(), + static_cast(nullptr), make_default); +} + +auto Instance::Attach(const std::string &path, const std::string &name, + const std::unordered_map &options, bool make_default) -> void { + duckdb_v2_attach_options_handle attach_options = nullptr; + CheckedAPICall(duckdb_v2_attach_options_create, handle(), &attach_options); + try { + for (auto &entry : options) { + auto key_str = ToStr(entry.first); + auto setting_str = ToStr(entry.second); + CheckedAPICall(duckdb_v2_attach_options_set, attach_options, key_str.data(), key_str.size(), + setting_str.data(), setting_str.size()); + } + auto attach_name = ToStr(name); + auto path_str = ToStr(path); + CheckedAPICall(duckdb_v2_instance_attach, handle(), attach_name.data(), attach_name.size(), path_str.data(), + path_str.size(), attach_options, make_default); + } catch (...) { + duckdb_v2_attach_options_destroy(&attach_options); + throw; + } + duckdb_v2_attach_options_destroy(&attach_options); +} + +auto Instance::Detach(const std::string &name) -> void { + auto name_str = ToStr(name); + CheckedAPICall(duckdb_v2_instance_detach, handle(), name_str.data(), name_str.size()); +} + +auto Instance::SetDefault(const std::string &name) -> void { + auto name_str = ToStr(name); + CheckedAPICall(duckdb_v2_instance_set_default, handle(), name_str.data(), name_str.size()); +} + +auto Instance::Connect() -> Connection { + duckdb_v2_connection_handle conn = nullptr; + CheckedAPICall(duckdb_v2_connection_create, handle(), &conn); + return detail::HandleFactory::Make(conn, true); +} + +//--------------------------------------------------------------------------- +// Config +//--------------------------------------------------------------------------- + +Config::Config(void *impl) : detail::Handle(impl) { +} + +Config::~Config() { +} + +auto Config::GetOptionCount() const -> size_t { + idx_t count = 0; + CheckedAPICall(duckdb_v2_config_get_option_count, handle(), &count); + return static_cast(count); +} + +auto Config::DescribeOption(size_t index) const -> OptionDescription { + duckdb_v2_option_handle option = nullptr; + CheckedAPICall(duckdb_v2_config_get_option_by_index, handle(), static_cast(index), &option); + return detail::HandleFactory::Make(option); +} + +auto Config::DescribeOption(std::string_view name) const -> OptionDescription { + duckdb_v2_option_handle option = nullptr; + auto name_str = std::string_view(name.data(), name.size()); + CheckedAPICall(duckdb_v2_config_get_option_by_name, handle(), name_str.data(), name_str.size(), &option); + return detail::HandleFactory::Make(option); +} + +auto Config::TryGetOption(std::string_view name) const -> std::optional { + auto name_str = std::string_view(name.data(), name.size()); + duckdb_v2_value_handle value = nullptr; + DUCKDB_V2_SETTING_SCOPE scope = DUCKDB_V2_SETTING_SCOPE_DEFAULT; + duckdb_v2_error_info_handle err = nullptr; + const auto code = + duckdb_v2_config_get_option_value(handle(), name_str.data(), name_str.size(), &value, &scope, &err); + if (code == DUCKDB_V2_ERROR_INPUT_INVALID) { + // no setting goes by that name + duckdb_v2_error_info_destroy(&err); + return std::nullopt; + } + if (code != DUCKDB_V2_ERROR_NONE) { + ThrowAPIError(code, err); + } + return OptionValue {detail::HandleFactory::Make(value), static_cast(scope)}; +} + +auto Config::GetOption(std::string_view name) const -> OptionValue { + auto value = TryGetOption(name); + if (!value) { + throw InvalidInputException("unknown configuration option: " + std::string(name)); + } + return std::move(*value); +} + +auto Config::SetOption(std::string_view name, std::string_view value, SettingScope scope) -> void { + auto name_str = std::string_view(name.data(), name.size()); + auto setting_str = std::string_view(value.data(), value.size()); + CheckedAPICall(duckdb_v2_config_set_option_text, handle(), name_str.data(), name_str.size(), setting_str.data(), + setting_str.size(), static_cast(scope)); +} + +auto Config::operator[](std::string_view name) const -> OptionValue { + return GetOption(name); +} + +auto Config::SetOption(std::string_view name, const Value &value, SettingScope scope) -> void { + auto name_str = std::string_view(name.data(), name.size()); + CheckedAPICall(duckdb_v2_config_set_option_value, handle(), name_str.data(), name_str.size(), value.handle(), + static_cast(scope)); +} + +//--------------------------------------------------------------------------- +// Connection +//--------------------------------------------------------------------------- + +Connection::Connection(void *impl, bool owned) + : detail::Handle(impl), + factory(detail::HandleFactory::Make( + GetFactoryHandle(duckdb_v2_connection_get_factory, impl))), + config(detail::HandleFactory::Make( + GetConfigHandle(duckdb_v2_connection_get_config, impl))), + owned(owned) { +} + +Connection::~Connection() { + if (owned) { + auto _h = handle(); + duckdb_v2_connection_destroy(&_h); + } +} + +//---------------------------------------------------------------------------------------------------------------------- +// SQL statements +//---------------------------------------------------------------------------------------------------------------------- + +SqlStatement::SqlStatement(void *impl) : detail::Handle(impl) { +} + +SqlStatement::~SqlStatement() { + auto _h = handle(); + duckdb_v2_sql_statement_destroy(&_h); +} + +auto SqlStatement::GetStatementType() const -> StatementType { + DUCKDB_V2_STATEMENT_TYPE type = DUCKDB_V2_STATEMENT_TYPE_INVALID; + CheckedAPICall(duckdb_v2_sql_statement_get_type, handle(), &type); + return static_cast(type); +} + +auto SqlStatement::GetText() const -> std::string_view { + const char *text = nullptr; + idx_t text_length = 0; + CheckedAPICall(duckdb_v2_sql_statement_get_text, handle(), &text, &text_length); + return FromStr(text, text_length); +} + +auto SqlStatement::AddCollection(std::string_view name, const ColumnDataCollection &collection, + const std::vector &column_names) -> void { + auto name_str = ToStr(name); + StringArrays names(column_names.size()); + for (auto &column_name : column_names) { + names.Push(column_name); + } + CheckedAPICall(duckdb_v2_statement_add_collection, handle(), name_str.data(), name_str.size(), collection.handle(), + names.ptrs(), names.lengths(), names.size()); +} + +auto SqlStatement::GetParameterNames() const -> std::vector { + idx_t count = 0; + CheckedAPICall(duckdb_v2_sql_statement_get_parameter_count, handle(), &count); + std::vector names; + names.reserve(count); + for (idx_t i = 0; i < count; i++) { + const char *name = nullptr; + idx_t name_length = 0; + CheckedAPICall(duckdb_v2_sql_statement_get_parameter_name, handle(), i, &name, &name_length); + names.push_back(FromStr(name, name_length)); + } + return names; +} + +StatementIterator::StatementIterator(void *impl) : detail::Handle(impl) { +} + +StatementIterator::~StatementIterator() { + auto _h = handle(); + duckdb_v2_statement_iterator_destroy(&_h); +} + +auto StatementIterator::Next() -> SqlStatement { + duckdb_v2_sql_statement_handle statement = nullptr; + CheckedAPICall(duckdb_v2_statement_iterator_next, handle(), &statement); + // An empty handle marks exhaustion. + return detail::HandleFactory::Make(statement); +} + +auto Connection::ParseSQL(std::string_view sql, bool apply_invalidation_policy) -> StatementIterator { + duckdb_v2_statement_iterator_handle iterator = nullptr; + CheckedAPICall(duckdb_v2_parse_sql, handle(), sql.data(), sql.size(), apply_invalidation_policy, &iterator); + return detail::HandleFactory::Make(iterator); +} + +// TokenType mirrors DUCKDB_V2_TOKEN_TYPE numerically; every member is pinned. END_OF_INPUT has no C++ member: it +// is the C iterator's exhaustion marker, and the vector simply ends. +static_assert(static_cast(TokenType::INVALID) == DUCKDB_V2_TOKEN_TYPE_INVALID, + "TokenType must mirror DUCKDB_V2_TOKEN_TYPE"); +static_assert(static_cast(TokenType::KEYWORD) == DUCKDB_V2_TOKEN_TYPE_KEYWORD, + "TokenType must mirror DUCKDB_V2_TOKEN_TYPE"); +static_assert(static_cast(TokenType::IDENTIFIER) == DUCKDB_V2_TOKEN_TYPE_IDENTIFIER, + "TokenType must mirror DUCKDB_V2_TOKEN_TYPE"); +static_assert(static_cast(TokenType::STRING_LITERAL) == DUCKDB_V2_TOKEN_TYPE_STRING_LITERAL, + "TokenType must mirror DUCKDB_V2_TOKEN_TYPE"); +static_assert(static_cast(TokenType::NUMBER_LITERAL) == DUCKDB_V2_TOKEN_TYPE_NUMBER_LITERAL, + "TokenType must mirror DUCKDB_V2_TOKEN_TYPE"); +static_assert(static_cast(TokenType::OPERATOR) == DUCKDB_V2_TOKEN_TYPE_OPERATOR, + "TokenType must mirror DUCKDB_V2_TOKEN_TYPE"); +static_assert(static_cast(TokenType::COMMENT) == DUCKDB_V2_TOKEN_TYPE_COMMENT, + "TokenType must mirror DUCKDB_V2_TOKEN_TYPE"); +static_assert(static_cast(TokenType::TERMINATOR) == DUCKDB_V2_TOKEN_TYPE_TERMINATOR, + "TokenType must mirror DUCKDB_V2_TOKEN_TYPE"); + +auto Connection::Tokenize(std::string_view sql) const -> TokenList { + duckdb_v2_token_iterator_handle iterator = nullptr; + auto sql_str = ToStr(sql); + CheckedAPICall(duckdb_v2_tokenize_sql, handle(), sql_str.data(), sql_str.size(), &iterator); + TokenList list; + try { + while (true) { + auto type = DUCKDB_V2_TOKEN_TYPE_INVALID; + idx_t start = 0; + idx_t length = 0; + CheckedAPICall(duckdb_v2_token_iterator_next, iterator, &type, &start, &length); + if (type == DUCKDB_V2_TOKEN_TYPE_END_OF_INPUT) { + break; + } + list.tokens.push_back(Token {static_cast(type), start, length}); + } + CheckedAPICall(duckdb_v2_token_iterator_ends_unterminated, iterator, &list.ends_unterminated); + } catch (...) { + duckdb_v2_token_iterator_destroy(&iterator); + throw; + } + duckdb_v2_token_iterator_destroy(&iterator); + return list; +} + +auto Connection::Execute(const SqlStatement &statement, const Value *parameters, idx_t parameter_count) -> QueryResult { + // Borrowed, not consumed: pass the handle without releasing it, so the + // caller's SqlStatement keeps ownership and can be executed again. + ParameterArrays split(parameters, parameter_count); + duckdb_v2_result_handle result = nullptr; + CheckedAPICall(duckdb_v2_statement_execute, handle(), statement.handle(), split.names(), split.names_lengths(), + split.values(), parameter_count, &result); + return detail::HandleFactory::Make(result); +} + +auto Connection::Execute(const SqlStatement &statement, const std::vector ¶meters) -> QueryResult { + ParameterArrays split(parameters.data(), parameters.size()); + duckdb_v2_result_handle result = nullptr; + CheckedAPICall(duckdb_v2_statement_execute, handle(), statement.handle(), split.names(), split.names_lengths(), + split.values(), static_cast(parameters.size()), &result); + return detail::HandleFactory::Make(result); +} + +auto Connection::Execute(const SqlStatement &statement) -> QueryResult { + return Execute(statement, nullptr, 0); +} + +auto Connection::Execute(const std::string &sql) -> QueryResult { + auto statements = ParseSQL(sql); + auto statement = statements.Next(); + if (!statement || statements.Next()) { + throw InvalidInputException("Execute expects exactly one statement; use ParseSQL for multi-statement input"); + } + return Execute(statement); +} + +auto Connection::Execute(const SqlStatement &statement, const Value *parameters, idx_t parameter_count, + ArrowFormat format) -> ArrowResult { + // Borrowed, not consumed: pass the handle without releasing it, so the + // caller's SqlStatement keeps ownership and can be executed again. + return ExecuteStatementArrow(handle(), statement.handle(), ParameterArrays(parameters, parameter_count), + parameter_count, format); +} + +auto Connection::ExecuteArrowNamed(const SqlStatement &statement, const NamedParam *parameters, idx_t parameter_count, + ArrowFormat format) -> ArrowResult { + return ExecuteStatementArrow(handle(), statement.handle(), ParameterArrays(parameters, parameter_count), + parameter_count, format); +} + +auto Connection::Execute(const SqlStatement &statement, ArrowFormat format) -> ArrowResult { + return Execute(statement, nullptr, 0, format); +} + +//---------------------------------------------------------------------------------------------------------------------- +// Prepared statements +//---------------------------------------------------------------------------------------------------------------------- + +PreparedStatement::PreparedStatement(void *impl) : detail::Handle(impl) { +} + +PreparedStatement::~PreparedStatement() { + auto _h = handle(); + duckdb_v2_prepared_statement_destroy(&_h); +} + +auto Connection::Prepare(const SqlStatement &statement, bool require_cacheable) -> PreparedStatement { + // Borrowed, not consumed: the caller's SqlStatement keeps ownership and can be + // prepared or executed again. + duckdb_v2_prepared_statement_handle prepared = nullptr; + CheckedAPICall(duckdb_v2_prepared_statement_create, handle(), statement.handle(), require_cacheable, &prepared); + return detail::HandleFactory::Make(prepared); +} + +auto PreparedStatement::Execute(const Value *parameters, idx_t parameter_count) -> QueryResult { + ParameterArrays split(parameters, parameter_count); + duckdb_v2_result_handle result = nullptr; + CheckedAPICall(duckdb_v2_prepared_statement_execute, handle(), split.names(), split.names_lengths(), split.values(), + parameter_count, &result); + return detail::HandleFactory::Make(result); +} + +auto PreparedStatement::Execute(const std::vector ¶meters) -> QueryResult { + ParameterArrays split(parameters.data(), parameters.size()); + duckdb_v2_result_handle result = nullptr; + CheckedAPICall(duckdb_v2_prepared_statement_execute, handle(), split.names(), split.names_lengths(), split.values(), + static_cast(parameters.size()), &result); + return detail::HandleFactory::Make(result); +} + +auto PreparedStatement::Execute() -> QueryResult { + return Execute(nullptr, 0); +} + +auto PreparedStatement::Execute(const Value *parameters, idx_t parameter_count, ArrowFormat format) -> ArrowResult { + return ExecutePreparedArrow(handle(), ParameterArrays(parameters, parameter_count), parameter_count, format); +} + +auto PreparedStatement::ExecuteArrowNamed(const NamedParam *parameters, idx_t parameter_count, ArrowFormat format) + -> ArrowResult { + return ExecutePreparedArrow(handle(), ParameterArrays(parameters, parameter_count), parameter_count, format); +} + +auto PreparedStatement::Execute(ArrowFormat format) -> ArrowResult { + return Execute(nullptr, 0, format); +} + +auto PreparedStatement::ReusesPlan() const -> bool { + bool reuses = false; + CheckedAPICall(duckdb_v2_prepared_statement_reuses_plan, handle(), &reuses); + return reuses; +} + +auto Connection::Interrupt() -> void { + CheckedAPICall(duckdb_v2_connection_interrupt, handle()); +} + +auto Connection::GetQueryProgress() const -> Connection::QueryProgress { + QueryProgress progress {}; + CheckedAPICall(duckdb_v2_connection_progress_get, handle(), &progress.percentage, &progress.rows_processed, + &progress.total_rows_to_process); + return progress; +} + +//---------------------------------------------------------------------------------------------------------------------- +// Context +//---------------------------------------------------------------------------------------------------------------------- + +Factory::Factory(void *impl) : detail::Handle(impl) { +} + +Factory::~Factory() { +} + +Context::Context(void *impl) + : detail::Handle(impl), + factory(detail::HandleFactory::Make( + GetFactoryHandle(duckdb_v2_context_get_factory, impl))), + config(detail::HandleFactory::Make( + GetConfigHandle(duckdb_v2_context_get_config, impl))) { +} + +Context::~Context() { + // Context lifetime is managed by DuckDB, so we don't destroy the handle here +} + +//---------------------------------------------------------------------------------------------------------------------- +// Extension +//---------------------------------------------------------------------------------------------------------------------- + +Extension::Extension(void *impl) : detail::Handle(impl) { +} + +auto Connection::Register(ScalarFunction &scalar_function) -> void { + scalar_function.PrepareRegistration(); + CheckedAPICall(duckdb_v2_connection_register_scalar_function, handle(), scalar_function.handle()); +} + +auto Extension::Register(ScalarFunction &scalar_function) -> void { + scalar_function.PrepareRegistration(); + CheckedAPICall(duckdb_v2_extension_register_scalar_function, handle(), scalar_function.handle()); +} + +auto Connection::Register(AggregateFunction &aggregate_function) -> void { + aggregate_function.PrepareRegistration(); + CheckedAPICall(duckdb_v2_connection_register_aggregate_function, handle(), aggregate_function.handle()); +} + +auto Extension::Register(AggregateFunction &aggregate_function) -> void { + aggregate_function.PrepareRegistration(); + CheckedAPICall(duckdb_v2_extension_register_aggregate_function, handle(), aggregate_function.handle()); +} + +auto Connection::Register(TableFunction &table_function) -> void { + table_function.PrepareRegistration(); + CheckedAPICall(duckdb_v2_connection_register_table_function, handle(), table_function.handle()); +} + +auto Extension::Register(TableFunction &table_function) -> void { + table_function.PrepareRegistration(); + CheckedAPICall(duckdb_v2_extension_register_table_function, handle(), table_function.handle()); +} + +auto Connection::Register(MultiFileFunction &multi_file_function) -> void { + multi_file_function.PrepareRegistration(); + CheckedAPICall(duckdb_v2_connection_register_multi_file_function, handle(), multi_file_function.handle()); +} + +auto Extension::Register(MultiFileFunction &multi_file_function) -> void { + multi_file_function.PrepareRegistration(); + CheckedAPICall(duckdb_v2_extension_register_multi_file_function, handle(), multi_file_function.handle()); +} + +auto Connection::Register(CustomType &custom_type) -> void { + custom_type.PrepareRegistration(); + CheckedAPICall(duckdb_v2_connection_register_custom_type, handle(), custom_type.handle()); +} + +auto Extension::Register(CustomType &custom_type) -> void { + custom_type.PrepareRegistration(); + CheckedAPICall(duckdb_v2_extension_register_custom_type, handle(), custom_type.handle()); +} + +auto Connection::Register(CopyFunction ©_function) -> void { + copy_function.PrepareRegistration(); + CheckedAPICall(duckdb_v2_connection_register_copy_function, handle(), copy_function.handle()); +} + +auto Extension::Register(CopyFunction ©_function) -> void { + copy_function.PrepareRegistration(); + CheckedAPICall(duckdb_v2_extension_register_copy_function, handle(), copy_function.handle()); +} + +auto Connection::Register(CastFunction &cast_function) -> void { + cast_function.PrepareRegistration(); + CheckedAPICall(duckdb_v2_connection_register_cast_function, handle(), cast_function.handle()); +} + +auto Extension::Register(CastFunction &cast_function) -> void { + cast_function.PrepareRegistration(); + CheckedAPICall(duckdb_v2_extension_register_cast_function, handle(), cast_function.handle()); +} + +auto Connection::Register(PragmaFunction &pragma_function) -> void { + pragma_function.PrepareRegistration(); + CheckedAPICall(duckdb_v2_connection_register_pragma_function, handle(), pragma_function.handle()); +} + +auto Extension::Register(PragmaFunction &pragma_function) -> void { + pragma_function.PrepareRegistration(); + CheckedAPICall(duckdb_v2_extension_register_pragma_function, handle(), pragma_function.handle()); +} + +auto Extension::Register(MacroFunction ¯o_function) -> void { + CheckedAPICall(duckdb_v2_extension_register_macro_function, handle(), macro_function.handle()); +} + +auto Connection::Register(CustomOption &custom_option) -> void { + custom_option.PrepareRegistration(); + CheckedAPICall(duckdb_v2_connection_register_custom_option, handle(), custom_option.handle()); +} + +auto Extension::Register(CustomOption &custom_option) -> void { + custom_option.PrepareRegistration(); + CheckedAPICall(duckdb_v2_extension_register_custom_option, handle(), custom_option.handle()); +} + +auto Connection::Register(ReplacementScan &replacement_scan) -> void { + replacement_scan.PrepareRegistration(); + CheckedAPICall(duckdb_v2_connection_register_replacement_scan, handle(), replacement_scan.handle()); +} + +auto Extension::Register(ReplacementScan &replacement_scan) -> void { + replacement_scan.PrepareRegistration(); + CheckedAPICall(duckdb_v2_extension_register_replacement_scan, handle(), replacement_scan.handle()); +} + +auto Instance::Register(ReplacementScan &replacement_scan) -> void { + replacement_scan.PrepareRegistration(); + CheckedAPICall(duckdb_v2_instance_register_replacement_scan, handle(), replacement_scan.handle()); +} + +auto Instance::Register(LogSink &log_sink) -> void { + log_sink.PrepareRegistration(); + CheckedAPICall(duckdb_v2_instance_register_log_sink, handle(), log_sink.handle()); +} + +auto Extension::Register(LogSink &log_sink) -> void { + log_sink.PrepareRegistration(); + CheckedAPICall(duckdb_v2_extension_register_log_sink, handle(), log_sink.handle()); +} + +Extension::~Extension() { + // The loader is owned by DuckDB for the duration of the load, so we don't destroy the handle here +} + +namespace detail { + +auto RunExtensionEntry(void (*body)(Extension &, Context &), void *extension, void *context, void *err) -> void { + auto *error_slot = static_cast(err); + // The guard is the only thing standing between a throwing extension body and unwinding through DuckDB's C frame. + WithExceptionGuard(error_slot, [&]() { + auto ext = HandleFactory::Make(extension); + auto ctx = HandleFactory::Make(context); + body(ext, ctx); + }); +} + +} // namespace detail + +auto Factory::ParseType(std::string_view text) const -> LogicalType { + duckdb_v2_logical_type_handle type = nullptr; + auto text_str = std::string_view(text.data(), text.size()); + CheckedAPICall(duckdb_v2_factory_create_type_from_text, handle(), text_str.data(), text_str.size(), &type); + return detail::HandleFactory::Make(type); +} + +auto Context::Log(LogLevel level, std::string_view message, std::string_view log_type) const -> void { + auto log_type_str = ToStr(log_type); + auto message_str = ToStr(message); + CheckedAPICall(duckdb_v2_context_log, handle(), static_cast(level), log_type_str.data(), + log_type_str.size(), message_str.data(), message_str.size()); +} + +auto Connection::Log(LogLevel level, std::string_view message, std::string_view log_type) const -> void { + auto log_type_str = ToStr(log_type); + auto message_str = ToStr(message); + CheckedAPICall(duckdb_v2_connection_log, handle(), static_cast(level), log_type_str.data(), + log_type_str.size(), message_str.data(), message_str.size()); +} + +auto Instance::Log(LogLevel level, std::string_view message, std::string_view log_type) const -> void { + auto log_type_str = ToStr(log_type); + auto message_str = ToStr(message); + CheckedAPICall(duckdb_v2_instance_log, handle(), static_cast(level), log_type_str.data(), + log_type_str.size(), message_str.data(), message_str.size()); +} + +auto Factory::CreateType(std::string_view name) const -> LogicalType { + return CreateType(name, {}); +} + +auto Factory::CreateType(std::string_view name, const std::vector ¶ms) const -> LogicalType { + return CreateType(QualifiedName::Create({std::string(name)}), params); +} + +auto Context::GetFileSystem() const -> FileSystem { + duckdb_v2_file_system_handle fs = nullptr; + CheckedAPICall(duckdb_v2_context_get_file_system, handle(), &fs); + return detail::HandleFactory::Make(fs); +} + +auto Connection::GetFileSystem() const -> FileSystem { + duckdb_v2_file_system_handle fs = nullptr; + CheckedAPICall(duckdb_v2_connection_get_file_system, handle(), &fs); + return detail::HandleFactory::Make(fs); +} + +auto Instance::GetFileSystem() const -> FileSystem { + duckdb_v2_file_system_handle fs = nullptr; + CheckedAPICall(duckdb_v2_instance_get_file_system, handle(), &fs); + return detail::HandleFactory::Make(fs); +} + +auto Factory::CreateType(const QualifiedName &name) const -> LogicalType { + return CreateType(name, {}); +} + +auto Factory::CreateType(const QualifiedName &name, const std::vector ¶ms) const -> LogicalType { + TypeParamArrays split(params); + duckdb_v2_logical_type_handle type = nullptr; + CheckedAPICall(duckdb_v2_factory_create_type_from_name, handle(), name.handle(), split.names(), + split.names_lengths(), split.values(), static_cast(params.size()), &type); + return detail::HandleFactory::Make(type); +} + +auto Factory::CreateType(LogicalTypeId id) const -> LogicalType { + return CreateType(id, {}); +} + +auto Factory::CreateType(LogicalTypeId id, const std::vector ¶ms) const -> LogicalType { + TypeParamArrays split(params); + duckdb_v2_logical_type_handle type = nullptr; + CheckedAPICall(duckdb_v2_factory_create_type_from_id, handle(), static_cast(id), + split.names(), split.names_lengths(), split.values(), static_cast(params.size()), &type); + return detail::HandleFactory::Make(type); +} + +//---------------------------------------------------------------------------------------------------------------------- +// Logical Type +//---------------------------------------------------------------------------------------------------------------------- + +LogicalType::LogicalType(void *impl) : detail::Handle(impl) { +} + +bool LogicalType::operator==(const LogicalType &other) const { + if (handle() == other.handle()) { + return true; // same handle means same logical type + } + bool result = false; + CheckedAPICall(duckdb_v2_logical_type_is_equal, handle(), other.handle(), &result); + return result; +} + +auto LogicalType::Copy() const -> LogicalType { + duckdb_v2_logical_type_handle copy = nullptr; + CheckedAPICall(duckdb_v2_logical_type_copy, handle(), ©); + return detail::HandleFactory::Make(copy); +} + +auto LogicalType::GetTypeId() const -> LogicalTypeId { + auto id = static_cast(0); + CheckedAPICall(duckdb_v2_logical_type_get_id, handle(), &id); + return static_cast(id); +} + +auto LogicalType::GetName() const -> std::string_view { + const char *name = nullptr; + idx_t name_length = 0; + CheckedAPICall(duckdb_v2_logical_type_get_name, handle(), &name, &name_length); + return FromStr(name, name_length); +} + +auto LogicalType::WithAlias(Factory &factory, std::string_view alias) const -> LogicalType { + duckdb_v2_logical_type_handle new_type = nullptr; + auto alias_name_str = ToStr(alias); + CheckedAPICall(duckdb_v2_factory_create_type_with_alias, factory.handle(), handle(), alias_name_str.data(), + alias_name_str.size(), &new_type); + return detail::HandleFactory::Make(new_type); +} + +LogicalType::~LogicalType() { + auto _h = handle(); + duckdb_v2_logical_type_destroy(&_h); +} + +// LogicalTypeId mirrors LOGICAL_TYPE_ID numerically; every member is pinned. +#define DUCKDB_CPP_ASSERT_TYPE_ID(member) \ + static_assert(static_cast(LogicalTypeId::member) == DUCKDB_V2_LOGICAL_TYPE_ID_##member, \ + "LogicalTypeId::" #member " must mirror DUCKDB_V2_LOGICAL_TYPE_ID_" #member) +DUCKDB_CPP_ASSERT_TYPE_ID(INVALID); +DUCKDB_CPP_ASSERT_TYPE_ID(SQLNULL); +DUCKDB_CPP_ASSERT_TYPE_ID(UNKNOWN); +DUCKDB_CPP_ASSERT_TYPE_ID(ANY); +DUCKDB_CPP_ASSERT_TYPE_ID(TYPE); +DUCKDB_CPP_ASSERT_TYPE_ID(BOOLEAN); +DUCKDB_CPP_ASSERT_TYPE_ID(TINYINT); +DUCKDB_CPP_ASSERT_TYPE_ID(SMALLINT); +DUCKDB_CPP_ASSERT_TYPE_ID(INTEGER); +DUCKDB_CPP_ASSERT_TYPE_ID(BIGINT); +DUCKDB_CPP_ASSERT_TYPE_ID(DATE); +DUCKDB_CPP_ASSERT_TYPE_ID(TIME); +DUCKDB_CPP_ASSERT_TYPE_ID(TIMESTAMP_SEC); +DUCKDB_CPP_ASSERT_TYPE_ID(TIMESTAMP_MS); +DUCKDB_CPP_ASSERT_TYPE_ID(TIMESTAMP); +DUCKDB_CPP_ASSERT_TYPE_ID(TIMESTAMP_NS); +DUCKDB_CPP_ASSERT_TYPE_ID(DECIMAL); +DUCKDB_CPP_ASSERT_TYPE_ID(FLOAT); +DUCKDB_CPP_ASSERT_TYPE_ID(DOUBLE); +DUCKDB_CPP_ASSERT_TYPE_ID(VARCHAR); +DUCKDB_CPP_ASSERT_TYPE_ID(BLOB); +DUCKDB_CPP_ASSERT_TYPE_ID(INTERVAL); +DUCKDB_CPP_ASSERT_TYPE_ID(UTINYINT); +DUCKDB_CPP_ASSERT_TYPE_ID(USMALLINT); +DUCKDB_CPP_ASSERT_TYPE_ID(UINTEGER); +DUCKDB_CPP_ASSERT_TYPE_ID(UBIGINT); +DUCKDB_CPP_ASSERT_TYPE_ID(TIMESTAMP_TZ); +DUCKDB_CPP_ASSERT_TYPE_ID(TIMESTAMP_TZ_NS); +DUCKDB_CPP_ASSERT_TYPE_ID(TIME_TZ); +DUCKDB_CPP_ASSERT_TYPE_ID(TIME_NS); +DUCKDB_CPP_ASSERT_TYPE_ID(BIT); +DUCKDB_CPP_ASSERT_TYPE_ID(BIGNUM); +DUCKDB_CPP_ASSERT_TYPE_ID(UHUGEINT); +DUCKDB_CPP_ASSERT_TYPE_ID(HUGEINT); +DUCKDB_CPP_ASSERT_TYPE_ID(UUID); +DUCKDB_CPP_ASSERT_TYPE_ID(GEOMETRY); +DUCKDB_CPP_ASSERT_TYPE_ID(STRUCT); +DUCKDB_CPP_ASSERT_TYPE_ID(LIST); +DUCKDB_CPP_ASSERT_TYPE_ID(MAP); +DUCKDB_CPP_ASSERT_TYPE_ID(ENUM); +DUCKDB_CPP_ASSERT_TYPE_ID(UNION); +DUCKDB_CPP_ASSERT_TYPE_ID(ARRAY); +DUCKDB_CPP_ASSERT_TYPE_ID(VARIANT); +DUCKDB_CPP_ASSERT_TYPE_ID(TUPLE); +#undef DUCKDB_CPP_ASSERT_TYPE_ID + +auto LogicalType::ToText() const -> std::string { + return RenderText(duckdb_v2_logical_type_to_text, handle()); +} + +auto LogicalType::GetParamCount() const -> idx_t { + idx_t count = 0; + CheckedAPICall(duckdb_v2_logical_type_get_param_count, handle(), &count); + return count; +} + +auto LogicalType::GetParam(idx_t index) const -> TypeParam { + const char *name = nullptr; + idx_t name_length = 0; + duckdb_v2_value_handle value = nullptr; + CheckedAPICall(duckdb_v2_logical_type_get_param, handle(), index, &name, &name_length, &value); + return TypeParam {std::string(FromStr(name, name_length)), detail::HandleFactory::Make(value)}; +} + +// A DECIMAL's width and scale parameters are UINTEGER values; engines before the width cap was lifted hand over +// UTINYINT. +static auto ReadDecimalParam(const Value ¶m) -> uint32_t { + if (param.GetLogicalType().GetTypeId() == LogicalTypeId::UTINYINT) { + return param.Get(); + } + return param.Get(); +} + +auto LogicalType::GetDecimalWidth() const -> uint32_t { + return ReadDecimalParam(GetParam(0).GetValue()); +} + +auto LogicalType::GetDecimalScale() const -> uint32_t { + return ReadDecimalParam(GetParam(1).GetValue()); +} + +auto LogicalType::GetEnumSize() const -> idx_t { + return GetParamCount(); +} + +auto LogicalType::GetEnumValue(idx_t index) const -> std::string { + // Owned string: the backing Value is owned per call, a view would dangle. + return std::string(GetParam(index).GetValue().Get()); +} + +auto LogicalType::GetListChildType() const -> LogicalType { + return GetParam(0).GetValue().Get(); +} + +auto LogicalType::GetArrayChildType() const -> LogicalType { + return GetParam(0).GetValue().Get(); +} + +auto LogicalType::GetArraySize() const -> idx_t { + return GetParam(1).GetValue().Get(); +} + +auto LogicalType::GetMapKeyType() const -> LogicalType { + return GetParam(0).GetValue().Get(); +} + +auto LogicalType::GetMapValueType() const -> LogicalType { + return GetParam(1).GetValue().Get(); +} + +auto LogicalType::GetStructChildCount() const -> idx_t { + return GetParamCount(); +} + +auto LogicalType::GetStructChildName(idx_t index) const -> std::string { + return GetParam(index).GetName(); +} + +auto LogicalType::GetStructChildType(idx_t index) const -> LogicalType { + return GetParam(index).GetValue().Get(); +} + +auto LogicalType::GetUnionMemberCount() const -> idx_t { + return GetParamCount(); +} + +auto LogicalType::GetUnionMemberName(idx_t index) const -> std::string { + return GetParam(index).GetName(); +} + +auto LogicalType::GetUnionMemberType(idx_t index) const -> LogicalType { + return GetParam(index).GetValue().Get(); +} + +auto LogicalType::GetDecimalInternalTypeId() const -> LogicalTypeId { + // The committed DECIMAL storage tiers: width <= 4 int16, <= 9 int32, + // <= 18 int64, <= 38 int128, wider BIGNUM. Pinned against the engine in [capi_v2]. + auto width = GetDecimalWidth(); + if (width <= 4) { + return LogicalTypeId::SMALLINT; + } + if (width <= 9) { + return LogicalTypeId::INTEGER; + } + if (width <= 18) { + return LogicalTypeId::BIGINT; + } + if (width <= 38) { + return LogicalTypeId::HUGEINT; + } + return LogicalTypeId::BIGNUM; +} + +auto LogicalType::GetEnumInternalTypeId() const -> LogicalTypeId { + // The committed ENUM storage tiers: size <= 255 uint8, <= 65535 uint16, + // else uint32. Pinned against the engine in [capi_v2]. + auto size = GetEnumSize(); + if (size <= 255) { + return LogicalTypeId::UTINYINT; + } + if (size <= 65535) { + return LogicalTypeId::USMALLINT; + } + return LogicalTypeId::UINTEGER; +} + +//---------------------------------------------------------------------------------------------------------------------- +// Schema +//---------------------------------------------------------------------------------------------------------------------- +Schema::Schema(void *impl) : detail::Handle(impl) { +} +Schema::~Schema() { + auto _h = handle(); + duckdb_v2_schema_destroy(&_h); +} +auto Schema::GetFieldCount() const -> idx_t { + idx_t count = 0; + CheckedAPICall(duckdb_v2_schema_get_count, handle(), &count); + return count; +} +auto Schema::GetFieldName(idx_t index) const -> std::string_view { + const char *name = nullptr; + idx_t name_length = 0; + duckdb_v2_logical_type_handle type = nullptr; // borrowed; unused here + CheckedAPICall(duckdb_v2_schema_get_field, handle(), index, &name, &name_length, &type); + return FromStr(name, name_length); +} +auto Schema::GetFieldType(idx_t index) const -> LogicalType { + const char *name = nullptr; + idx_t name_length = 0; + duckdb_v2_logical_type_handle borrowed = nullptr; + CheckedAPICall(duckdb_v2_schema_get_field, handle(), index, &name, &name_length, &borrowed); + // get_field borrows the type; copy it into an owned handle the wrapper manages. + duckdb_v2_logical_type_handle owned = nullptr; + CheckedAPICall(duckdb_v2_logical_type_copy, borrowed, &owned); + return detail::HandleFactory::Make(owned); +} + +auto Connection::Bind(const SqlStatement &statement) const -> Signature { + duckdb_v2_schema_handle out_schema = nullptr; + duckdb_v2_schema_handle out_parameters = nullptr; + CheckedAPICall(duckdb_v2_statement_bind, handle(), statement.handle(), &out_schema, &out_parameters); + return Signature {detail::HandleFactory::Make(out_schema), + detail::HandleFactory::Make(out_parameters)}; +} + +auto Connection::DescribeTable(const QualifiedName &name) const -> TableDescription { + duckdb_v2_table_description_handle _h = nullptr; + CheckedAPICall(duckdb_v2_connection_describe_table, handle(), name.handle(), &_h); + return detail::HandleFactory::Make(_h); +} + +auto Connection::EnableProfiling(bool enabled) -> void { + CheckedAPICall(duckdb_v2_connection_enable_profiling, handle(), enabled); +} + +auto Connection::GetQueryMetrics() const -> QueryMetrics { + duckdb_v2_query_metrics_handle _h = nullptr; + CheckedAPICall(duckdb_v2_connection_get_query_metrics, handle(), &_h); + return detail::HandleFactory::Make(_h); +} + +namespace { +// Collects the text a text sink delivers +void CollectText(const char *text, idx_t text_length, void *user_data, duckdb_v2_error_info_handle *err) { + WithExceptionGuard(err, [&] { + if (text && text_length) { + static_cast(user_data)->append(text, text_length); + } + }); +} +} // namespace + +auto Connection::GetProfilingInformation(std::string_view format) const -> std::string { + std::string out; + CheckedAPICall(duckdb_v2_connection_get_profiling_information, handle(), format.data(), format.size(), CollectText, + &out); + return out; +} + +//---------------------------------------------------------------------------------------------------------------------- +// Value +//---------------------------------------------------------------------------------------------------------------------- + +Value::Value(void *impl) : detail::Handle(impl) { +} + +Value::~Value() { + auto _h = handle(); + duckdb_v2_value_destroy(&_h); +} + +auto Value::IsNull() const -> bool { + bool is_null = false; + CheckedAPICall(duckdb_v2_value_is_null, handle(), &is_null); + return is_null; +} + +auto Value::GetLogicalType() const -> LogicalType { + duckdb_v2_logical_type_handle type = nullptr; + CheckedAPICall(duckdb_v2_value_get_logical_type, handle(), &type); + return detail::HandleFactory::Make(type); +} + +auto Value::ToText() const -> std::string { + return RenderText(duckdb_v2_value_to_string, handle()); +} + +auto Value::Cast(Factory &factory, const LogicalType &target) const -> Value { + duckdb_v2_value_handle value = nullptr; + CheckedAPICall(duckdb_v2_value_cast, factory.handle(), handle(), target.handle(), &value); + return detail::HandleFactory::Make(value); +} + +auto Value::GetChildCount() const -> idx_t { + idx_t count = 0; + CheckedAPICall(duckdb_v2_value_get_child_count, handle(), &count); + return count; +} + +auto Value::GetChild(idx_t index) const -> Value { + duckdb_v2_value_handle child = nullptr; + CheckedAPICall(duckdb_v2_value_get_child, handle(), index, &child); + return detail::HandleFactory::Make(child); +} + +auto Value::VariantToValue() const -> Value { + duckdb_v2_value_handle converted = nullptr; + CheckedAPICall(duckdb_v2_value_variant_to_value, handle(), &converted); + return detail::HandleFactory::Make(converted); +} + +template <> +auto Value::Get() const -> bool { + bool value = false; + CheckedAPICall(duckdb_v2_value_get_bool, handle(), &value); + return value; +} + +template <> +auto Value::Get() const -> uint8_t { + uint8_t value = 0; + CheckedAPICall(duckdb_v2_value_get_utinyint, handle(), &value); + return value; +} + +template <> +auto Value::Get() const -> uint16_t { + uint16_t value = 0; + CheckedAPICall(duckdb_v2_value_get_usmallint, handle(), &value); + return value; +} + +template <> +auto Value::Get() const -> uint32_t { + uint32_t value = 0; + CheckedAPICall(duckdb_v2_value_get_uint, handle(), &value); + return value; +} + +template <> +auto Value::Get() const -> uint64_t { + uint64_t value = 0; + CheckedAPICall(duckdb_v2_value_get_ubigint, handle(), &value); + return value; +} + +template <> +auto Value::Get() const -> uint128_t { + duckdb_v2_uhugeint_t value {}; + CheckedAPICall(duckdb_v2_value_get_uhugeint, handle(), &value); + return FromC(value); +} + +template <> +auto Value::Get() const -> int8_t { + int8_t value = 0; + CheckedAPICall(duckdb_v2_value_get_tinyint, handle(), &value); + return value; +} + +template <> +auto Value::Get() const -> int16_t { + int16_t value = 0; + CheckedAPICall(duckdb_v2_value_get_smallint, handle(), &value); + return value; +} + +template <> +auto Value::Get() const -> int32_t { + int32_t value = 0; + CheckedAPICall(duckdb_v2_value_get_int, handle(), &value); + return value; +} + +template <> +auto Value::Get() const -> int64_t { + int64_t value = 0; + CheckedAPICall(duckdb_v2_value_get_bigint, handle(), &value); + return value; +} + +template <> +auto Value::Get() const -> int128_t { + duckdb_v2_hugeint_t value {}; + CheckedAPICall(duckdb_v2_value_get_hugeint, handle(), &value); + return FromC(value); +} + +template <> +auto Value::Get() const -> float { + float value = 0; + CheckedAPICall(duckdb_v2_value_get_float, handle(), &value); + return value; +} + +template <> +auto Value::Get() const -> double { + double value = 0; + CheckedAPICall(duckdb_v2_value_get_double, handle(), &value); + return value; +} + +template <> +auto Value::Get() const -> varchar_t { + const char *value = nullptr; + idx_t value_length = 0; + CheckedAPICall(duckdb_v2_value_get_varchar, handle(), &value, &value_length); + return varchar_t(value, value_length); +} + +template <> +auto Value::Get() const -> blob_t { + const char *value = nullptr; + idx_t value_length = 0; + CheckedAPICall(duckdb_v2_value_get_blob, handle(), &value, &value_length); + return blob_t(value, value_length); +} + +template <> +auto Value::Get() const -> LogicalType { + duckdb_v2_logical_type_handle type = nullptr; + CheckedAPICall(duckdb_v2_value_get_type, handle(), &type); + return detail::HandleFactory::Make(type); +} + +//---------------------------------------------------------------------------------------------------------------------- +// Value Constructors +//---------------------------------------------------------------------------------------------------------------------- + +#define MAKE_VALUE_IMPL(factory, name, ...) \ + duckdb_v2_value_handle handle = nullptr; \ + CheckedAPICall(name, factory.handle(), __VA_ARGS__, &handle); \ + return detail::HandleFactory::Make(handle); + +// Connection +// Context +auto Value::CreateNull(Factory &factory, const LogicalType &type) -> Value { + duckdb_v2_value_handle value = nullptr; + CheckedAPICall(duckdb_v2_value_create_null, factory.handle(), type.handle(), &value); + return detail::HandleFactory::Make(value); +} +auto Value::Create(Factory &factory, bool value) -> Value { + MAKE_VALUE_IMPL(factory, duckdb_v2_value_create_bool, value) +} + +auto Value::Create(Factory &factory, uint8_t value) -> Value { + MAKE_VALUE_IMPL(factory, duckdb_v2_value_create_utinyint, value) +} + +auto Value::Create(Factory &factory, uint16_t value) -> Value { + MAKE_VALUE_IMPL(factory, duckdb_v2_value_create_usmallint, value) +} + +auto Value::Create(Factory &factory, uint32_t value) -> Value { + MAKE_VALUE_IMPL(factory, duckdb_v2_value_create_uint, value) +} + +auto Value::Create(Factory &factory, uint64_t value) -> Value { + MAKE_VALUE_IMPL(factory, duckdb_v2_value_create_ubigint, value) +} + +auto Value::Create(Factory &factory, uint128_t value) -> Value { + auto value_uhugeint = ToC(value); + MAKE_VALUE_IMPL(factory, duckdb_v2_value_create_uhugeint, &value_uhugeint) +} + +auto Value::Create(Factory &factory, int8_t value) -> Value { + MAKE_VALUE_IMPL(factory, duckdb_v2_value_create_tinyint, value) +} + +auto Value::Create(Factory &factory, int16_t value) -> Value { + MAKE_VALUE_IMPL(factory, duckdb_v2_value_create_smallint, value) +} + +auto Value::Create(Factory &factory, int32_t value) -> Value { + MAKE_VALUE_IMPL(factory, duckdb_v2_value_create_int, value) +} + +auto Value::Create(Factory &factory, int64_t value) -> Value { + MAKE_VALUE_IMPL(factory, duckdb_v2_value_create_bigint, value) +} + +auto Value::Create(Factory &factory, int128_t value) -> Value { + auto value_hugeint = ToC(value); + MAKE_VALUE_IMPL(factory, duckdb_v2_value_create_hugeint, &value_hugeint) +} + +auto Value::Create(Factory &factory, float value) -> Value { + MAKE_VALUE_IMPL(factory, duckdb_v2_value_create_float, value) +} + +auto Value::Create(Factory &factory, double value) -> Value { + MAKE_VALUE_IMPL(factory, duckdb_v2_value_create_double, value) +} + +auto Value::Create(Factory &factory, blob_t value) -> Value { + auto value_str = ToStr(value); + MAKE_VALUE_IMPL(factory, duckdb_v2_value_create_blob, value_str.data(), value_str.size()) +} + +auto Value::Create(Factory &factory, varchar_t value) -> Value { + auto value_str = ToStr(value); + MAKE_VALUE_IMPL(factory, duckdb_v2_value_create_varchar, value_str.data(), value_str.size()) +} + +auto Value::Create(Factory &factory, const LogicalType &value) -> Value { + MAKE_VALUE_IMPL(factory, duckdb_v2_value_create_type, value.handle()) +} + +//---------------------------------------------------------------------------------------------------------------------- +// Temporal Values +//---------------------------------------------------------------------------------------------------------------------- + +// The wrapper types exist to name a SQL type that a plain integer cannot: +// TIMESTAMP, TIMESTAMP_S and TIMESTAMP_NS are all one int64. They carry the +// type's own unit, so nothing is converted here. + +template <> +auto Value::Get() const -> date_t { + int32_t payload = 0; + CheckedAPICall(duckdb_v2_value_get_date, handle(), &payload); + return date_t {payload}; +} + +auto Value::Create(Factory &factory, date_t value) -> Value { + MAKE_VALUE_IMPL(factory, duckdb_v2_value_create_date, value.days) +} + +template <> +auto Value::Get() const -> dtime_t { + int64_t payload = 0; + CheckedAPICall(duckdb_v2_value_get_time, handle(), &payload); + return dtime_t {payload}; +} + +auto Value::Create(Factory &factory, dtime_t value) -> Value { + MAKE_VALUE_IMPL(factory, duckdb_v2_value_create_time, value.micros) +} + +template <> +auto Value::Get() const -> dtime_ns_t { + int64_t payload = 0; + CheckedAPICall(duckdb_v2_value_get_time_ns, handle(), &payload); + return dtime_ns_t {payload}; +} + +auto Value::Create(Factory &factory, dtime_ns_t value) -> Value { + MAKE_VALUE_IMPL(factory, duckdb_v2_value_create_time_ns, value.nanos) +} + +template <> +auto Value::Get() const -> dtime_tz_t { + uint64_t payload = 0; + CheckedAPICall(duckdb_v2_value_get_time_tz, handle(), &payload); + return dtime_tz_t(payload); +} + +auto Value::Create(Factory &factory, dtime_tz_t value) -> Value { + MAKE_VALUE_IMPL(factory, duckdb_v2_value_create_time_tz, value.GetBits()) +} + +template <> +auto Value::Get() const -> timestamp_t { + int64_t payload = 0; + CheckedAPICall(duckdb_v2_value_get_timestamp, handle(), &payload); + return timestamp_t {payload}; +} + +auto Value::Create(Factory &factory, timestamp_t value) -> Value { + MAKE_VALUE_IMPL(factory, duckdb_v2_value_create_timestamp, value.micros) +} + +template <> +auto Value::Get() const -> timestamp_s_t { + int64_t payload = 0; + CheckedAPICall(duckdb_v2_value_get_timestamp_sec, handle(), &payload); + return timestamp_s_t {payload}; +} + +auto Value::Create(Factory &factory, timestamp_s_t value) -> Value { + MAKE_VALUE_IMPL(factory, duckdb_v2_value_create_timestamp_sec, value.seconds) +} + +template <> +auto Value::Get() const -> timestamp_ms_t { + int64_t payload = 0; + CheckedAPICall(duckdb_v2_value_get_timestamp_ms, handle(), &payload); + return timestamp_ms_t {payload}; +} + +auto Value::Create(Factory &factory, timestamp_ms_t value) -> Value { + MAKE_VALUE_IMPL(factory, duckdb_v2_value_create_timestamp_ms, value.millis) +} + +template <> +auto Value::Get() const -> timestamp_ns_t { + int64_t payload = 0; + CheckedAPICall(duckdb_v2_value_get_timestamp_ns, handle(), &payload); + return timestamp_ns_t {payload}; +} + +auto Value::Create(Factory &factory, timestamp_ns_t value) -> Value { + MAKE_VALUE_IMPL(factory, duckdb_v2_value_create_timestamp_ns, value.nanos) +} + +template <> +auto Value::Get() const -> timestamp_tz_t { + int64_t payload = 0; + CheckedAPICall(duckdb_v2_value_get_timestamp_tz, handle(), &payload); + return timestamp_tz_t {payload}; +} + +auto Value::Create(Factory &factory, timestamp_tz_t value) -> Value { + MAKE_VALUE_IMPL(factory, duckdb_v2_value_create_timestamp_tz, value.micros) +} + +template <> +auto Value::Get() const -> timestamp_tz_ns_t { + int64_t payload = 0; + CheckedAPICall(duckdb_v2_value_get_timestamp_tz_ns, handle(), &payload); + return timestamp_tz_ns_t {payload}; +} + +auto Value::Create(Factory &factory, timestamp_tz_ns_t value) -> Value { + MAKE_VALUE_IMPL(factory, duckdb_v2_value_create_timestamp_tz_ns, value.nanos) +} + +auto ToC(interval_t value) -> duckdb_v2_interval_t { + return duckdb_v2_interval_t {value.months, value.days, value.micros}; +} + +template <> +auto Value::Get() const -> interval_t { + duckdb_v2_interval_t payload {}; + CheckedAPICall(duckdb_v2_value_get_interval, handle(), &payload); + return interval_t {payload.months, payload.days, payload.micros}; +} + +auto Value::Create(Factory &factory, interval_t value) -> Value { + auto value_interval = ToC(value); + MAKE_VALUE_IMPL(factory, duckdb_v2_value_create_interval, &value_interval) +} + +void Value::GetDecimal(int128_t &out, uint32_t width, uint32_t scale) const { + duckdb_v2_hugeint_t payload {}; + uint32_t actual_width = 0; + uint32_t actual_scale = 0; + CheckedAPICall(duckdb_v2_value_get_decimal, handle(), &payload, &actual_width, &actual_scale); + if (actual_width != width || actual_scale != scale) { + throw InvalidInputException("Get: value is DECIMAL(" + std::to_string(actual_width) + ", " + + std::to_string(actual_scale) + "), not DECIMAL(" + std::to_string(width) + ", " + + std::to_string(scale) + ")"); + } + out = FromC(payload); +} + +auto Value::GetDecimal() const -> RuntimeDecimal { + duckdb_v2_hugeint_t payload {}; + RuntimeDecimal result {}; + CheckedAPICall(duckdb_v2_value_get_decimal, handle(), &payload, &result.width, &result.scale); + result.value = FromC(payload); + return result; +} + +auto Value::CreateDecimal(Factory &factory, int128_t value, uint32_t width, uint32_t scale) -> Value { + duckdb_v2_value_handle out = nullptr; + auto value_hugeint = ToC(value); + CheckedAPICall(duckdb_v2_value_create_decimal, factory.handle(), &value_hugeint, width, scale, &out); + return detail::HandleFactory::Make(out); +} + +//---------------------------------------------------------------------------------------------------------------------- +// BIT, BIGNUM and UUID +//---------------------------------------------------------------------------------------------------------------------- + +// Each is a lens over a payload that already has a C representation, so the +// constructors and getters reuse those entry points; what the types add is a +// distinct name for overload resolution and the decode the storage needs. + +auto bignum_t::Decode() const -> Decoded { + const auto *bytes = reinterpret_cast(data()); + Decoded out {}; + idx_t length = 0; + CheckedAPICall(duckdb_v2_bignum_decode, bytes, static_cast(size()), nullptr, static_cast(0), &length, + &out.is_negative); + out.magnitude.resize(length); + CheckedAPICall(duckdb_v2_bignum_decode, bytes, static_cast(size()), out.magnitude.data(), + static_cast(out.magnitude.size()), &length, &out.is_negative); + return out; +} + +auto bignum_t::Encode(const Decoded &value) -> std::vector { + idx_t length = 0; + CheckedAPICall(duckdb_v2_bignum_encode, value.magnitude.data(), static_cast(value.magnitude.size()), + value.is_negative, nullptr, static_cast(0), &length); + std::vector storage(length); + CheckedAPICall(duckdb_v2_bignum_encode, value.magnitude.data(), static_cast(value.magnitude.size()), + value.is_negative, storage.data(), static_cast(storage.size()), &length); + return storage; +} + +template <> +auto Value::Get() const -> bit_t { + const char *payload = nullptr; + idx_t payload_length = 0; + CheckedAPICall(duckdb_v2_value_get_blob, handle(), &payload, &payload_length); + return bit_t(payload, static_cast(payload_length)); +} + +template <> +auto Value::Get() const -> bignum_t { + const char *payload = nullptr; + idx_t payload_length = 0; + CheckedAPICall(duckdb_v2_value_get_blob, handle(), &payload, &payload_length); + return bignum_t(payload, static_cast(payload_length)); +} + +template <> +auto Value::Get() const -> uuid_t { + duckdb_v2_hugeint_t payload {}; + CheckedAPICall(duckdb_v2_value_get_uuid, handle(), &payload); + return uuid_t(FromC(payload)); +} + +auto Value::Create(Factory &factory, bit_t value) -> Value { + auto value_str = ToStr(value); + MAKE_VALUE_IMPL(factory, duckdb_v2_value_create_bit, value_str.data(), value_str.size()) +} + +auto Value::Create(Factory &factory, bignum_t value) -> Value { + auto value_str = ToStr(value); + MAKE_VALUE_IMPL(factory, duckdb_v2_value_create_bignum, value_str.data(), value_str.size()) +} + +auto Value::Create(Factory &factory, uuid_t value) -> Value { + auto value_hugeint = ToC(value.value); + MAKE_VALUE_IMPL(factory, duckdb_v2_value_create_uuid, &value_hugeint) +} + +//---------------------------------------------------------------------------------------------------------------------- +// Composite Value Constructors +//---------------------------------------------------------------------------------------------------------------------- + +// Each is a straight forward to its C entry point: the child types are +// resolved engine-side, so nothing is assembled here beyond flattening the +// borrowed children into handle arrays. +namespace { + +auto ChildHandles(const std::vector &values) -> std::vector { + std::vector handles; + handles.reserve(values.size()); + for (const auto &value : values) { + handles.push_back(value.handle()); + } + return handles; +} + +// Empty vectors have no data(), and the C API takes NULL for an empty array. +template +auto DataOrNull(const std::vector &values) -> const T * { + return values.empty() ? nullptr : values.data(); +} + +auto FromHandle(duckdb_v2_value_handle value) -> Value { + return detail::HandleFactory::Make(value); +} + +} // namespace + +auto Value::CreateList(Factory &factory, ValueList values) -> Value { + auto children = ChildHandles(values); + duckdb_v2_value_handle out = nullptr; + CheckedAPICall(duckdb_v2_value_create_list, factory.handle(), nullptr, DataOrNull(children), + static_cast(children.size()), &out); + return FromHandle(out); +} + +auto Value::CreateList(Factory &factory, const LogicalType &child_type) -> Value { + duckdb_v2_value_handle out = nullptr; + CheckedAPICall(duckdb_v2_value_create_list, factory.handle(), child_type.handle(), nullptr, static_cast(0), + &out); + return FromHandle(out); +} + +auto Value::CreateArray(Factory &factory, ValueList values) -> Value { + auto children = ChildHandles(values); + duckdb_v2_value_handle out = nullptr; + CheckedAPICall(duckdb_v2_value_create_array, factory.handle(), nullptr, DataOrNull(children), + static_cast(children.size()), &out); + return FromHandle(out); +} + +namespace { + +// STRUCT crosses as parallel name and child arrays. +struct StructArrays { + explicit StructArrays(const std::vector> &values) : names(values.size()) { + children.reserve(values.size()); + for (const auto &field : values) { + names.Push(field.first); + children.push_back(field.second.handle()); + } + } + StringArrays names; + std::vector children; +}; + +} // namespace + +auto Value::CreateStruct(Factory &factory, NamedValueList values) -> Value { + StructArrays split(values); + duckdb_v2_value_handle out = nullptr; + CheckedAPICall(duckdb_v2_value_create_struct, factory.handle(), split.names.ptrs(), split.names.lengths(), + DataOrNull(split.children), static_cast(values.size()), &out); + return FromHandle(out); +} + +auto Value::CreateTuple(Factory &factory, ValueList values) -> Value { + auto children = ChildHandles(values); + duckdb_v2_value_handle out = nullptr; + CheckedAPICall(duckdb_v2_value_create_tuple, factory.handle(), DataOrNull(children), + static_cast(children.size()), &out); + return FromHandle(out); +} + +namespace { + +// MAP crosses as parallel key and value arrays. +struct MapArrays { + explicit MapArrays(const std::vector> &values) { + keys.reserve(values.size()); + entries.reserve(values.size()); + for (const auto &entry : values) { + keys.push_back(entry.first.handle()); + entries.push_back(entry.second.handle()); + } + } + std::vector keys; + std::vector entries; +}; + +} // namespace + +auto Value::CreateMap(Factory &factory, KeyValueList values) -> Value { + MapArrays split(values); + duckdb_v2_value_handle out = nullptr; + CheckedAPICall(duckdb_v2_value_create_map, factory.handle(), nullptr, nullptr, DataOrNull(split.keys), + DataOrNull(split.entries), static_cast(values.size()), &out); + return FromHandle(out); +} + +auto Value::CreateMap(Factory &factory, const LogicalType &key_type, const LogicalType &value_type) -> Value { + duckdb_v2_value_handle out = nullptr; + CheckedAPICall(duckdb_v2_value_create_map, factory.handle(), key_type.handle(), value_type.handle(), nullptr, + nullptr, static_cast(0), &out); + return FromHandle(out); +} + +//---------------------------------------------------------------------------------------------------------------------- +// String Heap +//---------------------------------------------------------------------------------------------------------------------- +// blob_t mirrors duckdb_v2_bytes; pin it here (both types visible) so any +// layout drift breaks the build rather than the ABI. +static_assert(sizeof(blob_t) == sizeof(duckdb_v2_bytes) && alignof(blob_t) == alignof(duckdb_v2_bytes), + "blob_t must mirror the C ABI's duckdb_v2_bytes"); +static_assert(offsetof(blob_t, value.pointer.length) == offsetof(duckdb_v2_bytes, value.pointer.length) && + offsetof(blob_t, value.pointer.prefix) == offsetof(duckdb_v2_bytes, value.pointer.prefix) && + offsetof(blob_t, value.pointer.ptr) == offsetof(duckdb_v2_bytes, value.pointer.ptr) && + offsetof(blob_t, value.inlined.inlined) == offsetof(duckdb_v2_bytes, value.inlined.inlined), + "blob_t field offsets must match duckdb_v2_bytes"); +static_assert(blob_t::INLINE_LENGTH == DUCKDB_V2_BYTES_INLINE_LENGTH, + "blob_t::INLINE_LENGTH must match DUCKDB_V2_BYTES_INLINE_LENGTH"); + +Arena::Arena(void *impl) : detail::Handle(impl) { +} + +Arena::~Arena() { + /* String heaps are always borrowed, so we don't destroy the handle here */ +} + +auto Arena::Allocate(idx_t byte_len) -> uint8_t * { + uint8_t *ptr = nullptr; + CheckedAPICall(duckdb_v2_arena_allocate, handle(), byte_len, &ptr); + return ptr; +} + +auto Arena::ThrowStringTooLong(idx_t size) -> void { + throw Exception(DUCKDB_V2_ERROR_INPUT_OUT_OF_RANGE, "Out of Range Error: string length " + std::to_string(size) + + " exceeds the maximum a duckdb_v2_bytes can hold"); +} + +//---------------------------------------------------------------------------------------------------------------------- +// Vector +//---------------------------------------------------------------------------------------------------------------------- +// VectorType mirrors DUCKDB_V2_VECTOR_TYPE numerically; trip here if either +// side is renumbered. +static_assert(static_cast(VectorType::OTHER) == DUCKDB_V2_VECTOR_TYPE_OTHER, + "VectorType must mirror DUCKDB_V2_VECTOR_TYPE"); +static_assert(static_cast(VectorType::FLAT) == DUCKDB_V2_VECTOR_TYPE_FLAT, + "VectorType must mirror DUCKDB_V2_VECTOR_TYPE"); +static_assert(static_cast(VectorType::CONSTANT) == DUCKDB_V2_VECTOR_TYPE_CONSTANT, + "VectorType must mirror DUCKDB_V2_VECTOR_TYPE"); +static_assert(static_cast(VectorType::DICTIONARY) == DUCKDB_V2_VECTOR_TYPE_DICTIONARY, + "VectorType must mirror DUCKDB_V2_VECTOR_TYPE"); + +// VectorView mirrors duckdb_v2_vector_view. GetView copies it field-for-field, +// so the compiler checks the pointer types; this pins the one typedef the +// header cannot see. +static_assert(std::is_same::value, "VectorView::sel must mirror duckdb_v2_sel_t"); + +Vector::Vector(void *impl) : detail::Handle(impl) { +} + +Vector::~Vector() { + /* Vectors are always borrowed, so we don't destroy the handle here */ +} + +auto Vector::GetDataMutable() -> void * { + void *data = nullptr; + CheckedAPICall(duckdb_v2_vector_get_data_mutable, handle(), &data); + return data; +} + +auto Vector::GetChildCount() const -> idx_t { + idx_t count = 0; + CheckedAPICall(duckdb_v2_vector_get_child_count, handle(), &count); + return count; +} + +auto Vector::GetChild(idx_t index) const -> Vector { + duckdb_v2_vector_handle child = nullptr; + CheckedAPICall(duckdb_v2_vector_get_child, handle(), index, &child); + return detail::HandleFactory::Make(child); +} + +auto Vector::Flatten() const -> void { + CheckedAPICall(duckdb_v2_vector_flatten, handle()); +} + +auto Vector::Reference(const Vector &source) -> void { + CheckedAPICall(duckdb_v2_vector_reference, handle(), source.handle()); +} + +auto Vector::Cast(Factory &factory, Vector &target) const -> void { + CheckedAPICall(duckdb_v2_vector_cast, factory.handle(), handle(), target.handle(), DUCKDB_V2_CAST_MODE_NORMAL, + nullptr, nullptr); +} + +auto Vector::TryCast(Factory &factory, Vector &target, std::string *error_message) const -> bool { + bool converted = false; + duckdb_v2_error_info_handle cast_error = nullptr; + CheckedAPICall(duckdb_v2_vector_cast, factory.handle(), handle(), target.handle(), DUCKDB_V2_CAST_MODE_TRY, + &converted, error_message ? &cast_error : nullptr); + if (cast_error) { + const char *text = nullptr; + idx_t text_length = 0; + duckdb_v2_error_info_get_text(cast_error, &text, &text_length); + error_message->assign(std::string(FromStr(text, text_length))); + duckdb_v2_error_info_destroy(&cast_error); + } + return converted; +} + +auto Vector::GetLogicalType() const -> LogicalType { + duckdb_v2_logical_type_handle type = nullptr; + CheckedAPICall(duckdb_v2_vector_get_logical_type, handle(), &type); + return detail::HandleFactory::Make(type); +} + +auto Vector::GetSize() const -> idx_t { + idx_t size = 0; + CheckedAPICall(duckdb_v2_vector_get_size, handle(), &size); + return size; +} + +auto Vector::SetSize(idx_t size) -> void { + CheckedAPICall(duckdb_v2_vector_set_size, handle(), size); +} + +auto Vector::GetView() const -> VectorView { + duckdb_v2_vector_view view {}; + CheckedAPICall(duckdb_v2_vector_get_view, handle(), &view); + return VectorView {view.data, view.validity, view.sel, view.count}; +} + +auto Vector::GetVectorType() const -> VectorType { + DUCKDB_V2_VECTOR_TYPE type = DUCKDB_V2_VECTOR_TYPE_OTHER; + CheckedAPICall(duckdb_v2_vector_get_vector_type, handle(), &type); + return static_cast(type); +} + +auto Vector::GetValidityMutable() -> ValidityMask { + uint64_t *words = nullptr; + CheckedAPICall(duckdb_v2_vector_flat_get_validity_mutable, handle(), &words); + return ValidityMask {words}; +} + +auto Vector::SetNull(idx_t row) -> void { + CheckedAPICall(duckdb_v2_vector_set_null, handle(), row); +} + +auto Vector::SetConstantValid(bool valid) -> void { + CheckedAPICall(duckdb_v2_vector_constant_set_valid, handle(), valid); +} + +auto Vector::MakeConstant(const Value &value, idx_t count) -> void { + CheckedAPICall(duckdb_v2_vector_make_constant, handle(), value.handle(), count); +} + +auto Vector::MakeSequence(int64_t start, int64_t increment, idx_t count) -> void { + CheckedAPICall(duckdb_v2_vector_make_sequence, handle(), start, increment, count); +} + +auto Vector::GetValue(idx_t row) const -> Value { + duckdb_v2_value_handle value = nullptr; + CheckedAPICall(duckdb_v2_vector_get_value, handle(), row, &value); + return detail::HandleFactory::Make(value); +} + +auto Vector::SetValue(idx_t row, const Value &value) -> void { + CheckedAPICall(duckdb_v2_vector_set_value, handle(), row, value.handle()); +} + +// --- end single-cell value bridge --- + +auto Vector::CheckWriteRange(idx_t start, idx_t count) const -> void { + if (count == 0) { + return; + } + // A CONSTANT vector's data array holds a single slot; only index 0 is writable. + if (GetVectorType() == VectorType::CONSTANT && (start != 0 || count > 1)) { + throw InvalidInputException("Invalid Input Error: cannot assign a string to a CONSTANT vector at index != 0"); + } +} + +auto Vector::AssignString(idx_t index, std::string_view data) -> void { + if (GetLogicalType().GetTypeId() != LogicalTypeId::VARCHAR) { + AssignStringUnsafe(index, data); + return; + } + auto heap = GetHeap(); + SetString(index, heap.AddString(data)); +} + +auto Vector::AssignStringUnsafe(idx_t index, std::string_view data) -> void { + auto heap = GetHeap(); + auto bytes = heap.AddBlob(data); + SetString(index, varchar_t(bytes.data(), bytes.size())); +} + +auto Vector::GetHeap() -> Arena { + duckdb_v2_arena_handle heap = nullptr; + CheckedAPICall(duckdb_v2_vector_get_arena, handle(), &heap); + return detail::HandleFactory::Make(heap); +} + +auto Vector::SetString(idx_t index, varchar_t value) -> void { + CheckWriteRange(index, 1); + GetDataMutable()[index] = value; +} + +void ValidateUTF8(std::string_view text) { + auto text_str = ToStr(text); + CheckedAPICall(duckdb_v2_validate_utf8, text_str.data(), text_str.size()); +} + +//---------------------------------------------------------------------------------------------------------------------- +// Data Chunk +//---------------------------------------------------------------------------------------------------------------------- +namespace { +// LogicalType is a Handle (with a vtable), so its storage is not layout-compatible with a raw +// duckdb_v2_logical_type_handle array. Extract the underlying handles into a contiguous buffer. +auto ExtractTypeHandles(const std::vector &types) -> std::vector { + std::vector type_pointers; + type_pointers.reserve(types.size()); + for (const auto &type : types) { + type_pointers.push_back(type.handle()); + } + return type_pointers; +} +} // namespace + +DataChunk::DataChunk(Factory &factory, const std::vector &types) { + const auto type_pointers = ExtractTypeHandles(types); + duckdb_v2_data_chunk_handle chunk = nullptr; + CheckedAPICall(duckdb_v2_data_chunk_create, factory.handle(), type_pointers.data(), type_pointers.size(), &chunk); + + impl = chunk; + owned = true; +} + +DataChunk::DataChunk(void *impl, bool owned) : detail::Handle(impl), owned(owned) { +} + +DataChunk::~DataChunk() { + if (owned) { + auto _h = handle(); + duckdb_v2_data_chunk_destroy(&_h); + } +} + +auto DataChunk::Copy(Factory &factory) const -> DataChunk { + duckdb_v2_data_chunk_handle copy = nullptr; + CheckedAPICall(duckdb_v2_data_chunk_copy, factory.handle(), handle(), ©); + return detail::HandleFactory::Make(copy, true); +} + +auto DataChunk::GetRowCount() const -> idx_t { + idx_t count = 0; + CheckedAPICall(duckdb_v2_data_chunk_get_size, handle(), &count); + return count; +} + +auto DataChunk::GetCapacity() const -> idx_t { + idx_t capacity = 0; + CheckedAPICall(duckdb_v2_data_chunk_get_capacity, handle(), &capacity); + return capacity; +} + +auto DataChunk::Clear() -> void { + CheckedAPICall(duckdb_v2_data_chunk_clear, handle()); +} + +auto DataChunk::GetVectorCount() const -> idx_t { + idx_t count = 0; + CheckedAPICall(duckdb_v2_data_chunk_get_vector_count, handle(), &count); + return count; +} + +auto DataChunk::GetVector(idx_t index) const -> Vector { + duckdb_v2_vector_handle vector = nullptr; + CheckedAPICall(duckdb_v2_data_chunk_get_vector, handle(), index, &vector); + return detail::HandleFactory::Make(vector); +} + +//---------------------------------------------------------------------------------------------------------------------- +// Column Data Collection +//---------------------------------------------------------------------------------------------------------------------- + +ColumnDataCollection::AppendState::AppendState(void *impl) : detail::Handle(impl) { +} + +ColumnDataCollection::AppendState::~AppendState() { + auto _h = handle(); + duckdb_v2_column_data_collection_append_state_destroy(&_h); +} + +ColumnDataCollection::SharedScanState::SharedScanState(void *impl) : detail::Handle(impl) { +} + +ColumnDataCollection::SharedScanState::~SharedScanState() { + auto _h = handle(); + duckdb_v2_column_data_collection_shared_scan_state_destroy(&_h); +} + +ColumnDataCollection::WorkerScanState::WorkerScanState(void *impl) : detail::Handle(impl) { +} + +ColumnDataCollection::WorkerScanState::~WorkerScanState() { + auto _h = handle(); + duckdb_v2_column_data_collection_worker_scan_state_destroy(&_h); +} + +ColumnDataCollection::ColumnDataCollection(Factory &factory, const std::vector &types) { + const auto type_pointers = ExtractTypeHandles(types); + duckdb_v2_column_data_collection_handle collection = nullptr; + CheckedAPICall(duckdb_v2_column_data_collection_create, factory.handle(), type_pointers.data(), + type_pointers.size(), &collection); + impl = collection; +} + +ColumnDataCollection::ColumnDataCollection(void *impl) : detail::Handle(impl) { +} + +auto Factory::CreateDataChunk(const std::vector &types) -> DataChunk { + return DataChunk(*this, types); +} + +auto Factory::CreateColumnDataCollection(const std::vector &types) -> ColumnDataCollection { + return ColumnDataCollection(*this, types); +} + +ColumnDataCollection::~ColumnDataCollection() { + auto _h = handle(); + duckdb_v2_column_data_collection_destroy(&_h); +} + +auto ColumnDataCollection::GetRowCount() const -> idx_t { + idx_t count = 0; + CheckedAPICall(duckdb_v2_column_data_collection_row_count, handle(), &count); + return count; +} + +auto ColumnDataCollection::Reset() -> void { + CheckedAPICall(duckdb_v2_column_data_collection_reset, handle()); +} + +auto ColumnDataCollection::Clear() -> void { + CheckedAPICall(duckdb_v2_column_data_collection_clear, handle()); +} + +// NOLINTNEXTLINE(cppcoreguidelines-rvalue-reference-param-not-moved) +auto ColumnDataCollection::Combine(ColumnDataCollection &&source) -> void { + auto source_handle = source.handle(); + CheckedAPICall(duckdb_v2_column_data_collection_combine, handle(), &source_handle); + // The C API consumed the source; detach the wrapper so its destructor does not double-free. A refused merge threw + // above and leaves the source intact. + source.release(); +} + +auto ColumnDataCollection::CreateAppendState() -> AppendState { + duckdb_v2_column_data_collection_append_state_handle state = nullptr; + CheckedAPICall(duckdb_v2_column_data_collection_append_state_create, handle(), &state); + return detail::HandleFactory::Make(state); +} + +auto ColumnDataCollection::Append(AppendState &state, const DataChunk &chunk) -> void { + CheckedAPICall(duckdb_v2_column_data_collection_append, handle(), state.handle(), chunk.handle()); +} + +auto ColumnDataCollection::Append(const DataChunk &chunk) -> void { + auto state = CreateAppendState(); + Append(state, chunk); +} + +auto ColumnDataCollection::CreateSharedScanState() const -> SharedScanState { + duckdb_v2_column_data_collection_shared_scan_state_handle state = nullptr; + CheckedAPICall(duckdb_v2_column_data_collection_shared_scan_state_create, handle(), &state); + return detail::HandleFactory::Make(state); +} + +auto ColumnDataCollection::CreateWorkerScanState() const -> WorkerScanState { + duckdb_v2_column_data_collection_worker_scan_state_handle state = nullptr; + CheckedAPICall(duckdb_v2_column_data_collection_worker_scan_state_create, handle(), &state); + return detail::HandleFactory::Make(state); +} + +auto ColumnDataCollection::Scan(SharedScanState &shared, WorkerScanState &worker, DataChunk &chunk) const -> bool { + bool did_produce = false; + CheckedAPICall(duckdb_v2_column_data_collection_scan, handle(), shared.handle(), worker.handle(), chunk.handle(), + &did_produce); + return did_produce; +} + +//---------------------------------------------------------------------------------------------------------------------- +// Query Result +//---------------------------------------------------------------------------------------------------------------------- + +QueryResult::QueryResult(void *impl) : detail::Handle(impl) { +} + +QueryResult::~QueryResult() { + auto _h = handle(); + duckdb_v2_result_destroy(&_h); +} + +auto QueryResult::GetSchema() const -> Schema { + duckdb_v2_schema_handle schema = nullptr; + CheckedAPICall(duckdb_v2_result_get_schema, handle(), &schema); + return detail::HandleFactory::Make(schema); +} + +// ResultType mirrors DUCKDB_V2_RESULT_TYPE numerically; every member is pinned. +static_assert(static_cast(ResultType::QUERY_RESULT) == DUCKDB_V2_RESULT_TYPE_QUERY_RESULT, + "ResultType must mirror DUCKDB_V2_RESULT_TYPE"); +static_assert(static_cast(ResultType::CHANGED_ROWS) == DUCKDB_V2_RESULT_TYPE_CHANGED_ROWS, + "ResultType must mirror DUCKDB_V2_RESULT_TYPE"); +static_assert(static_cast(ResultType::NOTHING) == DUCKDB_V2_RESULT_TYPE_NOTHING, + "ResultType must mirror DUCKDB_V2_RESULT_TYPE"); + +// StatementType mirrors DUCKDB_V2_STATEMENT_TYPE numerically; every member is pinned. +#define DUCKDB_CPP_ASSERT_STATEMENT_TYPE(member) \ + static_assert(static_cast(StatementType::member) == DUCKDB_V2_STATEMENT_TYPE_##member, \ + "StatementType::" #member " must mirror DUCKDB_V2_STATEMENT_TYPE_" #member) +DUCKDB_CPP_ASSERT_STATEMENT_TYPE(INVALID); +DUCKDB_CPP_ASSERT_STATEMENT_TYPE(SELECT); +DUCKDB_CPP_ASSERT_STATEMENT_TYPE(INSERT); +DUCKDB_CPP_ASSERT_STATEMENT_TYPE(UPDATE); +DUCKDB_CPP_ASSERT_STATEMENT_TYPE(CREATE); +DUCKDB_CPP_ASSERT_STATEMENT_TYPE(DELETE); +DUCKDB_CPP_ASSERT_STATEMENT_TYPE(PREPARE); +DUCKDB_CPP_ASSERT_STATEMENT_TYPE(EXECUTE); +DUCKDB_CPP_ASSERT_STATEMENT_TYPE(ALTER); +DUCKDB_CPP_ASSERT_STATEMENT_TYPE(TRANSACTION); +DUCKDB_CPP_ASSERT_STATEMENT_TYPE(COPY); +DUCKDB_CPP_ASSERT_STATEMENT_TYPE(ANALYZE); +DUCKDB_CPP_ASSERT_STATEMENT_TYPE(VARIABLE_SET); +DUCKDB_CPP_ASSERT_STATEMENT_TYPE(CREATE_FUNC); +DUCKDB_CPP_ASSERT_STATEMENT_TYPE(EXPLAIN); +DUCKDB_CPP_ASSERT_STATEMENT_TYPE(DROP); +DUCKDB_CPP_ASSERT_STATEMENT_TYPE(EXPORT); +DUCKDB_CPP_ASSERT_STATEMENT_TYPE(PRAGMA); +DUCKDB_CPP_ASSERT_STATEMENT_TYPE(VACUUM); +DUCKDB_CPP_ASSERT_STATEMENT_TYPE(CALL); +DUCKDB_CPP_ASSERT_STATEMENT_TYPE(SET); +DUCKDB_CPP_ASSERT_STATEMENT_TYPE(LOAD); +DUCKDB_CPP_ASSERT_STATEMENT_TYPE(RELATION); +DUCKDB_CPP_ASSERT_STATEMENT_TYPE(EXTENSION); +DUCKDB_CPP_ASSERT_STATEMENT_TYPE(LOGICAL_PLAN); +DUCKDB_CPP_ASSERT_STATEMENT_TYPE(ATTACH); +DUCKDB_CPP_ASSERT_STATEMENT_TYPE(DETACH); +DUCKDB_CPP_ASSERT_STATEMENT_TYPE(MULTI); +DUCKDB_CPP_ASSERT_STATEMENT_TYPE(COPY_DATABASE); +DUCKDB_CPP_ASSERT_STATEMENT_TYPE(UPDATE_EXTENSIONS); +DUCKDB_CPP_ASSERT_STATEMENT_TYPE(MERGE_INTO); +DUCKDB_CPP_ASSERT_STATEMENT_TYPE(CONNECT); +DUCKDB_CPP_ASSERT_STATEMENT_TYPE(DISCONNECT); +DUCKDB_CPP_ASSERT_STATEMENT_TYPE(EXTERNAL_RESOURCE); +#undef DUCKDB_CPP_ASSERT_STATEMENT_TYPE + +auto QueryResult::GetResultType() const -> ResultType { + DUCKDB_V2_RESULT_TYPE type = DUCKDB_V2_RESULT_TYPE_QUERY_RESULT; + CheckedAPICall(duckdb_v2_result_get_result_type, handle(), &type); + return static_cast(type); +} + +auto QueryResult::GetStatementType() const -> StatementType { + DUCKDB_V2_STATEMENT_TYPE type = DUCKDB_V2_STATEMENT_TYPE_INVALID; + CheckedAPICall(duckdb_v2_result_get_statement_type, handle(), &type); + return static_cast(type); +} + +// StepStatus mirrors DUCKDB_V2_RESULT_STEP_STATUS numerically; trip here if +// either side is renumbered. +static_assert(static_cast(StepStatus::WAITING) == DUCKDB_V2_RESULT_STEP_STATUS_WAITING, + "StepStatus must mirror DUCKDB_V2_RESULT_STEP_STATUS"); +static_assert(static_cast(StepStatus::CHUNK) == DUCKDB_V2_RESULT_STEP_STATUS_CHUNK, + "StepStatus must mirror DUCKDB_V2_RESULT_STEP_STATUS"); +static_assert(static_cast(StepStatus::FINISHED) == DUCKDB_V2_RESULT_STEP_STATUS_FINISHED, + "StepStatus must mirror DUCKDB_V2_RESULT_STEP_STATUS"); +static_assert(static_cast(StepStatus::CANCELLED) == DUCKDB_V2_RESULT_STEP_STATUS_CANCELLED, + "StepStatus must mirror DUCKDB_V2_RESULT_STEP_STATUS"); + +auto QueryResult::Step() -> StepResult { + duckdb_v2_data_chunk_handle chunk = nullptr; + DUCKDB_V2_RESULT_STEP_STATUS status = DUCKDB_V2_RESULT_STEP_STATUS_WAITING; + CheckedAPICall(duckdb_v2_result_step, handle(), &chunk, &status); + return StepResult {static_cast(status), + detail::HandleFactory::Make(chunk, chunk != nullptr)}; +} + +auto QueryResult::Wait() -> void { + CheckedAPICall(duckdb_v2_result_wait, handle()); +} + +auto QueryResult::FetchChunk() -> DataChunk { + duckdb_v2_data_chunk_handle chunk = nullptr; + CheckedAPICall(duckdb_v2_result_fetch_chunk, handle(), &chunk); + // An empty handle marks end-of-stream. + return detail::HandleFactory::Make(chunk, chunk != nullptr); +} + +auto QueryResult::Drain() -> idx_t { + idx_t rows_changed = 0; + CheckedAPICall(duckdb_v2_result_drain, handle(), &rows_changed); + return rows_changed; +} + +auto QueryResult::RenderBox(idx_t max_rows, idx_t max_width, idx_t max_col_width, const std::string &null_value, + idx_t render_mode, idx_t limit) -> std::string { + auto raw = handle(); + this->release(); + std::string out; + + auto sink = [](const char *text, idx_t text_length, void *user_data, duckdb_v2_error_info_handle *err) { + WithExceptionGuard(err, [&] { + if (text && text_length) { + static_cast(user_data)->append(text, text_length); + } + }); + }; + + auto null_value_str = ToStr(null_value); + CheckedAPICall(duckdb_v2_result_render_box, &raw, max_rows, max_width, max_col_width, null_value_str.data(), + null_value_str.size(), render_mode, limit, sink, &out); + return out; +} + +//---------------------------------------------------------------------------------------------------------------------- +// Arrow Result +//---------------------------------------------------------------------------------------------------------------------- + +ArrowResult::ArrowResult(void *impl) : detail::Handle(impl) { +} + +ArrowResult::~ArrowResult() { + auto _h = handle(); + duckdb_v2_arrow_result_destroy(&_h); +} + +auto ArrowResult::GetSchema(ArrowSchema &out) const -> void { + out.release = nullptr; + CheckedAPICall(duckdb_v2_arrow_result_get_schema, handle(), &out); +} + +auto ArrowResult::GetResultType() const -> ResultType { + DUCKDB_V2_RESULT_TYPE type = DUCKDB_V2_RESULT_TYPE_QUERY_RESULT; + CheckedAPICall(duckdb_v2_arrow_result_get_result_type, handle(), &type); + return static_cast(type); +} + +auto ArrowResult::GetStatementType() const -> StatementType { + DUCKDB_V2_STATEMENT_TYPE type = DUCKDB_V2_STATEMENT_TYPE_INVALID; + CheckedAPICall(duckdb_v2_arrow_result_get_statement_type, handle(), &type); + return static_cast(type); +} + +auto ArrowResult::Step(ArrowArray &out) -> StepStatus { + out.release = nullptr; + DUCKDB_V2_RESULT_STEP_STATUS status = DUCKDB_V2_RESULT_STEP_STATUS_WAITING; + CheckedAPICall(duckdb_v2_arrow_result_step, handle(), &out, &status); + return static_cast(status); +} + +auto ArrowResult::Wait() -> void { + CheckedAPICall(duckdb_v2_arrow_result_wait, handle()); +} + +auto ArrowResult::FetchArray(ArrowArray &out) -> bool { + out.release = nullptr; + CheckedAPICall(duckdb_v2_arrow_result_fetch_array, handle(), &out); + // A released array marks end-of-stream. + return out.release != nullptr; +} + +auto ArrowResult::Drain() -> idx_t { + idx_t rows_changed = 0; + CheckedAPICall(duckdb_v2_arrow_result_drain, handle(), &rows_changed); + return rows_changed; +} + +auto ArrowResult::ToArrowStream(ArrowArrayStream &out) -> void { + out.release = nullptr; + auto raw = handle(); + CheckedAPICall(duckdb_v2_arrow_result_to_arrow_c_stream, &raw, &out); + // The stream owns the result now; detach without destroying it. A failed conversion threw above and left it here. + release(); +} + +//---------------------------------------------------------------------------------------------------------------------- +// Arrow +//---------------------------------------------------------------------------------------------------------------------- + +ArrowImporter::ArrowImporter(void *impl) : detail::Handle(impl) { +} + +ArrowImporter::ArrowImporter(Context &context, ArrowSchema &schema, idx_t batch_size) + : detail::Handle(nullptr) { + duckdb_v2_arrow_importer_handle importer = nullptr; + CheckedAPICall(duckdb_v2_arrow_importer_create, context.handle(), &schema, batch_size, &importer); + impl = importer; +} + +ArrowImporter::~ArrowImporter() { + auto _h = handle(); + duckdb_v2_arrow_importer_destroy(&_h); +} + +auto ArrowImporter::GetSchema() const -> Schema { + duckdb_v2_schema_handle schema = nullptr; + CheckedAPICall(duckdb_v2_arrow_importer_get_schema, handle(), &schema); + return detail::HandleFactory::Make(schema); +} + +auto ArrowImporter::Append(ArrowArray &array, bool consume, bool flush) -> void { + CheckedAPICall(duckdb_v2_arrow_importer_append, handle(), &array, consume, flush); +} + +auto ArrowImporter::Flush() -> void { + CheckedAPICall(duckdb_v2_arrow_importer_append, handle(), static_cast(nullptr), false, true); +} + +auto ArrowImporter::NextChunk() -> DataChunk { + duckdb_v2_data_chunk_handle chunk = nullptr; + CheckedAPICall(duckdb_v2_arrow_importer_next_chunk, handle(), &chunk); + // A null handle, meaning the array is drained, becomes an empty DataChunk. + return detail::HandleFactory::Make(chunk, true); +} + +ArrowExporter::ArrowExporter(void *impl) : detail::Handle(impl) { +} + +ArrowExporter::ArrowExporter(Context &context, const std::vector &types, + const std::vector &names, idx_t batch_size) + : detail::Handle(nullptr) { + // LogicalType is a Handle with a vtable, so its storage is not layout-compatible with a raw + // handle array; extract into contiguous buffers. + std::vector type_handles; + StringArrays name_arrays(names.size()); + type_handles.reserve(types.size()); + for (const auto &type : types) { + type_handles.push_back(type.handle()); + } + for (const auto &name : names) { + name_arrays.Push(name); + } + if (type_handles.size() != name_arrays.size()) { + throw InvalidInputException("ArrowExporter: one name is required per column type"); + } + duckdb_v2_arrow_exporter_handle exporter = nullptr; + CheckedAPICall(duckdb_v2_arrow_exporter_create, context.handle(), + type_handles.empty() ? nullptr : type_handles.data(), name_arrays.ptrs(), name_arrays.lengths(), + static_cast(type_handles.size()), batch_size, &exporter); + impl = exporter; +} + +ArrowExporter::~ArrowExporter() { + auto _h = handle(); + duckdb_v2_arrow_exporter_destroy(&_h); +} + +auto ArrowExporter::GetSchema(ArrowSchema &out) const -> void { + out.release = nullptr; + CheckedAPICall(duckdb_v2_arrow_exporter_get_schema, handle(), &out); +} + +auto ArrowExporter::Append(const DataChunk &chunk, bool flush) -> void { + // consume is false, so the C call leaves the chunk alone; the copy of the handle only gives it a slot to read. + auto raw = chunk.handle(); + CheckedAPICall(duckdb_v2_arrow_exporter_append, handle(), &raw, false, flush); +} + +auto ArrowExporter::Flush() -> void { + CheckedAPICall(duckdb_v2_arrow_exporter_append, handle(), static_cast(nullptr), + false, true); +} + +auto ArrowExporter::NextArray(ArrowArray &out) -> bool { + out.release = nullptr; + CheckedAPICall(duckdb_v2_arrow_exporter_next_array, handle(), &out); + return out.release != nullptr; +} + +//---------------------------------------------------------------------------------------------------------------------- +// Function Signature +//---------------------------------------------------------------------------------------------------------------------- + +FunctionSignature::FunctionSignature(void *impl) : detail::Handle(impl) { +} + +FunctionSignature::~FunctionSignature() { + // The signature is borrowed from its function, so we don't destroy the handle here +} + +FunctionDocs::FunctionDocs(void *impl) : detail::Handle(impl) { +} + +FunctionDocs::~FunctionDocs() { + // The documentation is borrowed from its function, so we don't destroy the handle here +} + +auto FunctionDocs::SetDescription(std::string_view description) -> FunctionDocs & { + auto view = ToStr(description); + CheckedAPICall(duckdb_v2_function_docs_set_description, handle(), view.data(), view.size()); + return *this; +} + +auto FunctionDocs::AddExample(std::string_view title, std::string_view example) -> FunctionDocs & { + auto title_view = ToStr(title); + auto example_view = ToStr(example); + CheckedAPICall(duckdb_v2_function_docs_add_example, handle(), title_view.data(), title_view.size(), + example_view.data(), example_view.size()); + return *this; +} + +auto FunctionDocs::AddCategory(std::string_view category) -> FunctionDocs & { + auto view = ToStr(category); + CheckedAPICall(duckdb_v2_function_docs_add_category, handle(), view.data(), view.size()); + return *this; +} + +auto FunctionSignature::AddParameter(const std::string &name, const LogicalType &type, FunctionParameterKind kind) + -> FunctionSignature & { + auto name_str = ToStr(name); + CheckedAPICall(duckdb_v2_function_signature_add_parameter, handle(), name_str.data(), name_str.size(), + type.handle(), static_cast(nullptr), + static_cast(kind)); + return *this; +} + +auto FunctionSignature::AddParameter(const std::string &name, const LogicalType &type, const Value &default_value, + FunctionParameterKind kind) -> FunctionSignature & { + auto name_str = ToStr(name); + CheckedAPICall(duckdb_v2_function_signature_add_parameter, handle(), name_str.data(), name_str.size(), + type.handle(), default_value.handle(), static_cast(kind)); + return *this; +} + +auto FunctionSignature::AddArgs(const std::string &name, const LogicalType &type) -> FunctionSignature & { + return AddParameter(name, type, FunctionParameterKind::POSITIONAL_VARIADIC); +} + +auto FunctionSignature::AddKwargs(const std::string &name, const LogicalType &type) -> FunctionSignature & { + return AddParameter(name, type, FunctionParameterKind::NAMED_VARIADIC); +} + +//---------------------------------------------------------------------------------------------------------------------- +// Function Bind Input +//---------------------------------------------------------------------------------------------------------------------- + +static auto BindInfo(void *args) -> duckdb_v2_function_bind_info_handle { + return static_cast(args); +} + +void *FunctionBindInput::GetFunctionInfo() const { + void *user_data = nullptr; + CheckedAPICall(duckdb_v2_function_bind_get_user_data, BindInfo(args), &user_data); + return user_data; +} + +void FunctionBindInput::SetBindDataInternal(void *data, bool (*equals)(void *a, void *b), void (*destructor)(void *)) { + duckdb_v2_opaque opaque {data, destructor, equals}; + CheckedAPICall(duckdb_v2_function_bind_set_bind_data, BindInfo(args), &opaque); +} + +static auto ToArgumentCounts(idx_t positional_fixed, idx_t positional_variadic, idx_t named_fixed, idx_t named_variadic) + -> ArgumentCounts { + ArgumentCounts counts; + counts.positional_fixed = positional_fixed; + counts.positional_variadic = positional_variadic; + counts.named_fixed = named_fixed; + counts.named_variadic = named_variadic; + return counts; +} + +auto FunctionBindInput::GetArgumentCounts() const -> ArgumentCounts { + idx_t counts[4] = {}; + CheckedAPICall(duckdb_v2_function_bind_get_arg_count, BindInfo(args), &counts[0], &counts[1], &counts[2], + &counts[3]); + return ToArgumentCounts(counts[0], counts[1], counts[2], counts[3]); +} + +auto FunctionBindInput::GetArgCount() const -> idx_t { + return GetArgumentCounts().Total(); +} + +auto FunctionBindInput::GetArgType(idx_t index) const -> LogicalType { + duckdb_v2_logical_type_handle type = nullptr; + CheckedAPICall(duckdb_v2_function_bind_get_arg_type, BindInfo(args), index, &type); + return detail::HandleFactory::Make(type); +} + +auto FunctionBindInput::GetConstantArgument(idx_t index) const -> Value { + duckdb_v2_value_handle value = nullptr; + CheckedAPICall(duckdb_v2_function_bind_get_arg_value, BindInfo(args), index, &value); + return detail::HandleFactory::Make(value); +} + +auto FunctionBindInput::TryGetConstantArgument(idx_t index) const -> std::optional { + duckdb_v2_value_handle value = nullptr; + // No error slot: an argument without a constant value is absence here, not a failure to report. + const auto code = duckdb_v2_function_bind_get_arg_value(BindInfo(args), index, &value, nullptr); + if (code != DUCKDB_V2_ERROR_NONE) { + return std::nullopt; + } + return detail::HandleFactory::Make(value); +} + +auto FunctionBindInput::GetArgName(idx_t index) const -> std::string { + const char *name = nullptr; + idx_t name_length = 0; + CheckedAPICall(duckdb_v2_function_bind_get_arg_name, BindInfo(args), index, &name, &name_length); + return std::string(FromStr(name, name_length)); +} + +auto FunctionBindInput::FindArg(const std::string &name) const -> std::optional { + idx_t index = 0; + bool found = false; + auto name_str = ToStr(name); + CheckedAPICall(duckdb_v2_function_bind_get_arg_index, BindInfo(args), name_str.data(), name_str.size(), &index, + &found); + if (!found) { + return std::nullopt; + } + return index; +} + +auto FunctionBindInput::GetContext() -> Context & { + return context; +} + +auto FunctionSignature::SetReturnType(const LogicalType &type) -> FunctionSignature & { + CheckedAPICall(duckdb_v2_function_signature_set_return_type, handle(), type.handle()); + return *this; +} + +//---------------------------------------------------------------------------------------------------------------------- +// Function Properties +//---------------------------------------------------------------------------------------------------------------------- + +namespace { + +// Conversions from the typed C++ property enums to the C API's generic +// (key, value) channel. Every C++ enumerator maps to exactly one C value. + +auto ToCValue(FunctionStability value) -> DUCKDB_V2_FUNCTION_PROPERTY_VALUE { + switch (value) { + case FunctionStability::CONSISTENT: + return DUCKDB_V2_FUNCTION_PROPERTY_STABILITY_CONSISTENT; + case FunctionStability::VOLATILE: + return DUCKDB_V2_FUNCTION_PROPERTY_STABILITY_VOLATILE; + case FunctionStability::CONSISTENT_WITHIN_QUERY: + return DUCKDB_V2_FUNCTION_PROPERTY_STABILITY_CONSISTENT_WITHIN_QUERY; + } + return DUCKDB_V2_FUNCTION_PROPERTY_STABILITY_CONSISTENT; +} + +auto ToCValue(FunctionNullHandling value) -> DUCKDB_V2_FUNCTION_PROPERTY_VALUE { + switch (value) { + case FunctionNullHandling::DEFAULT: + return DUCKDB_V2_FUNCTION_PROPERTY_NULL_HANDLING_DEFAULT; + case FunctionNullHandling::SPECIAL: + return DUCKDB_V2_FUNCTION_PROPERTY_NULL_HANDLING_SPECIAL; + } + return DUCKDB_V2_FUNCTION_PROPERTY_NULL_HANDLING_DEFAULT; +} + +auto ToCValue(FunctionFallibility value) -> DUCKDB_V2_FUNCTION_PROPERTY_VALUE { + switch (value) { + case FunctionFallibility::INFALLIBLE: + return DUCKDB_V2_FUNCTION_PROPERTY_FALLIBILITY_INFALLIBLE; + case FunctionFallibility::FALLIBLE: + return DUCKDB_V2_FUNCTION_PROPERTY_FALLIBILITY_FALLIBLE; + } + return DUCKDB_V2_FUNCTION_PROPERTY_FALLIBILITY_FALLIBLE; +} + +auto ToCValue(FunctionCollationHandling value) -> DUCKDB_V2_FUNCTION_PROPERTY_VALUE { + switch (value) { + case FunctionCollationHandling::PROPAGATE: + return DUCKDB_V2_FUNCTION_PROPERTY_COLLATION_HANDLING_PROPAGATE; + case FunctionCollationHandling::PUSH_COMBINABLE: + return DUCKDB_V2_FUNCTION_PROPERTY_COLLATION_HANDLING_PUSH_COMBINABLE; + case FunctionCollationHandling::IGNORE: + return DUCKDB_V2_FUNCTION_PROPERTY_COLLATION_HANDLING_IGNORE; + } + return DUCKDB_V2_FUNCTION_PROPERTY_COLLATION_HANDLING_PROPAGATE; +} + +auto ToCValue(AggregateFunction::OrderDependence value) -> DUCKDB_V2_FUNCTION_PROPERTY_VALUE { + switch (value) { + case AggregateFunction::OrderDependence::DEPENDENT: + return DUCKDB_V2_FUNCTION_PROPERTY_AGG_ORDER_DEPENDENT_YES; + case AggregateFunction::OrderDependence::INDEPENDENT: + return DUCKDB_V2_FUNCTION_PROPERTY_AGG_ORDER_DEPENDENT_NO; + } + return DUCKDB_V2_FUNCTION_PROPERTY_AGG_ORDER_DEPENDENT_YES; +} + +auto ToCValue(AggregateFunction::DistinctDependence value) -> DUCKDB_V2_FUNCTION_PROPERTY_VALUE { + switch (value) { + case AggregateFunction::DistinctDependence::DEPENDENT: + return DUCKDB_V2_FUNCTION_PROPERTY_AGG_DISTINCT_DEPENDENT_YES; + case AggregateFunction::DistinctDependence::INDEPENDENT: + return DUCKDB_V2_FUNCTION_PROPERTY_AGG_DISTINCT_DEPENDENT_NO; + } + return DUCKDB_V2_FUNCTION_PROPERTY_AGG_DISTINCT_DEPENDENT_YES; +} + +} // namespace + +//---------------------------------------------------------------------------------------------------------------------- +// Statistics +//---------------------------------------------------------------------------------------------------------------------- + +Stats::Stats(void *impl) : detail::Handle(impl) { +} + +auto Stats::CanHaveNull() const -> bool { + bool result = false; + CheckedAPICall(duckdb_v2_stats_can_have_null, handle(), &result); + return result; +} + +auto Stats::CanHaveValid() const -> bool { + bool result = false; + CheckedAPICall(duckdb_v2_stats_can_have_valid, handle(), &result); + return result; +} + +auto Stats::SetCanHaveNull(bool value) -> void { + CheckedAPICall(duckdb_v2_stats_set_can_have_null, handle(), value); +} + +auto Stats::SetCanHaveValid(bool value) -> void { + CheckedAPICall(duckdb_v2_stats_set_can_have_valid, handle(), value); +} + +auto Stats::GetValue() const -> Value { + duckdb_v2_value_handle out = nullptr; + CheckedAPICall(duckdb_v2_stats_get_value, handle(), &out); + return detail::HandleFactory::Make(out); +} + +auto Stats::SetValue(const Value &value) -> void { + CheckedAPICall(duckdb_v2_stats_set_value, handle(), value.handle()); +} + +//---------------------------------------------------------------------------------------------------------------------- +// Scalar Function +//---------------------------------------------------------------------------------------------------------------------- + +namespace { + +// The callback table for one registered scalar function: rides the C user_data +// slot so the trampolines can find it; the user's own slot (SetUserData) rides +// inside it. Owned by the registered function, freed at engine teardown. +struct ScalarFunctionInfo { + ScalarFunction::ResolveTypesCallback resolve_types_callback = nullptr; + ScalarFunction::BindCallback bind_callback = nullptr; + ScalarFunction::InitCallback init_callback = nullptr; + ScalarFunction::ExecCallback exec_callback = nullptr; + ScalarFunction::StatsCallback stats_callback = nullptr; + detail::UserData user_data; + + ScalarFunctionInfo(ScalarFunction::ResolveTypesCallback resolve_types_callback, + ScalarFunction::BindCallback bind_callback, ScalarFunction::InitCallback init_callback, + ScalarFunction::ExecCallback exec_callback, ScalarFunction::StatsCallback stats_callback, + detail::UserData user_data) + : resolve_types_callback(resolve_types_callback), bind_callback(bind_callback), init_callback(init_callback), + exec_callback(exec_callback), stats_callback(stats_callback), user_data(std::move(user_data)) { + } + + bool operator==(const ScalarFunctionInfo &other) const { + return resolve_types_callback == other.resolve_types_callback && bind_callback == other.bind_callback && + init_callback == other.init_callback && exec_callback == other.exec_callback && + stats_callback == other.stats_callback && user_data.get() == other.user_data.get(); + } +}; + +// Guard for the inputs' GetUserData: a clear error instead of a null deref. +void *RequireUserData(const detail::UserData &user_data) { + auto ptr = user_data.get(); + if (!ptr) { + throw InvalidInputException("no user data was set; call ScalarFunction::SetUserData before Register"); + } + return ptr; +} + +// Guard for the inputs' GetBindData: a clear error instead of a null deref. +void *RequireBindData(void *ptr) { + if (!ptr) { + throw InvalidInputException("no bind data was set; call BindInput::SetBindData in the bind callback"); + } + return ptr; +} + +// Guard for ExecInput::GetInitData: a clear error instead of a null deref. +void *RequireInitData(void *ptr) { + if (!ptr) { + throw InvalidInputException("no init data was set; call InitInput::SetInitData in the init callback"); + } + return ptr; +} + +} // namespace + +ScalarFunction::ScalarFunction(void *impl) : detail::Handle(impl) { +} + +ScalarFunction::~ScalarFunction() { + auto _h = handle(); + duckdb_v2_scalar_function_destroy(&_h); +} + +auto ScalarFunction::Create(Factory &factory) -> ScalarFunction { + duckdb_v2_scalar_function_handle _h = nullptr; + CheckedAPICall(duckdb_v2_scalar_function_create, factory.handle(), &_h); + return detail::HandleFactory::Make(_h); +} + +auto ScalarFunction::SetName(const std::string &name) & -> ScalarFunction & { + auto view = ToStr(name); + CheckedAPICall(duckdb_v2_scalar_function_set_name, handle(), view.data(), view.size()); + return *this; +} + +auto ScalarFunction::SetSchema(const std::string &schema) & -> ScalarFunction & { + auto view = ToStr(schema); + CheckedAPICall(duckdb_v2_scalar_function_set_schema, handle(), view.data(), view.size()); + return *this; +} + +auto ScalarFunction::GetDocs() -> FunctionDocs { + duckdb_v2_function_docs_handle docs = nullptr; + CheckedAPICall(duckdb_v2_scalar_function_get_docs, handle(), &docs); + return detail::HandleFactory::Make(docs); +} + +auto ScalarFunction::GetSignature() -> FunctionSignature { + duckdb_v2_function_signature_handle sig = nullptr; + CheckedAPICall(duckdb_v2_scalar_function_get_signature, handle(), &sig); + return detail::HandleFactory::Make(sig); +} + +auto ScalarFunction::SetUserDataInternal(void *data, void (*destructor)(void *)) -> void { + user_data = detail::UserData(data, destructor); +} + +auto ScalarFunction::SetResolveTypesCallback(ResolveTypesCallback callback) & -> ScalarFunction & { + if (!callback) { + CheckedAPICall(duckdb_v2_scalar_function_set_resolve_types_callback, handle(), nullptr); + resolve_types_callback = nullptr; + return *this; + } + + // The C-side callback is one shared trampoline; the user's callback is looked + // up through the info table riding the user_data slot (set by Register). + static auto trampoline = [](duckdb_v2_function_bind_info_handle info, + duckdb_v2_scalar_function_resolve_types_info_handle result, + duckdb_v2_context_handle context, duckdb_v2_error_info_handle *err) { + WithExceptionGuard(err, [&]() { + void *user_data = nullptr; + CheckedAPICall(duckdb_v2_function_bind_get_user_data, info, &user_data); + const auto &function = *static_cast(user_data); + + auto input = detail::HandleFactory::Make( + static_cast(info), static_cast(result), static_cast(context)); + function.resolve_types_callback(input); + }); + }; + + CheckedAPICall(duckdb_v2_scalar_function_set_resolve_types_callback, handle(), trampoline); + resolve_types_callback = callback; + return *this; +} + +auto ScalarFunction::SetBindCallback(BindCallback callback) & -> ScalarFunction & { + if (!callback) { + CheckedAPICall(duckdb_v2_scalar_function_set_bind_callback, handle(), nullptr); + bind_callback = nullptr; + return *this; + } + + // The C-side callback is one shared trampoline; the user's callback is looked + // up through the info table riding the user_data slot (set by Register). + static auto trampoline = [](duckdb_v2_function_bind_info_handle info, + duckdb_v2_scalar_function_bind_info_handle result, duckdb_v2_context_handle context, + duckdb_v2_error_info_handle *err) { + WithExceptionGuard(err, [&]() { + void *user_data = nullptr; + CheckedAPICall(duckdb_v2_function_bind_get_user_data, info, &user_data); + const auto &function = *static_cast(user_data); + + auto input = detail::HandleFactory::Make(static_cast(info), static_cast(result), + static_cast(context)); + function.bind_callback(input); + }); + }; + + CheckedAPICall(duckdb_v2_scalar_function_set_bind_callback, handle(), trampoline); + bind_callback = callback; + return *this; +} + +auto ScalarFunction::SetInitCallback(InitCallback callback) & -> ScalarFunction & { + if (!callback) { + CheckedAPICall(duckdb_v2_scalar_function_set_init_callback, handle(), nullptr); + init_callback = nullptr; + return *this; + } + + static auto trampoline = [](duckdb_v2_scalar_function_init_info_handle info, duckdb_v2_context_handle context, + duckdb_v2_error_info_handle *err) { + WithExceptionGuard(err, [&]() { + void *user_data = nullptr; + CheckedAPICall(duckdb_v2_scalar_function_init_get_user_data, info, &user_data); + const auto &function = *static_cast(user_data); + + auto input = + detail::HandleFactory::Make(static_cast(info), static_cast(context)); + function.init_callback(input); + }); + }; + + CheckedAPICall(duckdb_v2_scalar_function_set_init_callback, handle(), trampoline); + init_callback = callback; + return *this; +} + +auto ScalarFunction::SetExecCallback(ExecCallback callback) & -> ScalarFunction & { + if (!callback) { + CheckedAPICall(duckdb_v2_scalar_function_set_exec_callback, handle(), nullptr); + exec_callback = nullptr; + return *this; + } + + static auto trampoline = [](duckdb_v2_scalar_function_exec_info_handle info, duckdb_v2_context_handle context, + duckdb_v2_error_info_handle *err) { + WithExceptionGuard(err, [&]() { + void *user_data = nullptr; + CheckedAPICall(duckdb_v2_scalar_function_exec_get_user_data, info, &user_data); + const auto &function = *static_cast(user_data); + + auto input = + detail::HandleFactory::Make(static_cast(info), static_cast(context)); + function.exec_callback(input); + }); + }; + + CheckedAPICall(duckdb_v2_scalar_function_set_exec_callback, handle(), trampoline); + exec_callback = callback; + return *this; +} + +auto ScalarFunction::SetStatsCallback(StatsCallback callback) & -> ScalarFunction & { + if (!callback) { + CheckedAPICall(duckdb_v2_scalar_function_set_stats_callback, handle(), nullptr); + stats_callback = nullptr; + return *this; + } + + static auto trampoline = [](duckdb_v2_scalar_function_stats_info_handle info, duckdb_v2_context_handle context, + duckdb_v2_error_info_handle *err) { + WithExceptionGuard(err, [&]() { + void *user_data = nullptr; + CheckedAPICall(duckdb_v2_scalar_function_stats_get_user_data, info, &user_data); + const auto &function = *static_cast(user_data); + + auto input = + detail::HandleFactory::Make(static_cast(info), static_cast(context)); + function.stats_callback(input); + }); + }; + + CheckedAPICall(duckdb_v2_scalar_function_set_stats_callback, handle(), trampoline); + stats_callback = callback; + return *this; +} + +auto ScalarFunction::SetStability(FunctionStability value) & -> ScalarFunction & { + CheckedAPICall(duckdb_v2_scalar_function_set_property, handle(), DUCKDB_V2_FUNCTION_PROPERTY_STABILITY, + ToCValue(value)); + return *this; +} + +auto ScalarFunction::SetNullHandling(FunctionNullHandling value) & -> ScalarFunction & { + CheckedAPICall(duckdb_v2_scalar_function_set_property, handle(), DUCKDB_V2_FUNCTION_PROPERTY_NULL_HANDLING, + ToCValue(value)); + return *this; +} + +auto ScalarFunction::SetFallibility(FunctionFallibility value) & -> ScalarFunction & { + CheckedAPICall(duckdb_v2_scalar_function_set_property, handle(), DUCKDB_V2_FUNCTION_PROPERTY_FALLIBILITY, + ToCValue(value)); + return *this; +} + +auto ScalarFunction::SetCollationHandling(FunctionCollationHandling value) & -> ScalarFunction & { + CheckedAPICall(duckdb_v2_scalar_function_set_property, handle(), DUCKDB_V2_FUNCTION_PROPERTY_COLLATION_HANDLING, + ToCValue(value)); + return *this; +} + +auto ScalarFunction::PrepareRegistration() -> void { + // The callback table rides the C user_data slot so the trampolines can find + // it; the user's own data (SetUserData, moved out here) rides inside it. + auto info = std::unique_ptr(new ScalarFunctionInfo( + resolve_types_callback, bind_callback, init_callback, exec_callback, stats_callback, std::move(user_data))); + duckdb_v2_opaque opaque {info.get(), detail::TypedDelete, + detail::TypedEquals}; + CheckedAPICall(duckdb_v2_scalar_function_set_user_data, handle(), &opaque); + // The function owns the table now. + info.release(); // NOLINT(bugprone-unused-return-value) +} + +void *ScalarFunction::ResolveTypesInput::GetUserDataInternal() const { + const auto &function = *static_cast(GetFunctionInfo()); + return RequireUserData(function.user_data); +} + +auto ScalarFunction::ResolveTypesInput::SetReturnType(const LogicalType &type) -> void { + CheckedAPICall(duckdb_v2_scalar_function_resolve_types_set_return_type, + static_cast(result), type.handle()); +} + +void ScalarFunction::BindInput::SetBindDataInternal(void *data, bool (*equals)(void *a, void *b), + void (*destructor)(void *)) { + duckdb_v2_opaque opaque {data, destructor, equals}; + CheckedAPICall(duckdb_v2_scalar_function_bind_set_bind_data, + static_cast(result), &opaque); +} + +void *ScalarFunction::BindInput::GetUserDataInternal() const { + const auto &function = *static_cast(GetFunctionInfo()); + return RequireUserData(function.user_data); +} + +void *ScalarFunction::InitInput::GetBindDataInternal() const { + void *bind_data = nullptr; + CheckedAPICall(duckdb_v2_scalar_function_init_get_bind_data, + static_cast(args), &bind_data); + return RequireBindData(bind_data); +} + +void ScalarFunction::InitInput::SetInitDataInternal(void *data, void (*destructor)(void *)) { + duckdb_v2_opaque opaque {data, destructor, nullptr}; + CheckedAPICall(duckdb_v2_scalar_function_init_set_init_data, + static_cast(args), &opaque); +} + +void *ScalarFunction::InitInput::GetUserDataInternal() const { + void *user_data = nullptr; + CheckedAPICall(duckdb_v2_scalar_function_init_get_user_data, + static_cast(args), &user_data); + const auto &function = *static_cast(user_data); + return RequireUserData(function.user_data); +} + +auto ScalarFunction::InitInput::GetContext() -> Context & { + return context; +} + +void *ScalarFunction::ExecInput::GetBindDataInternal() const { + void *bind_data = nullptr; + CheckedAPICall(duckdb_v2_scalar_function_exec_get_bind_data, + static_cast(args), &bind_data); + return RequireBindData(bind_data); +} + +void *ScalarFunction::ExecInput::GetInitDataInternal() const { + void *init_data = nullptr; + CheckedAPICall(duckdb_v2_scalar_function_exec_get_init_data, + static_cast(args), &init_data); + return RequireInitData(init_data); +} + +void *ScalarFunction::ExecInput::GetUserDataInternal() const { + void *user_data = nullptr; + CheckedAPICall(duckdb_v2_scalar_function_exec_get_user_data, + static_cast(args), &user_data); + const auto &function = *static_cast(user_data); + return RequireUserData(function.user_data); +} + +auto ScalarFunction::ExecInput::GetRowCount() const -> idx_t { + idx_t count = 0; + CheckedAPICall(duckdb_v2_scalar_function_exec_get_row_count, + static_cast(args), &count); + return count; +} + +auto ScalarFunction::ExecInput::GetArgumentCounts() const -> ArgumentCounts { + idx_t counts[4] = {}; + CheckedAPICall(duckdb_v2_scalar_function_exec_get_arg_count, + static_cast(args), &counts[0], &counts[1], &counts[2], + &counts[3]); + return ToArgumentCounts(counts[0], counts[1], counts[2], counts[3]); +} + +auto ScalarFunction::ExecInput::GetArgCount() const -> idx_t { + return GetArgumentCounts().Total(); +} + +auto ScalarFunction::ExecInput::GetArg(idx_t index) const -> Vector { + duckdb_v2_vector_handle vector = nullptr; + CheckedAPICall(duckdb_v2_scalar_function_exec_get_arg, + static_cast(args), index, &vector); + return detail::HandleFactory::Make(vector); +} + +auto ScalarFunction::ExecInput::GetResult() const -> Vector { + duckdb_v2_vector_handle vector = nullptr; + CheckedAPICall(duckdb_v2_scalar_function_exec_get_result, + static_cast(args), &vector); + return detail::HandleFactory::Make(vector); +} + +auto ScalarFunction::ExecInput::GetContext() -> Context & { + return context; +} + +void *ScalarFunction::StatsInput::GetBindDataInternal() const { + void *bind_data = nullptr; + CheckedAPICall(duckdb_v2_scalar_function_stats_get_bind_data, + static_cast(args), &bind_data); + return RequireBindData(bind_data); +} + +void *ScalarFunction::StatsInput::GetUserDataInternal() const { + void *user_data = nullptr; + CheckedAPICall(duckdb_v2_scalar_function_stats_get_user_data, + static_cast(args), &user_data); + const auto &function = *static_cast(user_data); + return RequireUserData(function.user_data); +} + +auto ScalarFunction::StatsInput::GetArgumentCounts() const -> ArgumentCounts { + idx_t counts[4] = {}; + CheckedAPICall(duckdb_v2_scalar_function_stats_get_arg_count, + static_cast(args), &counts[0], &counts[1], &counts[2], + &counts[3]); + return ToArgumentCounts(counts[0], counts[1], counts[2], counts[3]); +} + +auto ScalarFunction::StatsInput::GetArgCount() const -> idx_t { + return GetArgumentCounts().Total(); +} + +auto ScalarFunction::StatsInput::GetArgStats(idx_t index) const -> Stats { + duckdb_v2_stats_handle stats = nullptr; + CheckedAPICall(duckdb_v2_scalar_function_stats_get_arg_stats, + static_cast(args), index, &stats); + return detail::HandleFactory::Make(stats); +} + +auto ScalarFunction::StatsInput::GetResultStats() const -> Stats { + duckdb_v2_stats_handle stats = nullptr; + CheckedAPICall(duckdb_v2_scalar_function_stats_get_result_stats, + static_cast(args), &stats); + return detail::HandleFactory::Make(stats); +} + +auto ScalarFunction::StatsInput::GetContext() -> Context & { + return context; +} + +//---------------------------------------------------------------------------------------------------------------------- +// Aggregate Function +//---------------------------------------------------------------------------------------------------------------------- + +namespace { + +// The callback table for one registered aggregate function: rides the C +// user_data slot so the trampolines can find it; the user's own slot +// (SetUserData) rides inside it. Owned by the registered function, freed at +// engine teardown. +struct AggregateFunctionInfo { + AggregateFunction::BindCallback bind_callback = nullptr; + AggregateFunction::SizeCallback size_callback = nullptr; + AggregateFunction::InitCallback init_callback = nullptr; + AggregateFunction::UpdateCallback update_callback = nullptr; + AggregateFunction::CombineCallback combine_callback = nullptr; + AggregateFunction::FinalizeCallback finalize_callback = nullptr; + AggregateFunction::DestroyCallback destroy_callback = nullptr; + AggregateFunction::StatsCallback stats_callback = nullptr; + detail::UserData user_data; + + AggregateFunctionInfo(AggregateFunction::BindCallback bind_callback, AggregateFunction::SizeCallback size_callback, + AggregateFunction::InitCallback init_callback, + AggregateFunction::UpdateCallback update_callback, + AggregateFunction::CombineCallback combine_callback, + AggregateFunction::FinalizeCallback finalize_callback, + AggregateFunction::DestroyCallback destroy_callback, + AggregateFunction::StatsCallback stats_callback, detail::UserData user_data) + : bind_callback(bind_callback), size_callback(size_callback), init_callback(init_callback), + update_callback(update_callback), combine_callback(combine_callback), finalize_callback(finalize_callback), + destroy_callback(destroy_callback), stats_callback(stats_callback), user_data(std::move(user_data)) { + } + + bool operator==(const AggregateFunctionInfo &other) const { + return bind_callback == other.bind_callback && size_callback == other.size_callback && + init_callback == other.init_callback && update_callback == other.update_callback && + combine_callback == other.combine_callback && finalize_callback == other.finalize_callback && + destroy_callback == other.destroy_callback && stats_callback == other.stats_callback && + user_data.get() == other.user_data.get(); + } +}; + +// Guard for the inputs' GetUserData: a clear error instead of a null deref. +void *RequireAggregateUserData(const detail::UserData &user_data) { + auto ptr = user_data.get(); + if (!ptr) { + throw InvalidInputException("no user data was set; call AggregateFunction::SetUserData before Register"); + } + return ptr; +} + +// Guard for the inputs' GetBindData: a clear error instead of a null deref. +void *RequireAggregateBindData(void *ptr) { + if (!ptr) { + throw InvalidInputException("no bind data was set; call BindInput::SetBindData in the bind callback"); + } + return ptr; +} + +} // namespace + +AggregateFunction::AggregateFunction(void *impl) : detail::Handle(impl) { +} + +AggregateFunction::~AggregateFunction() { + auto _h = handle(); + duckdb_v2_aggregate_function_destroy(&_h); +} + +auto AggregateFunction::Create(Factory &factory) -> AggregateFunction { + duckdb_v2_aggregate_function_handle _h = nullptr; + CheckedAPICall(duckdb_v2_aggregate_function_create, factory.handle(), &_h); + return detail::HandleFactory::Make(_h); +} + +auto AggregateFunction::SetName(const std::string &name) & -> AggregateFunction & { + auto view = ToStr(name); + CheckedAPICall(duckdb_v2_aggregate_function_set_name, handle(), view.data(), view.size()); + return *this; +} + +auto AggregateFunction::GetDocs() -> FunctionDocs { + duckdb_v2_function_docs_handle docs = nullptr; + CheckedAPICall(duckdb_v2_aggregate_function_get_docs, handle(), &docs); + return detail::HandleFactory::Make(docs); +} + +auto AggregateFunction::GetSignature() -> FunctionSignature { + duckdb_v2_function_signature_handle sig = nullptr; + CheckedAPICall(duckdb_v2_aggregate_function_get_signature, handle(), &sig); + return detail::HandleFactory::Make(sig); +} + +auto AggregateFunction::SetUserDataInternal(void *data, void (*destructor)(void *)) -> void { + user_data = detail::UserData(data, destructor); +} + +auto AggregateFunction::SetBindCallback(BindCallback callback) & -> AggregateFunction & { + if (!callback) { + CheckedAPICall(duckdb_v2_aggregate_function_set_bind_callback, handle(), nullptr); + bind_callback = nullptr; + return *this; + } + + // The C-side callback is one shared trampoline; the user's callback is looked + // up through the info table riding the user_data slot (set by Register). + static auto trampoline = [](duckdb_v2_function_bind_info_handle info, + duckdb_v2_aggregate_function_bind_info_handle result, duckdb_v2_context_handle context, + duckdb_v2_error_info_handle *err) { + WithExceptionGuard(err, [&]() { + void *user_data = nullptr; + CheckedAPICall(duckdb_v2_function_bind_get_user_data, info, &user_data); + const auto &function = *static_cast(user_data); + + auto input = detail::HandleFactory::Make(static_cast(info), static_cast(result), + static_cast(context)); + function.bind_callback(input); + }); + }; + + CheckedAPICall(duckdb_v2_aggregate_function_set_bind_callback, handle(), trampoline); + bind_callback = callback; + return *this; +} + +auto AggregateFunction::SetSizeCallback(SizeCallback callback) & -> AggregateFunction & { + if (!callback) { + CheckedAPICall(duckdb_v2_aggregate_function_set_size_callback, handle(), nullptr); + size_callback = nullptr; + return *this; + } + + static auto trampoline = [](duckdb_v2_aggregate_function_size_info_handle info, duckdb_v2_error_info_handle *err) { + WithExceptionGuard(err, [&]() { + void *user_data = nullptr; + CheckedAPICall(duckdb_v2_aggregate_function_size_get_user_data, info, &user_data); + const auto &function = *static_cast(user_data); + + auto input = detail::HandleFactory::Make(static_cast(info)); + function.size_callback(input); + }); + }; + + CheckedAPICall(duckdb_v2_aggregate_function_set_size_callback, handle(), trampoline); + size_callback = callback; + return *this; +} + +auto AggregateFunction::SetInitCallback(InitCallback callback) & -> AggregateFunction & { + if (!callback) { + CheckedAPICall(duckdb_v2_aggregate_function_set_init_callback, handle(), nullptr); + init_callback = nullptr; + return *this; + } + + static auto trampoline = [](duckdb_v2_aggregate_function_init_info_handle info, duckdb_v2_error_info_handle *err) { + WithExceptionGuard(err, [&]() { + void *user_data = nullptr; + CheckedAPICall(duckdb_v2_aggregate_function_init_get_user_data, info, &user_data); + const auto &function = *static_cast(user_data); + + auto input = detail::HandleFactory::Make(static_cast(info)); + function.init_callback(input); + }); + }; + + CheckedAPICall(duckdb_v2_aggregate_function_set_init_callback, handle(), trampoline); + init_callback = callback; + return *this; +} + +auto AggregateFunction::SetUpdateCallback(UpdateCallback callback) & -> AggregateFunction & { + if (!callback) { + CheckedAPICall(duckdb_v2_aggregate_function_set_update_callback, handle(), nullptr); + update_callback = nullptr; + return *this; + } + + static auto trampoline = [](duckdb_v2_aggregate_function_update_info_handle info, + duckdb_v2_error_info_handle *err) { + WithExceptionGuard(err, [&]() { + void *user_data = nullptr; + CheckedAPICall(duckdb_v2_aggregate_function_update_get_user_data, info, &user_data); + const auto &function = *static_cast(user_data); + + auto input = detail::HandleFactory::Make(static_cast(info)); + function.update_callback(input); + }); + }; + + CheckedAPICall(duckdb_v2_aggregate_function_set_update_callback, handle(), trampoline); + update_callback = callback; + return *this; +} + +auto AggregateFunction::SetCombineCallback(CombineCallback callback) & -> AggregateFunction & { + if (!callback) { + CheckedAPICall(duckdb_v2_aggregate_function_set_combine_callback, handle(), nullptr); + combine_callback = nullptr; + return *this; + } + + static auto trampoline = [](duckdb_v2_aggregate_function_combine_info_handle info, + duckdb_v2_error_info_handle *err) { + WithExceptionGuard(err, [&]() { + void *user_data = nullptr; + CheckedAPICall(duckdb_v2_aggregate_function_combine_get_user_data, info, &user_data); + const auto &function = *static_cast(user_data); + + auto input = detail::HandleFactory::Make(static_cast(info)); + function.combine_callback(input); + }); + }; + + CheckedAPICall(duckdb_v2_aggregate_function_set_combine_callback, handle(), trampoline); + combine_callback = callback; + return *this; +} + +auto AggregateFunction::SetFinalizeCallback(FinalizeCallback callback) & -> AggregateFunction & { + if (!callback) { + CheckedAPICall(duckdb_v2_aggregate_function_set_finalize_callback, handle(), nullptr); + finalize_callback = nullptr; + return *this; + } + + static auto trampoline = [](duckdb_v2_aggregate_function_finalize_info_handle info, + duckdb_v2_error_info_handle *err) { + WithExceptionGuard(err, [&]() { + void *user_data = nullptr; + CheckedAPICall(duckdb_v2_aggregate_function_finalize_get_user_data, info, &user_data); + const auto &function = *static_cast(user_data); + + auto input = detail::HandleFactory::Make(static_cast(info)); + function.finalize_callback(input); + }); + }; + + CheckedAPICall(duckdb_v2_aggregate_function_set_finalize_callback, handle(), trampoline); + finalize_callback = callback; + return *this; +} + +auto AggregateFunction::SetDestroyCallback(DestroyCallback callback) & -> AggregateFunction & { + if (!callback) { + CheckedAPICall(duckdb_v2_aggregate_function_set_destroy_callback, handle(), nullptr); + destroy_callback = nullptr; + return *this; + } + + static auto trampoline = [](duckdb_v2_aggregate_function_destroy_info_handle info, + duckdb_v2_error_info_handle *err) { + WithExceptionGuard(err, [&]() { + void *user_data = nullptr; + CheckedAPICall(duckdb_v2_aggregate_function_destroy_get_user_data, info, &user_data); + const auto &function = *static_cast(user_data); + + auto input = detail::HandleFactory::Make(static_cast(info)); + function.destroy_callback(input); + }); + }; + + CheckedAPICall(duckdb_v2_aggregate_function_set_destroy_callback, handle(), trampoline); + destroy_callback = callback; + return *this; +} + +auto AggregateFunction::SetStatsCallback(StatsCallback callback) & -> AggregateFunction & { + if (!callback) { + CheckedAPICall(duckdb_v2_aggregate_function_set_stats_callback, handle(), nullptr); + stats_callback = nullptr; + return *this; + } + + static auto trampoline = [](duckdb_v2_aggregate_function_stats_info_handle info, duckdb_v2_context_handle context, + duckdb_v2_error_info_handle *err) { + WithExceptionGuard(err, [&]() { + void *user_data = nullptr; + CheckedAPICall(duckdb_v2_aggregate_function_stats_get_user_data, info, &user_data); + const auto &function = *static_cast(user_data); + + auto input = + detail::HandleFactory::Make(static_cast(info), static_cast(context)); + function.stats_callback(input); + }); + }; + + CheckedAPICall(duckdb_v2_aggregate_function_set_stats_callback, handle(), trampoline); + stats_callback = callback; + return *this; +} + +auto AggregateFunction::SetStability(FunctionStability value) & -> AggregateFunction & { + CheckedAPICall(duckdb_v2_aggregate_function_set_property, handle(), DUCKDB_V2_FUNCTION_PROPERTY_STABILITY, + ToCValue(value)); + return *this; +} + +auto AggregateFunction::SetNullHandling(FunctionNullHandling value) & -> AggregateFunction & { + CheckedAPICall(duckdb_v2_aggregate_function_set_property, handle(), DUCKDB_V2_FUNCTION_PROPERTY_NULL_HANDLING, + ToCValue(value)); + return *this; +} + +auto AggregateFunction::SetFallibility(FunctionFallibility value) & -> AggregateFunction & { + CheckedAPICall(duckdb_v2_aggregate_function_set_property, handle(), DUCKDB_V2_FUNCTION_PROPERTY_FALLIBILITY, + ToCValue(value)); + return *this; +} + +auto AggregateFunction::SetCollationHandling(FunctionCollationHandling value) & -> AggregateFunction & { + CheckedAPICall(duckdb_v2_aggregate_function_set_property, handle(), DUCKDB_V2_FUNCTION_PROPERTY_COLLATION_HANDLING, + ToCValue(value)); + return *this; +} + +auto AggregateFunction::SetOrderDependence(OrderDependence value) & -> AggregateFunction & { + CheckedAPICall(duckdb_v2_aggregate_function_set_property, handle(), DUCKDB_V2_FUNCTION_PROPERTY_AGG_ORDER_DEPENDENT, + ToCValue(value)); + return *this; +} + +auto AggregateFunction::SetDistinctDependence(DistinctDependence value) & -> AggregateFunction & { + CheckedAPICall(duckdb_v2_aggregate_function_set_property, handle(), + DUCKDB_V2_FUNCTION_PROPERTY_AGG_DISTINCT_DEPENDENT, ToCValue(value)); + return *this; +} + +auto AggregateFunction::PrepareRegistration() -> void { + // The callback table rides the C user_data slot so the trampolines can find + // it; the user's own data (SetUserData, moved out here) rides inside it. + auto info = std::unique_ptr( + new AggregateFunctionInfo(bind_callback, size_callback, init_callback, update_callback, combine_callback, + finalize_callback, destroy_callback, stats_callback, std::move(user_data))); + duckdb_v2_opaque opaque {info.get(), detail::TypedDelete, + detail::TypedEquals}; + CheckedAPICall(duckdb_v2_aggregate_function_set_user_data, handle(), &opaque); + // The function owns the table now. + info.release(); // NOLINT(bugprone-unused-return-value) +} + +void *AggregateFunction::BindInput::GetUserDataInternal() const { + const auto &function = *static_cast(GetFunctionInfo()); + return RequireUserData(function.user_data); +} + +auto AggregateFunction::BindInput::SetReturnType(const LogicalType &type) -> void { + CheckedAPICall(duckdb_v2_aggregate_function_bind_set_return_type, + static_cast(result), type.handle()); +} + +void *AggregateFunction::SizeInput::GetBindDataInternal() const { + void *bind_data = nullptr; + CheckedAPICall(duckdb_v2_aggregate_function_size_get_bind_data, + static_cast(args), &bind_data); + return RequireAggregateBindData(bind_data); +} + +void *AggregateFunction::SizeInput::GetUserDataInternal() const { + void *user_data = nullptr; + CheckedAPICall(duckdb_v2_aggregate_function_size_get_user_data, + static_cast(args), &user_data); + const auto &function = *static_cast(user_data); + return RequireAggregateUserData(function.user_data); +} + +auto AggregateFunction::SizeInput::SetStateSize(idx_t size) -> void { + CheckedAPICall(duckdb_v2_aggregate_function_size_set_state_size, + static_cast(args), size); +} + +void *AggregateFunction::InitInput::GetBindDataInternal() const { + void *bind_data = nullptr; + CheckedAPICall(duckdb_v2_aggregate_function_init_get_bind_data, + static_cast(args), &bind_data); + return RequireAggregateBindData(bind_data); +} + +void *AggregateFunction::InitInput::GetUserDataInternal() const { + void *user_data = nullptr; + CheckedAPICall(duckdb_v2_aggregate_function_init_get_user_data, + static_cast(args), &user_data); + const auto &function = *static_cast(user_data); + return RequireAggregateUserData(function.user_data); +} + +auto AggregateFunction::InitInput::GetStateCount() const -> idx_t { + idx_t count = 0; + CheckedAPICall(duckdb_v2_aggregate_function_init_get_state_count, + static_cast(args), &count); + return count; +} + +auto AggregateFunction::InitInput::GetStates() const -> void ** { + void **states = nullptr; + CheckedAPICall(duckdb_v2_aggregate_function_init_get_states, + static_cast(args), &states); + return states; +} + +void *AggregateFunction::UpdateInput::GetBindDataInternal() const { + void *bind_data = nullptr; + CheckedAPICall(duckdb_v2_aggregate_function_update_get_bind_data, + static_cast(args), &bind_data); + return RequireAggregateBindData(bind_data); +} + +void *AggregateFunction::UpdateInput::GetUserDataInternal() const { + void *user_data = nullptr; + CheckedAPICall(duckdb_v2_aggregate_function_update_get_user_data, + static_cast(args), &user_data); + const auto &function = *static_cast(user_data); + return RequireAggregateUserData(function.user_data); +} + +auto AggregateFunction::UpdateInput::GetRowCount() const -> idx_t { + idx_t count = 0; + CheckedAPICall(duckdb_v2_aggregate_function_update_get_row_count, + static_cast(args), &count); + return count; +} + +auto AggregateFunction::UpdateInput::GetArgumentCounts() const -> ArgumentCounts { + idx_t counts[4] = {}; + CheckedAPICall(duckdb_v2_aggregate_function_update_get_arg_count, + static_cast(args), &counts[0], &counts[1], + &counts[2], &counts[3]); + return ToArgumentCounts(counts[0], counts[1], counts[2], counts[3]); +} + +auto AggregateFunction::UpdateInput::GetArgCount() const -> idx_t { + return GetArgumentCounts().Total(); +} + +auto AggregateFunction::UpdateInput::GetArg(idx_t index) const -> Vector { + duckdb_v2_vector_handle vector = nullptr; + CheckedAPICall(duckdb_v2_aggregate_function_update_get_arg, + static_cast(args), index, &vector); + return detail::HandleFactory::Make(vector); +} + +auto AggregateFunction::UpdateInput::GetStates() const -> void ** { + void **states = nullptr; + CheckedAPICall(duckdb_v2_aggregate_function_update_get_states, + static_cast(args), &states); + return states; +} + +void *AggregateFunction::CombineInput::GetBindDataInternal() const { + void *bind_data = nullptr; + CheckedAPICall(duckdb_v2_aggregate_function_combine_get_bind_data, + static_cast(args), &bind_data); + return RequireAggregateBindData(bind_data); +} + +void *AggregateFunction::CombineInput::GetUserDataInternal() const { + void *user_data = nullptr; + CheckedAPICall(duckdb_v2_aggregate_function_combine_get_user_data, + static_cast(args), &user_data); + const auto &function = *static_cast(user_data); + return RequireAggregateUserData(function.user_data); +} + +auto AggregateFunction::CombineInput::GetStateCount() const -> idx_t { + idx_t count = 0; + CheckedAPICall(duckdb_v2_aggregate_function_combine_get_state_count, + static_cast(args), &count); + return count; +} + +auto AggregateFunction::CombineInput::GetSources() const -> void ** { + void **states = nullptr; + CheckedAPICall(duckdb_v2_aggregate_function_combine_get_sources, + static_cast(args), &states); + return states; +} + +auto AggregateFunction::CombineInput::GetTargets() const -> void ** { + void **states = nullptr; + CheckedAPICall(duckdb_v2_aggregate_function_combine_get_targets, + static_cast(args), &states); + return states; +} + +void *AggregateFunction::FinalizeInput::GetBindDataInternal() const { + void *bind_data = nullptr; + CheckedAPICall(duckdb_v2_aggregate_function_finalize_get_bind_data, + static_cast(args), &bind_data); + return RequireAggregateBindData(bind_data); +} + +void *AggregateFunction::FinalizeInput::GetUserDataInternal() const { + void *user_data = nullptr; + CheckedAPICall(duckdb_v2_aggregate_function_finalize_get_user_data, + static_cast(args), &user_data); + const auto &function = *static_cast(user_data); + return RequireAggregateUserData(function.user_data); +} + +auto AggregateFunction::FinalizeInput::GetStateCount() const -> idx_t { + idx_t count = 0; + CheckedAPICall(duckdb_v2_aggregate_function_finalize_get_state_count, + static_cast(args), &count); + return count; +} + +auto AggregateFunction::FinalizeInput::GetStates() const -> void ** { + void **states = nullptr; + CheckedAPICall(duckdb_v2_aggregate_function_finalize_get_states, + static_cast(args), &states); + return states; +} + +auto AggregateFunction::FinalizeInput::GetResult() const -> Vector { + duckdb_v2_vector_handle vector = nullptr; + CheckedAPICall(duckdb_v2_aggregate_function_finalize_get_result, + static_cast(args), &vector); + return detail::HandleFactory::Make(vector); +} + +auto AggregateFunction::FinalizeInput::GetResultOffset() const -> idx_t { + idx_t offset = 0; + CheckedAPICall(duckdb_v2_aggregate_function_finalize_get_result_offset, + static_cast(args), &offset); + return offset; +} + +void *AggregateFunction::DestroyInput::GetBindDataInternal() const { + void *bind_data = nullptr; + CheckedAPICall(duckdb_v2_aggregate_function_destroy_get_bind_data, + static_cast(args), &bind_data); + return RequireAggregateBindData(bind_data); +} + +void *AggregateFunction::DestroyInput::GetUserDataInternal() const { + void *user_data = nullptr; + CheckedAPICall(duckdb_v2_aggregate_function_destroy_get_user_data, + static_cast(args), &user_data); + const auto &function = *static_cast(user_data); + return RequireAggregateUserData(function.user_data); +} + +auto AggregateFunction::DestroyInput::GetStateCount() const -> idx_t { + idx_t count = 0; + CheckedAPICall(duckdb_v2_aggregate_function_destroy_get_state_count, + static_cast(args), &count); + return count; +} + +auto AggregateFunction::DestroyInput::GetStates() const -> void ** { + void **states = nullptr; + CheckedAPICall(duckdb_v2_aggregate_function_destroy_get_states, + static_cast(args), &states); + return states; +} + +void *AggregateFunction::StatsInput::GetBindDataInternal() const { + void *bind_data = nullptr; + CheckedAPICall(duckdb_v2_aggregate_function_stats_get_bind_data, + static_cast(args), &bind_data); + return RequireAggregateBindData(bind_data); +} + +void *AggregateFunction::StatsInput::GetUserDataInternal() const { + void *user_data = nullptr; + CheckedAPICall(duckdb_v2_aggregate_function_stats_get_user_data, + static_cast(args), &user_data); + const auto &function = *static_cast(user_data); + return RequireAggregateUserData(function.user_data); +} + +auto AggregateFunction::StatsInput::GetArgumentCounts() const -> ArgumentCounts { + idx_t counts[4] = {}; + CheckedAPICall(duckdb_v2_aggregate_function_stats_get_arg_count, + static_cast(args), &counts[0], &counts[1], + &counts[2], &counts[3]); + return ToArgumentCounts(counts[0], counts[1], counts[2], counts[3]); +} + +auto AggregateFunction::StatsInput::GetArgCount() const -> idx_t { + return GetArgumentCounts().Total(); +} + +auto AggregateFunction::StatsInput::GetArgStats(idx_t index) const -> Stats { + duckdb_v2_stats_handle stats = nullptr; + CheckedAPICall(duckdb_v2_aggregate_function_stats_get_arg_stats, + static_cast(args), index, &stats); + return detail::HandleFactory::Make(stats); +} + +auto AggregateFunction::StatsInput::GetResultStats() const -> Stats { + duckdb_v2_stats_handle stats = nullptr; + CheckedAPICall(duckdb_v2_aggregate_function_stats_get_result_stats, + static_cast(args), &stats); + return detail::HandleFactory::Make(stats); +} + +auto AggregateFunction::StatsInput::GetContext() -> Context & { + return context; +} + +//---------------------------------------------------------------------------------------------------------------------- +// Table Function +//---------------------------------------------------------------------------------------------------------------------- + +namespace { + +// The callback table for one registered table function: rides the C user_data +// slot so the trampolines can find it; the user's own slot (SetUserData) rides +// inside it. Owned by the registered function, freed at engine teardown. +struct TableFunctionInfo { + TableFunction::BindCallback bind_callback = nullptr; + TableFunction::InitGlobalCallback init_global_callback = nullptr; + TableFunction::InitLocalCallback init_local_callback = nullptr; + TableFunction::ExecCallback exec_callback = nullptr; + TableFunction::ProgressCallback progress_callback = nullptr; + TableFunction::FilterPushdownCallback filter_pushdown_callback = nullptr; + TableFunction::PartitionDataCallback partition_data_callback = nullptr; + TableFunction::PartitioningCallback partitioning_callback = nullptr; + TableFunction::ClaimBatchCallback claim_batch_callback = nullptr; + TableFunction::GetBindInfoCallback get_bind_info_callback = nullptr; + TableFunction::StatsCallback stats_callback = nullptr; + TableFunction::MetricsCallback metrics_callback = nullptr; + TableFunction::ToStringCallback to_string_callback = nullptr; + detail::UserData user_data; + + TableFunctionInfo(TableFunction::BindCallback bind_callback, TableFunction::InitGlobalCallback init_global_callback, + TableFunction::InitLocalCallback init_local_callback, TableFunction::ExecCallback exec_callback, + TableFunction::ProgressCallback progress_callback, + TableFunction::FilterPushdownCallback filter_pushdown_callback, + TableFunction::PartitionDataCallback partition_data_callback, + TableFunction::PartitioningCallback partitioning_callback, + TableFunction::ClaimBatchCallback claim_batch_callback, + TableFunction::GetBindInfoCallback get_bind_info_callback, + TableFunction::StatsCallback stats_callback, TableFunction::MetricsCallback metrics_callback, + TableFunction::ToStringCallback to_string_callback, detail::UserData user_data) + : bind_callback(bind_callback), init_global_callback(init_global_callback), + init_local_callback(init_local_callback), exec_callback(exec_callback), progress_callback(progress_callback), + filter_pushdown_callback(filter_pushdown_callback), partition_data_callback(partition_data_callback), + partitioning_callback(partitioning_callback), claim_batch_callback(claim_batch_callback), + get_bind_info_callback(get_bind_info_callback), stats_callback(stats_callback), + metrics_callback(metrics_callback), to_string_callback(to_string_callback), user_data(std::move(user_data)) { + } + + bool operator==(const TableFunctionInfo &other) const { + return bind_callback == other.bind_callback && init_global_callback == other.init_global_callback && + init_local_callback == other.init_local_callback && exec_callback == other.exec_callback && + progress_callback == other.progress_callback && + filter_pushdown_callback == other.filter_pushdown_callback && + partition_data_callback == other.partition_data_callback && + partitioning_callback == other.partitioning_callback && + claim_batch_callback == other.claim_batch_callback && + get_bind_info_callback == other.get_bind_info_callback && stats_callback == other.stats_callback && + metrics_callback == other.metrics_callback && to_string_callback == other.to_string_callback && + user_data.get() == other.user_data.get(); + } +}; + +// Guard for the inputs' GetUserData: a clear error instead of a null deref. +void *RequireTableUserData(const detail::UserData &user_data) { + auto ptr = user_data.get(); + if (!ptr) { + throw InvalidInputException("no user data was set; call TableFunction::SetUserData before Register"); + } + return ptr; +} + +// Guard for the inputs' GetBindData: a clear error instead of a null deref. +void *RequireTableBindData(void *ptr) { + if (!ptr) { + throw InvalidInputException("no bind data was set; call BindInput::SetBindData in the bind callback"); + } + return ptr; +} + +// Guard for the inputs' GetGlobalState: a clear error instead of a null deref. +void *RequireGlobalState(void *ptr) { + if (!ptr) { + throw InvalidInputException( + "no global state was set; call InitGlobalInput::SetGlobalState in the global init callback"); + } + return ptr; +} + +// Guard for ExecInput::GetLocalState: a clear error instead of a null deref. +void *RequireLocalState(void *ptr) { + if (!ptr) { + throw InvalidInputException( + "no local state was set; call InitLocalInput::SetLocalState in the local init callback"); + } + return ptr; +} + +} // namespace + +TableFunction::TableFunction(void *impl) : detail::Handle(impl) { +} + +TableFunction::~TableFunction() { + auto _h = handle(); + duckdb_v2_table_function_destroy(&_h); +} + +auto TableFunction::Create(Factory &factory) -> TableFunction { + duckdb_v2_table_function_handle _h = nullptr; + CheckedAPICall(duckdb_v2_table_function_create, factory.handle(), &_h); + return detail::HandleFactory::Make(_h); +} + +auto TableFunction::SetName(const std::string &name) & -> TableFunction & { + auto view = ToStr(name); + CheckedAPICall(duckdb_v2_table_function_set_name, handle(), view.data(), view.size()); + return *this; +} + +auto TableFunction::GetDocs() -> FunctionDocs { + duckdb_v2_function_docs_handle docs = nullptr; + CheckedAPICall(duckdb_v2_table_function_get_docs, handle(), &docs); + return detail::HandleFactory::Make(docs); +} + +auto TableFunction::GetSignature() -> FunctionSignature { + duckdb_v2_function_signature_handle sig = nullptr; + CheckedAPICall(duckdb_v2_table_function_get_signature, handle(), &sig); + return detail::HandleFactory::Make(sig); +} + +auto TableFunction::SetUserDataInternal(void *data, void (*destructor)(void *)) -> void { + user_data = detail::UserData(data, destructor); +} + +auto TableFunction::SetBindCallback(BindCallback callback) & -> TableFunction & { + if (!callback) { + CheckedAPICall(duckdb_v2_table_function_set_bind_callback, handle(), nullptr); + bind_callback = nullptr; + return *this; + } + + // The C-side callback is one shared trampoline; the user's callback is looked + // up through the info table riding the user_data slot (set by Register). + static auto trampoline = [](duckdb_v2_function_bind_info_handle info, + duckdb_v2_table_function_bind_info_handle result, duckdb_v2_context_handle context, + duckdb_v2_error_info_handle *err) { + WithExceptionGuard(err, [&]() { + void *user_data = nullptr; + CheckedAPICall(duckdb_v2_function_bind_get_user_data, info, &user_data); + const auto &function = *static_cast(user_data); + + auto input = detail::HandleFactory::Make(static_cast(info), static_cast(result), + static_cast(context)); + function.bind_callback(input); + }); + }; + + CheckedAPICall(duckdb_v2_table_function_set_bind_callback, handle(), trampoline); + bind_callback = callback; + return *this; +} + +auto TableFunction::SetInitGlobalCallback(InitGlobalCallback callback) & -> TableFunction & { + if (!callback) { + CheckedAPICall(duckdb_v2_table_function_set_init_global_callback, handle(), nullptr); + init_global_callback = nullptr; + return *this; + } + + static auto trampoline = [](duckdb_v2_table_function_init_global_info_handle info, duckdb_v2_context_handle context, + duckdb_v2_error_info_handle *err) { + WithExceptionGuard(err, [&]() { + void *user_data = nullptr; + CheckedAPICall(duckdb_v2_table_function_init_global_get_user_data, info, &user_data); + const auto &function = *static_cast(user_data); + + auto input = + detail::HandleFactory::Make(static_cast(info), static_cast(context)); + function.init_global_callback(input); + }); + }; + + CheckedAPICall(duckdb_v2_table_function_set_init_global_callback, handle(), trampoline); + init_global_callback = callback; + return *this; +} + +auto TableFunction::SetInitLocalCallback(InitLocalCallback callback) & -> TableFunction & { + if (!callback) { + CheckedAPICall(duckdb_v2_table_function_set_init_local_callback, handle(), nullptr); + init_local_callback = nullptr; + return *this; + } + + static auto trampoline = [](duckdb_v2_table_function_init_local_info_handle info, duckdb_v2_context_handle context, + duckdb_v2_error_info_handle *err) { + WithExceptionGuard(err, [&]() { + void *user_data = nullptr; + CheckedAPICall(duckdb_v2_table_function_init_local_get_user_data, info, &user_data); + const auto &function = *static_cast(user_data); + + auto input = + detail::HandleFactory::Make(static_cast(info), static_cast(context)); + function.init_local_callback(input); + }); + }; + + CheckedAPICall(duckdb_v2_table_function_set_init_local_callback, handle(), trampoline); + init_local_callback = callback; + return *this; +} + +auto TableFunction::SetExecCallback(ExecCallback callback) & -> TableFunction & { + if (!callback) { + CheckedAPICall(duckdb_v2_table_function_set_exec_callback, handle(), nullptr); + exec_callback = nullptr; + return *this; + } + + static auto trampoline = [](duckdb_v2_table_function_exec_info_handle info, duckdb_v2_context_handle context, + duckdb_v2_error_info_handle *err) { + WithExceptionGuard(err, [&]() { + void *user_data = nullptr; + CheckedAPICall(duckdb_v2_table_function_exec_get_user_data, info, &user_data); + const auto &function = *static_cast(user_data); + + auto input = + detail::HandleFactory::Make(static_cast(info), static_cast(context)); + function.exec_callback(input); + }); + }; + + CheckedAPICall(duckdb_v2_table_function_set_exec_callback, handle(), trampoline); + exec_callback = callback; + return *this; +} + +auto TableFunction::SetProgressCallback(ProgressCallback callback) & -> TableFunction & { + if (!callback) { + CheckedAPICall(duckdb_v2_table_function_set_progress_callback, handle(), nullptr); + progress_callback = nullptr; + return *this; + } + + static auto trampoline = [](duckdb_v2_table_function_progress_info_handle info, duckdb_v2_context_handle context, + duckdb_v2_error_info_handle *err) { + WithExceptionGuard(err, [&]() { + void *user_data = nullptr; + CheckedAPICall(duckdb_v2_table_function_progress_get_user_data, info, &user_data); + const auto &function = *static_cast(user_data); + + auto input = + detail::HandleFactory::Make(static_cast(info), static_cast(context)); + function.progress_callback(input); + }); + }; + + CheckedAPICall(duckdb_v2_table_function_set_progress_callback, handle(), trampoline); + progress_callback = callback; + return *this; +} + +auto TableFunction::SetFilterPushdownCallback(FilterPushdownCallback callback) & -> TableFunction & { + if (!callback) { + CheckedAPICall(duckdb_v2_table_function_set_filter_pushdown_callback, handle(), nullptr); + filter_pushdown_callback = nullptr; + return *this; + } + + static auto trampoline = [](duckdb_v2_table_function_filter_pushdown_info_handle info, + duckdb_v2_context_handle context, duckdb_v2_error_info_handle *err) { + WithExceptionGuard(err, [&]() { + void *user_data = nullptr; + CheckedAPICall(duckdb_v2_table_function_filter_pushdown_get_user_data, info, &user_data); + const auto &function = *static_cast(user_data); + + auto input = detail::HandleFactory::Make(static_cast(info), + static_cast(context)); + function.filter_pushdown_callback(input); + }); + }; + + CheckedAPICall(duckdb_v2_table_function_set_filter_pushdown_callback, handle(), trampoline); + filter_pushdown_callback = callback; + return *this; +} + +auto TableFunction::SetPartitionDataCallback(PartitionDataCallback callback) & -> TableFunction & { + if (!callback) { + CheckedAPICall(duckdb_v2_table_function_set_partition_data_callback, handle(), nullptr); + partition_data_callback = nullptr; + return *this; + } + + static auto trampoline = [](duckdb_v2_table_function_partition_data_info_handle info, + duckdb_v2_context_handle context, duckdb_v2_error_info_handle *err) { + WithExceptionGuard(err, [&]() { + void *user_data = nullptr; + CheckedAPICall(duckdb_v2_table_function_partition_data_get_user_data, info, &user_data); + const auto &function = *static_cast(user_data); + + auto input = detail::HandleFactory::Make(static_cast(info), + static_cast(context)); + function.partition_data_callback(input); + }); + }; + + CheckedAPICall(duckdb_v2_table_function_set_partition_data_callback, handle(), trampoline); + partition_data_callback = callback; + return *this; +} + +auto TableFunction::SetPartitioningCallback(PartitioningCallback callback) & -> TableFunction & { + if (!callback) { + CheckedAPICall(duckdb_v2_table_function_set_partitioning_callback, handle(), nullptr); + partitioning_callback = nullptr; + return *this; + } + + static auto trampoline = [](duckdb_v2_table_function_partitioning_info_handle info, + duckdb_v2_context_handle context, duckdb_v2_error_info_handle *err) { + WithExceptionGuard(err, [&]() { + void *user_data = nullptr; + CheckedAPICall(duckdb_v2_table_function_partitioning_get_user_data, info, &user_data); + const auto &function = *static_cast(user_data); + + auto input = + detail::HandleFactory::Make(static_cast(info), static_cast(context)); + function.partitioning_callback(input); + }); + }; + + CheckedAPICall(duckdb_v2_table_function_set_partitioning_callback, handle(), trampoline); + partitioning_callback = callback; + return *this; +} + +auto TableFunction::SetClaimBatchCallback(ClaimBatchCallback callback) & -> TableFunction & { + if (!callback) { + CheckedAPICall(duckdb_v2_table_function_set_claim_batch_callback, handle(), nullptr); + claim_batch_callback = nullptr; + return *this; + } + + static auto trampoline = [](duckdb_v2_table_function_claim_batch_info_handle info, duckdb_v2_context_handle context, + duckdb_v2_error_info_handle *err) { + WithExceptionGuard(err, [&]() { + void *user_data = nullptr; + CheckedAPICall(duckdb_v2_table_function_claim_batch_get_user_data, info, &user_data); + const auto &function = *static_cast(user_data); + + auto input = + detail::HandleFactory::Make(static_cast(info), static_cast(context)); + function.claim_batch_callback(input); + }); + }; + + CheckedAPICall(duckdb_v2_table_function_set_claim_batch_callback, handle(), trampoline); + claim_batch_callback = callback; + return *this; +} + +auto TableFunction::SetGetBindInfoCallback(GetBindInfoCallback callback) & -> TableFunction & { + if (!callback) { + CheckedAPICall(duckdb_v2_table_function_set_get_bind_info_callback, handle(), nullptr); + get_bind_info_callback = nullptr; + return *this; + } + + static auto trampoline = [](duckdb_v2_table_function_get_bind_info_info_handle info, + duckdb_v2_context_handle context, duckdb_v2_error_info_handle *err) { + WithExceptionGuard(err, [&]() { + void *user_data = nullptr; + CheckedAPICall(duckdb_v2_table_function_get_bind_info_get_user_data, info, &user_data); + const auto &function = *static_cast(user_data); + + auto input = + detail::HandleFactory::Make(static_cast(info), static_cast(context)); + function.get_bind_info_callback(input); + }); + }; + + CheckedAPICall(duckdb_v2_table_function_set_get_bind_info_callback, handle(), trampoline); + get_bind_info_callback = callback; + return *this; +} + +auto TableFunction::SetStatsCallback(StatsCallback callback) & -> TableFunction & { + if (!callback) { + CheckedAPICall(duckdb_v2_table_function_set_stats_callback, handle(), nullptr); + stats_callback = nullptr; + return *this; + } + + static auto trampoline = [](duckdb_v2_table_function_stats_info_handle info, duckdb_v2_context_handle context, + duckdb_v2_error_info_handle *err) { + WithExceptionGuard(err, [&]() { + void *user_data = nullptr; + CheckedAPICall(duckdb_v2_table_function_stats_get_user_data, info, &user_data); + const auto &function = *static_cast(user_data); + + auto input = + detail::HandleFactory::Make(static_cast(info), static_cast(context)); + function.stats_callback(input); + }); + }; + + CheckedAPICall(duckdb_v2_table_function_set_stats_callback, handle(), trampoline); + stats_callback = callback; + return *this; +} + +auto TableFunction::SetProjectionPushdown(bool enable) & -> TableFunction & { + CheckedAPICall(duckdb_v2_table_function_set_projection_pushdown, handle(), enable); + return *this; +} + +static_assert(static_cast(TableFunction::VirtualColumn::FILE_ROW_NUMBER) == + DUCKDB_V2_TABLE_VIRTUAL_COLUMN_FILE_ROW_NUMBER, + "TableFunction::VirtualColumn::FILE_ROW_NUMBER mismatch"); + +auto TableFunction::GetVirtualColumn(idx_t column_index) -> VirtualColumn { + if (!IsVirtualColumn(column_index)) { + throw InvalidInputException("The column index " + std::to_string(column_index) + + " stands for a declared column, not a virtual one"); + } + switch (column_index - VIRTUAL_COLUMN_START) { + case DUCKDB_V2_TABLE_VIRTUAL_COLUMN_FILE_ROW_NUMBER: + return VirtualColumn::FILE_ROW_NUMBER; + default: + throw InvalidInputException("The column index " + std::to_string(column_index) + + " stands for an unknown virtual column"); + } +} + +auto TableFunction::AddVirtualColumn(VirtualColumn column) & -> TableFunction & { + CheckedAPICall(duckdb_v2_table_function_add_virtual_column, handle(), + static_cast(column)); + return *this; +} + +auto TableFunction::SetMetricsCallback(MetricsCallback callback) & -> TableFunction & { + if (!callback) { + CheckedAPICall(duckdb_v2_table_function_set_metrics_callback, handle(), nullptr); + metrics_callback = nullptr; + return *this; + } + + static auto trampoline = [](duckdb_v2_table_function_metrics_info_handle info, duckdb_v2_context_handle context, + duckdb_v2_error_info_handle *err) { + WithExceptionGuard(err, [&]() { + void *user_data = nullptr; + CheckedAPICall(duckdb_v2_table_function_metrics_get_user_data, info, &user_data); + const auto &function = *static_cast(user_data); + + auto input = + detail::HandleFactory::Make(static_cast(info), static_cast(context)); + function.metrics_callback(input); + }); + }; + + CheckedAPICall(duckdb_v2_table_function_set_metrics_callback, handle(), trampoline); + metrics_callback = callback; + return *this; +} + +auto TableFunction::SetToStringCallback(ToStringCallback callback) & -> TableFunction & { + if (!callback) { + CheckedAPICall(duckdb_v2_table_function_set_to_string_callback, handle(), nullptr); + to_string_callback = nullptr; + return *this; + } + + static auto trampoline = [](duckdb_v2_table_function_to_string_info_handle info, duckdb_v2_error_info_handle *err) { + WithExceptionGuard(err, [&]() { + void *user_data = nullptr; + CheckedAPICall(duckdb_v2_table_function_to_string_get_user_data, info, &user_data); + const auto &function = *static_cast(user_data); + + auto input = detail::HandleFactory::Make(static_cast(info)); + function.to_string_callback(input); + }); + }; + + CheckedAPICall(duckdb_v2_table_function_set_to_string_callback, handle(), trampoline); + to_string_callback = callback; + return *this; +} + +auto TableFunction::PrepareRegistration() -> void { + // The callback table rides the C user_data slot so the trampolines can find + // it; the user's own data (SetUserData, moved out here) rides inside it. + auto info = std::unique_ptr(new TableFunctionInfo( + bind_callback, init_global_callback, init_local_callback, exec_callback, progress_callback, + filter_pushdown_callback, partition_data_callback, partitioning_callback, claim_batch_callback, + get_bind_info_callback, stats_callback, metrics_callback, to_string_callback, std::move(user_data))); + duckdb_v2_opaque opaque {info.get(), detail::TypedDelete, + detail::TypedEquals}; + CheckedAPICall(duckdb_v2_table_function_set_user_data, handle(), &opaque); + // The function owns the table now. + info.release(); // NOLINT(bugprone-unused-return-value) +} + +auto TableFunction::BindInput::AddResultColumn(const std::string &name, const LogicalType &type) -> void { + auto name_str = std::string_view(name.data(), name.size()); + CheckedAPICall(duckdb_v2_table_function_bind_add_result_column, + static_cast(result), name_str.data(), name_str.size(), + type.handle()); +} + +void *TableFunction::BindInput::GetUserDataInternal() const { + const auto &function = *static_cast(GetFunctionInfo()); + return RequireUserData(function.user_data); +} + +auto TableFunction::BindInput::SetCardinality(idx_t cardinality, bool is_exact) -> void { + CheckedAPICall(duckdb_v2_table_function_bind_set_cardinality, + static_cast(result), cardinality, is_exact); +} + +static_assert(static_cast(OrderPreservation::NO_ORDER) == DUCKDB_V2_ORDER_PRESERVATION_NO_ORDER, + "OrderPreservation::NO_ORDER mismatch"); +static_assert(static_cast(OrderPreservation::INSERTION_ORDER) == DUCKDB_V2_ORDER_PRESERVATION_INSERTION_ORDER, + "OrderPreservation::INSERTION_ORDER mismatch"); +static_assert(static_cast(OrderPreservation::FIXED_ORDER) == DUCKDB_V2_ORDER_PRESERVATION_FIXED_ORDER, + "OrderPreservation::FIXED_ORDER mismatch"); + +auto TableFunction::BindInput::SetOrderPreservation(OrderPreservation order) -> void { + CheckedAPICall(duckdb_v2_table_function_bind_set_order_preservation, + static_cast(result), + static_cast(order)); +} + +void TableFunction::InitGlobalInput::SetGlobalStateInternal(void *data, void (*destructor)(void *)) { + duckdb_v2_opaque opaque {data, destructor, nullptr}; + CheckedAPICall(duckdb_v2_table_function_init_global_set_global_state, + static_cast(args), &opaque); +} + +void *TableFunction::InitGlobalInput::GetBindDataInternal() const { + void *bind_data = nullptr; + CheckedAPICall(duckdb_v2_table_function_init_global_get_bind_data, + static_cast(args), &bind_data); + return RequireTableBindData(bind_data); +} + +void *TableFunction::InitGlobalInput::GetUserDataInternal() const { + void *user_data = nullptr; + CheckedAPICall(duckdb_v2_table_function_init_global_get_user_data, + static_cast(args), &user_data); + const auto &function = *static_cast(user_data); + return RequireTableUserData(function.user_data); +} + +auto TableFunction::InitGlobalInput::SetMaxThreads(idx_t max_threads) -> void { + CheckedAPICall(duckdb_v2_table_function_init_global_set_max_threads, + static_cast(args), max_threads); +} + +auto TableFunction::InitGlobalInput::GetContext() -> Context & { + return context; +} + +auto TableFunction::InitGlobalInput::GetColumnCount() const -> idx_t { + idx_t count = 0; + CheckedAPICall(duckdb_v2_table_function_init_global_get_column_count, + static_cast(args), &count); + return count; +} + +auto TableFunction::InitGlobalInput::GetColumnIndex(idx_t index) const -> idx_t { + idx_t column_index = 0; + CheckedAPICall(duckdb_v2_table_function_init_global_get_column_index, + static_cast(args), index, &column_index); + return column_index; +} + +void TableFunction::InitLocalInput::SetLocalStateInternal(void *data, void (*destructor)(void *)) { + duckdb_v2_opaque opaque {data, destructor, nullptr}; + CheckedAPICall(duckdb_v2_table_function_init_local_set_local_state, + static_cast(args), &opaque); +} + +void *TableFunction::InitLocalInput::GetBindDataInternal() const { + void *bind_data = nullptr; + CheckedAPICall(duckdb_v2_table_function_init_local_get_bind_data, + static_cast(args), &bind_data); + return RequireTableBindData(bind_data); +} + +void *TableFunction::InitLocalInput::GetGlobalStateInternal() const { + void *global_state = nullptr; + CheckedAPICall(duckdb_v2_table_function_init_local_get_global_state, + static_cast(args), &global_state); + return RequireGlobalState(global_state); +} + +void *TableFunction::InitLocalInput::GetUserDataInternal() const { + void *user_data = nullptr; + CheckedAPICall(duckdb_v2_table_function_init_local_get_user_data, + static_cast(args), &user_data); + const auto &function = *static_cast(user_data); + return RequireTableUserData(function.user_data); +} + +auto TableFunction::InitLocalInput::GetContext() -> Context & { + return context; +} + +auto TableFunction::InitLocalInput::GetColumnCount() const -> idx_t { + idx_t count = 0; + CheckedAPICall(duckdb_v2_table_function_init_local_get_column_count, + static_cast(args), &count); + return count; +} + +auto TableFunction::InitLocalInput::GetColumnIndex(idx_t index) const -> idx_t { + idx_t column_index = 0; + CheckedAPICall(duckdb_v2_table_function_init_local_get_column_index, + static_cast(args), index, &column_index); + return column_index; +} + +void *TableFunction::ExecInput::GetBindDataInternal() const { + void *bind_data = nullptr; + CheckedAPICall(duckdb_v2_table_function_exec_get_bind_data, + static_cast(args), &bind_data); + return RequireTableBindData(bind_data); +} + +void *TableFunction::ExecInput::GetGlobalStateInternal() const { + void *global_state = nullptr; + CheckedAPICall(duckdb_v2_table_function_exec_get_global_state, + static_cast(args), &global_state); + return RequireGlobalState(global_state); +} + +void *TableFunction::ExecInput::GetLocalStateInternal() const { + void *local_state = nullptr; + CheckedAPICall(duckdb_v2_table_function_exec_get_local_state, + static_cast(args), &local_state); + return RequireLocalState(local_state); +} + +void *TableFunction::ExecInput::GetUserDataInternal() const { + void *user_data = nullptr; + CheckedAPICall(duckdb_v2_table_function_exec_get_user_data, + static_cast(args), &user_data); + const auto &function = *static_cast(user_data); + return RequireTableUserData(function.user_data); +} + +auto TableFunction::ExecInput::GetOutputChunk() const -> DataChunk { + duckdb_v2_data_chunk_handle chunk = nullptr; + CheckedAPICall(duckdb_v2_table_function_exec_get_output_chunk, + static_cast(args), &chunk); + // Borrowed: the engine owns the chunk and reuses it across invocations. + return detail::HandleFactory::Make(chunk, false); +} + +auto TableFunction::ExecInput::GetContext() -> Context & { + return context; +} + +auto TableFunction::ExecInput::GetColumnCount() const -> idx_t { + idx_t count = 0; + CheckedAPICall(duckdb_v2_table_function_exec_get_column_count, + static_cast(args), &count); + return count; +} + +auto TableFunction::ExecInput::GetColumnIndex(idx_t index) const -> idx_t { + idx_t column_index = 0; + CheckedAPICall(duckdb_v2_table_function_exec_get_column_index, + static_cast(args), index, &column_index); + return column_index; +} + +void *TableFunction::ProgressInput::GetBindDataInternal() const { + void *bind_data = nullptr; + CheckedAPICall(duckdb_v2_table_function_progress_get_bind_data, + static_cast(args), &bind_data); + return RequireTableBindData(bind_data); +} + +void *TableFunction::ProgressInput::GetGlobalStateInternal() const { + void *global_state = nullptr; + CheckedAPICall(duckdb_v2_table_function_progress_get_global_state, + static_cast(args), &global_state); + return RequireGlobalState(global_state); +} + +void *TableFunction::ProgressInput::TryGetGlobalStateInternal() const { + void *global_state = nullptr; + CheckedAPICall(duckdb_v2_table_function_progress_get_global_state, + static_cast(args), &global_state); + return global_state; +} + +void *TableFunction::ProgressInput::GetUserDataInternal() const { + void *user_data = nullptr; + CheckedAPICall(duckdb_v2_table_function_progress_get_user_data, + static_cast(args), &user_data); + const auto &function = *static_cast(user_data); + return RequireTableUserData(function.user_data); +} + +auto TableFunction::ProgressInput::SetProgress(double progress) -> void { + CheckedAPICall(duckdb_v2_table_function_progress_set_progress, + static_cast(args), progress); +} + +auto TableFunction::ProgressInput::GetContext() -> Context & { + return context; +} + +void *TableFunction::MetricsInput::GetBindDataInternal() const { + void *bind_data = nullptr; + CheckedAPICall(duckdb_v2_table_function_metrics_get_bind_data, + static_cast(args), &bind_data); + return RequireTableBindData(bind_data); +} + +void *TableFunction::MetricsInput::GetGlobalStateInternal() const { + void *global_state = nullptr; + CheckedAPICall(duckdb_v2_table_function_metrics_get_global_state, + static_cast(args), &global_state); + return global_state; +} + +void *TableFunction::MetricsInput::GetUserDataInternal() const { + void *user_data = nullptr; + CheckedAPICall(duckdb_v2_table_function_metrics_get_user_data, + static_cast(args), &user_data); + const auto &function = *static_cast(user_data); + return RequireTableUserData(function.user_data); +} + +auto TableFunction::MetricsInput::SetMetric(std::string_view name, uint64_t value) -> void { + CheckedAPICall(duckdb_v2_table_function_metrics_set, + static_cast(args), name.data(), name.size(), value); +} + +auto TableFunction::MetricsInput::GetContext() -> Context & { + return context; +} + +void *TableFunction::FilterPushdownInput::GetBindDataInternal() const { + void *bind_data = nullptr; + CheckedAPICall(duckdb_v2_table_function_filter_pushdown_get_bind_data, + static_cast(args), &bind_data); + return RequireTableBindData(bind_data); +} + +void *TableFunction::FilterPushdownInput::GetUserDataInternal() const { + void *user_data = nullptr; + CheckedAPICall(duckdb_v2_table_function_filter_pushdown_get_user_data, + static_cast(args), &user_data); + const auto &function = *static_cast(user_data); + return RequireTableUserData(function.user_data); +} + +auto TableFunction::FilterPushdownInput::GetFilterCount() const -> idx_t { + idx_t count = 0; + CheckedAPICall(duckdb_v2_table_function_filter_pushdown_get_filter_count, + static_cast(args), &count); + return count; +} + +auto TableFunction::FilterPushdownInput::GetFilter(idx_t index) const -> Expression { + duckdb_v2_expression_handle filter = nullptr; + CheckedAPICall(duckdb_v2_table_function_filter_pushdown_get_filter, + static_cast(args), index, &filter); + return detail::HandleFactory::Make(static_cast(filter)); +} + +auto TableFunction::FilterPushdownInput::Accept(idx_t index) -> void { + CheckedAPICall(duckdb_v2_table_function_filter_pushdown_accept, + static_cast(args), index); +} + +auto TableFunction::FilterPushdownInput::GetColumnCount() const -> idx_t { + idx_t count = 0; + CheckedAPICall(duckdb_v2_table_function_filter_pushdown_get_column_count, + static_cast(args), &count); + return count; +} + +auto TableFunction::FilterPushdownInput::GetColumnIndex(idx_t index) const -> idx_t { + idx_t column_index = 0; + CheckedAPICall(duckdb_v2_table_function_filter_pushdown_get_column_index, + static_cast(args), index, &column_index); + return column_index; +} + +auto TableFunction::FilterPushdownInput::GetContext() -> Context & { + return context; +} + +void *TableFunction::PartitionDataInput::GetBindDataInternal() const { + void *bind_data = nullptr; + CheckedAPICall(duckdb_v2_table_function_partition_data_get_bind_data, + static_cast(args), &bind_data); + return RequireTableBindData(bind_data); +} + +void *TableFunction::PartitionDataInput::GetGlobalStateInternal() const { + void *global_state = nullptr; + CheckedAPICall(duckdb_v2_table_function_partition_data_get_global_state, + static_cast(args), &global_state); + return RequireGlobalState(global_state); +} + +void *TableFunction::PartitionDataInput::GetLocalStateInternal() const { + void *local_state = nullptr; + CheckedAPICall(duckdb_v2_table_function_partition_data_get_local_state, + static_cast(args), &local_state); + return RequireLocalState(local_state); +} + +void *TableFunction::PartitionDataInput::GetUserDataInternal() const { + void *user_data = nullptr; + CheckedAPICall(duckdb_v2_table_function_partition_data_get_user_data, + static_cast(args), &user_data); + const auto &function = *static_cast(user_data); + return RequireTableUserData(function.user_data); +} + +auto TableFunction::PartitionDataInput::RequiresBatchIndex() const -> bool { + bool required = false; + CheckedAPICall(duckdb_v2_table_function_partition_data_requires_batch_index, + static_cast(args), &required); + return required; +} + +auto TableFunction::PartitionDataInput::RequiresPartitionColumns() const -> bool { + bool required = false; + CheckedAPICall(duckdb_v2_table_function_partition_data_requires_partition_columns, + static_cast(args), &required); + return required; +} + +auto TableFunction::PartitionDataInput::GetPartitionColumnCount() const -> idx_t { + idx_t count = 0; + CheckedAPICall(duckdb_v2_table_function_partition_data_get_partition_column_count, + static_cast(args), &count); + return count; +} + +auto TableFunction::PartitionDataInput::GetPartitionColumnIndex(idx_t index) const -> idx_t { + idx_t column_index = 0; + CheckedAPICall(duckdb_v2_table_function_partition_data_get_partition_column_index, + static_cast(args), index, &column_index); + return column_index; +} + +auto TableFunction::PartitionDataInput::SetBatchIndex(idx_t batch_index) -> void { + CheckedAPICall(duckdb_v2_table_function_partition_data_set_batch_index, + static_cast(args), batch_index); +} + +auto TableFunction::PartitionDataInput::SetPartitionValue(idx_t index, const Value &value) -> void { + CheckedAPICall(duckdb_v2_table_function_partition_data_set_partition_value, + static_cast(args), index, value.handle()); +} + +auto TableFunction::PartitionDataInput::GetContext() -> Context & { + return context; +} + +void *TableFunction::PartitioningInput::GetBindDataInternal() const { + void *bind_data = nullptr; + CheckedAPICall(duckdb_v2_table_function_partitioning_get_bind_data, + static_cast(args), &bind_data); + return RequireTableBindData(bind_data); +} + +void *TableFunction::PartitioningInput::GetUserDataInternal() const { + void *user_data = nullptr; + CheckedAPICall(duckdb_v2_table_function_partitioning_get_user_data, + static_cast(args), &user_data); + const auto &function = *static_cast(user_data); + return RequireTableUserData(function.user_data); +} + +auto TableFunction::PartitioningInput::GetPartitionColumnCount() const -> idx_t { + idx_t count = 0; + CheckedAPICall(duckdb_v2_table_function_partitioning_get_partition_column_count, + static_cast(args), &count); + return count; +} + +auto TableFunction::PartitioningInput::GetPartitionColumnIndex(idx_t index) const -> idx_t { + idx_t column_index = 0; + CheckedAPICall(duckdb_v2_table_function_partitioning_get_partition_column_index, + static_cast(args), index, &column_index); + return column_index; +} + +static_assert(static_cast(TableFunction::PartitionInfo::NOT_PARTITIONED) == + DUCKDB_V2_TABLE_PARTITION_INFO_NOT_PARTITIONED, + "PartitionInfo::NOT_PARTITIONED mismatch"); +static_assert(static_cast(TableFunction::PartitionInfo::SINGLE_VALUE_PARTITIONS) == + DUCKDB_V2_TABLE_PARTITION_INFO_SINGLE_VALUE_PARTITIONS, + "PartitionInfo::SINGLE_VALUE_PARTITIONS mismatch"); +static_assert(static_cast(TableFunction::PartitionInfo::OVERLAPPING_PARTITIONS) == + DUCKDB_V2_TABLE_PARTITION_INFO_OVERLAPPING_PARTITIONS, + "PartitionInfo::OVERLAPPING_PARTITIONS mismatch"); +static_assert(static_cast(TableFunction::PartitionInfo::DISJOINT_PARTITIONS) == + DUCKDB_V2_TABLE_PARTITION_INFO_DISJOINT_PARTITIONS, + "PartitionInfo::DISJOINT_PARTITIONS mismatch"); + +auto TableFunction::PartitioningInput::SetPartitionInfo(PartitionInfo partition_info) -> void { + CheckedAPICall(duckdb_v2_table_function_partitioning_set_partition_info, + static_cast(args), + static_cast(partition_info)); +} + +auto TableFunction::PartitioningInput::GetContext() -> Context & { + return context; +} + +void *TableFunction::ClaimBatchInput::GetBindDataInternal() const { + void *bind_data = nullptr; + CheckedAPICall(duckdb_v2_table_function_claim_batch_get_bind_data, + static_cast(args), &bind_data); + return RequireTableBindData(bind_data); +} + +void *TableFunction::ClaimBatchInput::GetGlobalStateInternal() const { + void *global_state = nullptr; + CheckedAPICall(duckdb_v2_table_function_claim_batch_get_global_state, + static_cast(args), &global_state); + return RequireGlobalState(global_state); +} + +void *TableFunction::ClaimBatchInput::GetLocalStateInternal() const { + void *local_state = nullptr; + CheckedAPICall(duckdb_v2_table_function_claim_batch_get_local_state, + static_cast(args), &local_state); + return RequireLocalState(local_state); +} + +void *TableFunction::ClaimBatchInput::GetUserDataInternal() const { + void *user_data = nullptr; + CheckedAPICall(duckdb_v2_table_function_claim_batch_get_user_data, + static_cast(args), &user_data); + const auto &function = *static_cast(user_data); + return RequireTableUserData(function.user_data); +} + +auto TableFunction::ClaimBatchInput::SetClaimed(bool claimed) -> void { + CheckedAPICall(duckdb_v2_table_function_claim_batch_set_claimed, + static_cast(args), claimed); +} + +void *TableFunction::GetBindInfoInput::GetBindDataInternal() const { + void *bind_data = nullptr; + CheckedAPICall(duckdb_v2_table_function_get_bind_info_get_bind_data, + static_cast(args), &bind_data); + return RequireTableBindData(bind_data); +} + +void *TableFunction::GetBindInfoInput::GetUserDataInternal() const { + void *user_data = nullptr; + CheckedAPICall(duckdb_v2_table_function_get_bind_info_get_user_data, + static_cast(args), &user_data); + const auto &function = *static_cast(user_data); + return RequireTableUserData(function.user_data); +} + +auto TableFunction::GetBindInfoInput::SetColumnIdentifier(idx_t column_index, const Value &identifier) -> void { + CheckedAPICall(duckdb_v2_table_function_get_bind_info_set_column_identifier, + static_cast(args), column_index, + static_cast(nullptr), static_cast(0), identifier.handle()); +} + +auto TableFunction::GetBindInfoInput::SetColumnIdentifier(idx_t column_index, const std::vector &child_path, + const Value &identifier) -> void { + CheckedAPICall(duckdb_v2_table_function_get_bind_info_set_column_identifier, + static_cast(args), column_index, + child_path.data(), static_cast(child_path.size()), identifier.handle()); +} + +auto TableFunction::GetBindInfoInput::SetOption(const std::string &key, const Value &value) -> void { + auto view = ToStr(key); + CheckedAPICall(duckdb_v2_table_function_get_bind_info_set_option, + static_cast(args), view.data(), view.size(), + value.handle()); +} + +auto TableFunction::ClaimBatchInput::GetContext() -> Context & { + return context; +} + +auto TableFunction::GetBindInfoInput::GetContext() -> Context & { + return context; +} + +void *TableFunction::ToStringInput::GetBindDataInternal() const { + void *bind_data = nullptr; + CheckedAPICall(duckdb_v2_table_function_to_string_get_bind_data, + static_cast(args), &bind_data); + return RequireTableBindData(bind_data); +} + +void *TableFunction::ToStringInput::GetUserDataInternal() const { + void *user_data = nullptr; + CheckedAPICall(duckdb_v2_table_function_to_string_get_user_data, + static_cast(args), &user_data); + const auto &function = *static_cast(user_data); + return RequireTableUserData(function.user_data); +} + +auto TableFunction::ToStringInput::Set(std::string_view key, std::string_view value) -> void { + CheckedAPICall(duckdb_v2_table_function_to_string_set, + static_cast(args), key.data(), + static_cast(key.size()), value.data(), static_cast(value.size())); +} + +//---------------------------------------------------------------------------------------------------------------------- +// Multi-File Function +//---------------------------------------------------------------------------------------------------------------------- + +MultiFileFunction::MultiFileFunction(void *impl) : detail::Handle(impl) { +} + +MultiFileFunction::~MultiFileFunction() { + auto _h = handle(); + duckdb_v2_multi_file_function_destroy(&_h); +} + +auto MultiFileFunction::Create(Factory &factory) -> MultiFileFunction { + duckdb_v2_multi_file_function_handle _h = nullptr; + CheckedAPICall(duckdb_v2_multi_file_function_create, factory.handle(), &_h); + return detail::HandleFactory::Make(_h); +} + +auto MultiFileFunction::SetName(const std::string &name) & -> MultiFileFunction & { + auto view = ToStr(name); + CheckedAPICall(duckdb_v2_multi_file_function_set_name, handle(), view.data(), view.size()); + return *this; +} + +auto MultiFileFunction::SetSingleFileFunction(const std::string &name) & -> MultiFileFunction & { + auto view = ToStr(name); + CheckedAPICall(duckdb_v2_multi_file_function_set_single_file_function, handle(), view.data(), view.size()); + return *this; +} + +auto MultiFileFunction::SetReaderType(const std::string &reader_type) & -> MultiFileFunction & { + auto view = ToStr(reader_type); + CheckedAPICall(duckdb_v2_multi_file_function_set_reader_type, handle(), view.data(), view.size()); + return *this; +} + +auto MultiFileFunction::SetFileExtension(const std::string &extension) & -> MultiFileFunction & { + auto view = ToStr(extension); + CheckedAPICall(duckdb_v2_multi_file_function_set_file_extension, handle(), view.data(), view.size()); + return *this; +} + +auto MultiFileFunction::PrepareRegistration() -> void { +} + +void *TableFunction::StatsInput::GetBindDataInternal() const { + void *bind_data = nullptr; + CheckedAPICall(duckdb_v2_table_function_stats_get_bind_data, + static_cast(args), &bind_data); + return RequireTableBindData(bind_data); +} + +void *TableFunction::StatsInput::GetUserDataInternal() const { + void *user_data = nullptr; + CheckedAPICall(duckdb_v2_table_function_stats_get_user_data, + static_cast(args), &user_data); + const auto &function = *static_cast(user_data); + return RequireTableUserData(function.user_data); +} + +auto TableFunction::StatsInput::GetColumnIndex() const -> idx_t { + idx_t column_index = 0; + CheckedAPICall(duckdb_v2_table_function_stats_get_column_index, + static_cast(args), &column_index); + return column_index; +} + +auto TableFunction::StatsInput::GetResultStats() const -> Stats { + duckdb_v2_stats_handle stats = nullptr; + CheckedAPICall(duckdb_v2_table_function_stats_get_result_stats, + static_cast(args), &stats); + return detail::HandleFactory::Make(stats); +} + +auto TableFunction::StatsInput::GetContext() -> Context & { + return context; +} + +//---------------------------------------------------------------------------------------------------------------------- +// Bound Expression +//---------------------------------------------------------------------------------------------------------------------- + +Expression::Expression(void *impl) : detail::Handle(impl) { +} + +auto Expression::GetType() const -> ExpressionType { + auto type = DUCKDB_V2_EXPRESSION_TYPE_INVALID; + CheckedAPICall(duckdb_v2_expression_get_type, handle(), &type); + return static_cast(type); +} + +auto Expression::GetReturnType() const -> LogicalType { + duckdb_v2_logical_type_handle type = nullptr; + CheckedAPICall(duckdb_v2_expression_get_return_type, handle(), &type); + return detail::HandleFactory::Make(type); +} + +auto Expression::GetChildCount() const -> idx_t { + idx_t count = 0; + CheckedAPICall(duckdb_v2_expression_get_child_count, handle(), &count); + return count; +} + +auto Expression::GetChild(idx_t index) const -> Expression { + duckdb_v2_expression_handle child = nullptr; + CheckedAPICall(duckdb_v2_expression_get_child, handle(), index, &child); + return detail::HandleFactory::Make(static_cast(child)); +} + +auto Expression::GetConstantValue() const -> Value { + duckdb_v2_value_handle value = nullptr; + CheckedAPICall(duckdb_v2_expression_constant_get_value, handle(), &value); + return detail::HandleFactory::Make(value); +} + +auto Expression::GetColumnIndex() const -> idx_t { + idx_t index = 0; + CheckedAPICall(duckdb_v2_expression_column_ref_get_index, handle(), &index); + return index; +} + +auto Expression::GetFunctionName() const -> std::string { + const char *name = nullptr; + idx_t name_length = 0; + CheckedAPICall(duckdb_v2_expression_function_get_name, handle(), &name, &name_length); + return std::string(FromStr(name, name_length)); +} + +auto Expression::GetFunctionQualifiedName() const -> QualifiedName { + duckdb_v2_qname_handle name = nullptr; + CheckedAPICall(duckdb_v2_expression_function_get_qname, handle(), &name); + return detail::HandleFactory::Make(name); +} + +auto Expression::GetCastMode() const -> CastMode { + auto mode = DUCKDB_V2_CAST_MODE_NORMAL; + CheckedAPICall(duckdb_v2_expression_cast_get_mode, handle(), &mode); + return static_cast(mode); +} + +//---------------------------------------------------------------------------------------------------------------------- +// Custom Type +//---------------------------------------------------------------------------------------------------------------------- + +CustomType::CustomType(void *impl) : detail::Handle(impl) { +} + +CustomType::~CustomType() { + auto _h = handle(); + duckdb_v2_custom_type_destroy(&_h); +} + +auto CustomType::Create(Factory &factory) -> CustomType { + duckdb_v2_custom_type_handle _h = nullptr; + CheckedAPICall(duckdb_v2_custom_type_create, factory.handle(), &_h); + return detail::HandleFactory::Make(_h); +} + +auto CustomType::SetName(const std::string &name) & -> CustomType & { + auto name_str = ToStr(name); + CheckedAPICall(duckdb_v2_custom_type_set_name, handle(), name_str.data(), name_str.size()); + return *this; +} + +auto CustomType::SetBaseType(const LogicalType &type) & -> CustomType & { + CheckedAPICall(duckdb_v2_custom_type_set_base_type, handle(), type.handle()); + return *this; +} + +auto CustomType::PrepareRegistration() -> void { +} + +//---------------------------------------------------------------------------------------------------------------------- +// Copy Function +//---------------------------------------------------------------------------------------------------------------------- + +namespace { + +// The callback table for one registered copy function: rides the C user_data +// slot so the trampolines can find it; the user's own slot (SetUserData) rides +// inside it. Owned by the registered function, freed at engine teardown. +struct CopyFunctionInfo { + CopyFunction::CopyToBindCallback copy_to_bind_callback = nullptr; + CopyFunction::CopyToBatchSizeCallback copy_to_batch_size_callback = nullptr; + CopyFunction::CopyToInitCallback copy_to_init_callback = nullptr; + CopyFunction::CopyToBatchCallback copy_to_batch_callback = nullptr; + CopyFunction::CopyToFlushCallback copy_to_flush_callback = nullptr; + CopyFunction::CopyToFinalizeCallback copy_to_finalize_callback = nullptr; + CopyFunction::CopyToStatisticsCallback copy_to_statistics_callback = nullptr; + CopyFunction::CopyFromBindCallback copy_from_bind_callback = nullptr; + CopyFunction::CopyFromInitGlobalCallback copy_from_init_global_callback = nullptr; + CopyFunction::CopyFromInitLocalCallback copy_from_init_local_callback = nullptr; + CopyFunction::CopyFromExecCallback copy_from_exec_callback = nullptr; + CopyFunction::CopyFromProgressCallback copy_from_progress_callback = nullptr; + detail::UserData user_data; + + CopyFunctionInfo(CopyFunction::CopyToBindCallback copy_to_bind_callback, + CopyFunction::CopyToBatchSizeCallback copy_to_batch_size_callback, + CopyFunction::CopyToInitCallback copy_to_init_callback, + CopyFunction::CopyToBatchCallback copy_to_batch_callback, + CopyFunction::CopyToFlushCallback copy_to_flush_callback, + CopyFunction::CopyToFinalizeCallback copy_to_finalize_callback, + CopyFunction::CopyToStatisticsCallback copy_to_statistics_callback, + CopyFunction::CopyFromBindCallback copy_from_bind_callback, + CopyFunction::CopyFromInitGlobalCallback copy_from_init_global_callback, + CopyFunction::CopyFromInitLocalCallback copy_from_init_local_callback, + CopyFunction::CopyFromExecCallback copy_from_exec_callback, + CopyFunction::CopyFromProgressCallback copy_from_progress_callback, detail::UserData user_data) + : copy_to_bind_callback(copy_to_bind_callback), copy_to_batch_size_callback(copy_to_batch_size_callback), + copy_to_init_callback(copy_to_init_callback), copy_to_batch_callback(copy_to_batch_callback), + copy_to_flush_callback(copy_to_flush_callback), copy_to_finalize_callback(copy_to_finalize_callback), + copy_to_statistics_callback(copy_to_statistics_callback), copy_from_bind_callback(copy_from_bind_callback), + copy_from_init_global_callback(copy_from_init_global_callback), + copy_from_init_local_callback(copy_from_init_local_callback), + copy_from_exec_callback(copy_from_exec_callback), copy_from_progress_callback(copy_from_progress_callback), + user_data(std::move(user_data)) { + } + + bool operator==(const CopyFunctionInfo &other) const { + return copy_to_bind_callback == other.copy_to_bind_callback && + copy_to_batch_size_callback == other.copy_to_batch_size_callback && + copy_to_init_callback == other.copy_to_init_callback && + copy_to_batch_callback == other.copy_to_batch_callback && + copy_to_flush_callback == other.copy_to_flush_callback && + copy_to_finalize_callback == other.copy_to_finalize_callback && + copy_to_statistics_callback == other.copy_to_statistics_callback && + copy_from_bind_callback == other.copy_from_bind_callback && + copy_from_init_global_callback == other.copy_from_init_global_callback && + copy_from_init_local_callback == other.copy_from_init_local_callback && + copy_from_exec_callback == other.copy_from_exec_callback && + copy_from_progress_callback == other.copy_from_progress_callback && + user_data.get() == other.user_data.get(); + } +}; + +// Guard for the inputs' GetUserData: a clear error instead of a null deref. +void *RequireCopyUserData(const detail::UserData &user_data) { + auto ptr = user_data.get(); + if (!ptr) { + throw InvalidInputException("no user data was set; call CopyFunction::SetUserData before Register"); + } + return ptr; +} + +// Guard for the inputs' GetBindData: a clear error instead of a null deref. +void *RequireCopyBindData(void *ptr) { + if (!ptr) { + throw InvalidInputException("no bind data was set; call the bind input's SetBindData in the bind callback"); + } + return ptr; +} + +// Guard for the inputs' GetInitData: a clear error instead of a null deref. +void *RequireCopyInitData(void *ptr) { + if (!ptr) { + throw InvalidInputException("no init data was set; call CopyToInitInput::SetInitData in the init callback"); + } + return ptr; +} + +// Guard for the inputs' GetBatchData: a clear error instead of a null deref. +void *RequireCopyBatchData(void *ptr) { + if (!ptr) { + throw InvalidInputException("no batch data was set; call CopyToBatchInput::SetBatchData in the batch callback"); + } + return ptr; +} + +// Guard for the inputs' GetGlobalState: a clear error instead of a null deref. +void *RequireCopyGlobalState(void *ptr) { + if (!ptr) { + throw InvalidInputException( + "no global state was set; call CopyFromInitGlobalInput::SetGlobalState in the global init callback"); + } + return ptr; +} + +// Guard for the inputs' GetLocalState: a clear error instead of a null deref. +void *RequireCopyLocalState(void *ptr) { + if (!ptr) { + throw InvalidInputException( + "no local state was set; call CopyFromInitLocalInput::SetLocalState in the local init callback"); + } + return ptr; +} + +} // namespace + +CopyFunction::CopyFunction(void *impl) : detail::Handle(impl) { +} + +CopyFunction::~CopyFunction() { + auto _h = handle(); + duckdb_v2_copy_function_destroy(&_h); +} + +auto CopyFunction::Create(Factory &factory) -> CopyFunction { + duckdb_v2_copy_function_handle _h = nullptr; + CheckedAPICall(duckdb_v2_copy_function_create, factory.handle(), &_h); + return detail::HandleFactory::Make(_h); +} + +auto CopyFunction::SetName(const std::string &name) & -> CopyFunction & { + auto view = ToStr(name); + CheckedAPICall(duckdb_v2_copy_function_set_name, handle(), view.data(), view.size()); + return *this; +} + +auto CopyFunction::SetFileExtension(const std::string &extension) & -> CopyFunction & { + auto view = ToStr(extension); + CheckedAPICall(duckdb_v2_copy_function_set_file_extension, handle(), view.data(), view.size()); + return *this; +} + +auto CopyFunction::SetUserDataInternal(void *data, void (*destructor)(void *)) -> void { + user_data = detail::UserData(data, destructor); +} + +auto CopyFunction::SetCopyToBindCallback(CopyToBindCallback callback) & -> CopyFunction & { + if (!callback) { + CheckedAPICall(duckdb_v2_copy_to_set_bind_callback, handle(), nullptr); + copy_to_bind_callback = nullptr; + return *this; + } + + // The C-side callback is one shared trampoline; the user's callback is looked + // up through the info table riding the user_data slot (set by Register). + static auto trampoline = [](duckdb_v2_copy_to_bind_info_handle info, duckdb_v2_context_handle context, + duckdb_v2_error_info_handle *err) { + WithExceptionGuard(err, [&]() { + void *user_data = nullptr; + CheckedAPICall(duckdb_v2_copy_to_bind_get_user_data, info, &user_data); + const auto &function = *static_cast(user_data); + + auto input = + detail::HandleFactory::Make(static_cast(info), static_cast(context)); + function.copy_to_bind_callback(input); + }); + }; + + CheckedAPICall(duckdb_v2_copy_to_set_bind_callback, handle(), trampoline); + copy_to_bind_callback = callback; + return *this; +} + +auto CopyFunction::SetCopyToBatchSizeCallback(CopyToBatchSizeCallback callback) & -> CopyFunction & { + if (!callback) { + CheckedAPICall(duckdb_v2_copy_to_set_batch_size_callback, handle(), nullptr); + copy_to_batch_size_callback = nullptr; + return *this; + } + + static auto trampoline = [](duckdb_v2_copy_to_batch_size_info_handle info, duckdb_v2_context_handle context, + duckdb_v2_error_info_handle *err) { + WithExceptionGuard(err, [&]() { + void *user_data = nullptr; + CheckedAPICall(duckdb_v2_copy_to_batch_size_get_user_data, info, &user_data); + const auto &function = *static_cast(user_data); + + auto input = detail::HandleFactory::Make(static_cast(info), + static_cast(context)); + function.copy_to_batch_size_callback(input); + }); + }; + + CheckedAPICall(duckdb_v2_copy_to_set_batch_size_callback, handle(), trampoline); + copy_to_batch_size_callback = callback; + return *this; +} + +auto CopyFunction::SetCopyToInitCallback(CopyToInitCallback callback) & -> CopyFunction & { + if (!callback) { + CheckedAPICall(duckdb_v2_copy_to_set_init_callback, handle(), nullptr); + copy_to_init_callback = nullptr; + return *this; + } + + static auto trampoline = [](duckdb_v2_copy_to_init_info_handle info, duckdb_v2_context_handle context, + duckdb_v2_error_info_handle *err) { + WithExceptionGuard(err, [&]() { + void *user_data = nullptr; + CheckedAPICall(duckdb_v2_copy_to_init_get_user_data, info, &user_data); + const auto &function = *static_cast(user_data); + + auto input = + detail::HandleFactory::Make(static_cast(info), static_cast(context)); + function.copy_to_init_callback(input); + }); + }; + + CheckedAPICall(duckdb_v2_copy_to_set_init_callback, handle(), trampoline); + copy_to_init_callback = callback; + return *this; +} + +auto CopyFunction::SetCopyToBatchCallback(CopyToBatchCallback callback) & -> CopyFunction & { + if (!callback) { + CheckedAPICall(duckdb_v2_copy_to_set_batch_callback, handle(), nullptr); + copy_to_batch_callback = nullptr; + return *this; + } + + static auto trampoline = [](duckdb_v2_copy_to_batch_info_handle info, duckdb_v2_context_handle context, + duckdb_v2_error_info_handle *err) { + WithExceptionGuard(err, [&]() { + void *user_data = nullptr; + CheckedAPICall(duckdb_v2_copy_to_batch_get_user_data, info, &user_data); + const auto &function = *static_cast(user_data); + + auto input = + detail::HandleFactory::Make(static_cast(info), static_cast(context)); + function.copy_to_batch_callback(input); + }); + }; + + CheckedAPICall(duckdb_v2_copy_to_set_batch_callback, handle(), trampoline); + copy_to_batch_callback = callback; + return *this; +} + +auto CopyFunction::SetCopyToFlushCallback(CopyToFlushCallback callback) & -> CopyFunction & { + if (!callback) { + CheckedAPICall(duckdb_v2_copy_to_set_flush_callback, handle(), nullptr); + copy_to_flush_callback = nullptr; + return *this; + } + + static auto trampoline = [](duckdb_v2_copy_to_flush_info_handle info, duckdb_v2_context_handle context, + duckdb_v2_error_info_handle *err) { + WithExceptionGuard(err, [&]() { + void *user_data = nullptr; + CheckedAPICall(duckdb_v2_copy_to_flush_get_user_data, info, &user_data); + const auto &function = *static_cast(user_data); + + auto input = + detail::HandleFactory::Make(static_cast(info), static_cast(context)); + function.copy_to_flush_callback(input); + }); + }; + + CheckedAPICall(duckdb_v2_copy_to_set_flush_callback, handle(), trampoline); + copy_to_flush_callback = callback; + return *this; +} + +auto CopyFunction::SetCopyToFinalizeCallback(CopyToFinalizeCallback callback) & -> CopyFunction & { + if (!callback) { + CheckedAPICall(duckdb_v2_copy_to_set_finalize_callback, handle(), nullptr); + copy_to_finalize_callback = nullptr; + return *this; + } + + static auto trampoline = [](duckdb_v2_copy_to_finalize_info_handle info, duckdb_v2_context_handle context, + duckdb_v2_error_info_handle *err) { + WithExceptionGuard(err, [&]() { + void *user_data = nullptr; + CheckedAPICall(duckdb_v2_copy_to_finalize_get_user_data, info, &user_data); + const auto &function = *static_cast(user_data); + + auto input = detail::HandleFactory::Make(static_cast(info), + static_cast(context)); + function.copy_to_finalize_callback(input); + }); + }; + + CheckedAPICall(duckdb_v2_copy_to_set_finalize_callback, handle(), trampoline); + copy_to_finalize_callback = callback; + return *this; +} + +auto CopyFunction::SetCopyToStatisticsCallback(CopyToStatisticsCallback callback) & -> CopyFunction & { + if (!callback) { + CheckedAPICall(duckdb_v2_copy_to_set_statistics_callback, handle(), nullptr); + copy_to_statistics_callback = nullptr; + return *this; + } + + static auto trampoline = [](duckdb_v2_copy_to_statistics_info_handle info, duckdb_v2_context_handle context, + duckdb_v2_error_info_handle *err) { + WithExceptionGuard(err, [&]() { + void *user_data = nullptr; + CheckedAPICall(duckdb_v2_copy_to_statistics_get_user_data, info, &user_data); + const auto &function = *static_cast(user_data); + + auto input = detail::HandleFactory::Make(static_cast(info), + static_cast(context)); + function.copy_to_statistics_callback(input); + }); + }; + + CheckedAPICall(duckdb_v2_copy_to_set_statistics_callback, handle(), trampoline); + copy_to_statistics_callback = callback; + return *this; +} + +auto CopyFunction::SetCopyFromBindCallback(CopyFromBindCallback callback) & -> CopyFunction & { + if (!callback) { + CheckedAPICall(duckdb_v2_copy_from_set_bind_callback, handle(), nullptr); + copy_from_bind_callback = nullptr; + return *this; + } + + static auto trampoline = [](duckdb_v2_copy_from_bind_info_handle info, duckdb_v2_context_handle context, + duckdb_v2_error_info_handle *err) { + WithExceptionGuard(err, [&]() { + void *user_data = nullptr; + CheckedAPICall(duckdb_v2_copy_from_bind_get_user_data, info, &user_data); + const auto &function = *static_cast(user_data); + + auto input = + detail::HandleFactory::Make(static_cast(info), static_cast(context)); + function.copy_from_bind_callback(input); + }); + }; + + CheckedAPICall(duckdb_v2_copy_from_set_bind_callback, handle(), trampoline); + copy_from_bind_callback = callback; + return *this; +} + +auto CopyFunction::SetCopyFromInitGlobalCallback(CopyFromInitGlobalCallback callback) & -> CopyFunction & { + if (!callback) { + CheckedAPICall(duckdb_v2_copy_from_set_init_global_callback, handle(), nullptr); + copy_from_init_global_callback = nullptr; + return *this; + } + + static auto trampoline = [](duckdb_v2_copy_from_init_global_info_handle info, duckdb_v2_context_handle context, + duckdb_v2_error_info_handle *err) { + WithExceptionGuard(err, [&]() { + void *user_data = nullptr; + CheckedAPICall(duckdb_v2_copy_from_init_global_get_user_data, info, &user_data); + const auto &function = *static_cast(user_data); + + auto input = detail::HandleFactory::Make(static_cast(info), + static_cast(context)); + function.copy_from_init_global_callback(input); + }); + }; + + CheckedAPICall(duckdb_v2_copy_from_set_init_global_callback, handle(), trampoline); + copy_from_init_global_callback = callback; + return *this; +} + +auto CopyFunction::SetCopyFromInitLocalCallback(CopyFromInitLocalCallback callback) & -> CopyFunction & { + if (!callback) { + CheckedAPICall(duckdb_v2_copy_from_set_init_local_callback, handle(), nullptr); + copy_from_init_local_callback = nullptr; + return *this; + } + + static auto trampoline = [](duckdb_v2_copy_from_init_local_info_handle info, duckdb_v2_context_handle context, + duckdb_v2_error_info_handle *err) { + WithExceptionGuard(err, [&]() { + void *user_data = nullptr; + CheckedAPICall(duckdb_v2_copy_from_init_local_get_user_data, info, &user_data); + const auto &function = *static_cast(user_data); + + auto input = detail::HandleFactory::Make(static_cast(info), + static_cast(context)); + function.copy_from_init_local_callback(input); + }); + }; + + CheckedAPICall(duckdb_v2_copy_from_set_init_local_callback, handle(), trampoline); + copy_from_init_local_callback = callback; + return *this; +} + +auto CopyFunction::SetCopyFromExecCallback(CopyFromExecCallback callback) & -> CopyFunction & { + if (!callback) { + CheckedAPICall(duckdb_v2_copy_from_set_exec_callback, handle(), nullptr); + copy_from_exec_callback = nullptr; + return *this; + } + + static auto trampoline = [](duckdb_v2_copy_from_exec_info_handle info, duckdb_v2_context_handle context, + duckdb_v2_error_info_handle *err) { + WithExceptionGuard(err, [&]() { + void *user_data = nullptr; + CheckedAPICall(duckdb_v2_copy_from_exec_get_user_data, info, &user_data); + const auto &function = *static_cast(user_data); + + auto input = + detail::HandleFactory::Make(static_cast(info), static_cast(context)); + function.copy_from_exec_callback(input); + }); + }; + + CheckedAPICall(duckdb_v2_copy_from_set_exec_callback, handle(), trampoline); + copy_from_exec_callback = callback; + return *this; +} + +auto CopyFunction::SetCopyFromProgressCallback(CopyFromProgressCallback callback) & -> CopyFunction & { + if (!callback) { + CheckedAPICall(duckdb_v2_copy_from_set_progress_callback, handle(), nullptr); + copy_from_progress_callback = nullptr; + return *this; + } + + static auto trampoline = [](duckdb_v2_copy_from_progress_info_handle info, duckdb_v2_context_handle context, + duckdb_v2_error_info_handle *err) { + WithExceptionGuard(err, [&]() { + void *user_data = nullptr; + CheckedAPICall(duckdb_v2_copy_from_progress_get_user_data, info, &user_data); + const auto &function = *static_cast(user_data); + + auto input = detail::HandleFactory::Make(static_cast(info), + static_cast(context)); + function.copy_from_progress_callback(input); + }); + }; + + CheckedAPICall(duckdb_v2_copy_from_set_progress_callback, handle(), trampoline); + copy_from_progress_callback = callback; + return *this; +} + +auto CopyFunction::PrepareRegistration() -> void { + // The callback table rides the C user_data slot so the trampolines can find + // it; the user's own data (SetUserData, moved out here) rides inside it. + auto info = std::unique_ptr(new CopyFunctionInfo( + copy_to_bind_callback, copy_to_batch_size_callback, copy_to_init_callback, copy_to_batch_callback, + copy_to_flush_callback, copy_to_finalize_callback, copy_to_statistics_callback, copy_from_bind_callback, + copy_from_init_global_callback, copy_from_init_local_callback, copy_from_exec_callback, + copy_from_progress_callback, std::move(user_data))); + duckdb_v2_opaque opaque {info.get(), detail::TypedDelete, detail::TypedEquals}; + CheckedAPICall(duckdb_v2_copy_function_set_user_data, handle(), &opaque); + // The function owns the table now. + info.release(); // NOLINT(bugprone-unused-return-value) +} + +void *CopyFunction::CopyToBindInput::GetUserDataInternal() const { + void *user_data = nullptr; + CheckedAPICall(duckdb_v2_copy_to_bind_get_user_data, static_cast(args), + &user_data); + const auto &function = *static_cast(user_data); + return RequireCopyUserData(function.user_data); +} + +void CopyFunction::CopyToBindInput::SetBindDataInternal(void *data, bool (*equals)(void *a, void *b), + void (*destructor)(void *)) { + duckdb_v2_opaque opaque {data, destructor, equals}; + CheckedAPICall(duckdb_v2_copy_to_bind_set_bind_data, static_cast(args), + &opaque); +} + +auto CopyFunction::CopyToBindInput::GetFilePath() const -> std::string { + const char *path = nullptr; + idx_t path_length = 0; + CheckedAPICall(duckdb_v2_copy_to_bind_get_file_path, static_cast(args), &path, + &path_length); + return std::string(FromStr(path, path_length)); +} + +auto CopyFunction::CopyToBindInput::GetColumnCount() const -> idx_t { + idx_t count = 0; + CheckedAPICall(duckdb_v2_copy_to_bind_get_column_count, static_cast(args), + &count); + return count; +} + +auto CopyFunction::CopyToBindInput::GetColumnName(idx_t index) const -> std::string { + const char *name = nullptr; + idx_t name_length = 0; + CheckedAPICall(duckdb_v2_copy_to_bind_get_column_name, static_cast(args), index, + &name, &name_length); + return std::string(FromStr(name, name_length)); +} + +auto CopyFunction::CopyToBindInput::GetColumnType(idx_t index) const -> LogicalType { + duckdb_v2_logical_type_handle type = nullptr; + CheckedAPICall(duckdb_v2_copy_to_bind_get_column_type, static_cast(args), index, + &type); + return detail::HandleFactory::Make(type); +} + +auto CopyFunction::CopyToBindInput::GetOptionCount() const -> idx_t { + idx_t count = 0; + CheckedAPICall(duckdb_v2_copy_to_bind_get_option_count, static_cast(args), + &count); + return count; +} + +auto CopyFunction::CopyToBindInput::GetOptionName(idx_t index) const -> std::string { + const char *name = nullptr; + idx_t name_length = 0; + CheckedAPICall(duckdb_v2_copy_to_bind_get_option_name, static_cast(args), index, + &name, &name_length); + return std::string(FromStr(name, name_length)); +} + +auto CopyFunction::CopyToBindInput::GetOptionValue(idx_t index) const -> Value { + duckdb_v2_value_handle value = nullptr; + CheckedAPICall(duckdb_v2_copy_to_bind_get_option_value, static_cast(args), + index, &value); + return detail::HandleFactory::Make(value); +} + +auto CopyFunction::CopyToBindInput::GetContext() -> Context & { + return context; +} + +void *CopyFunction::CopyToBatchSizeInput::GetBindDataInternal() const { + void *data = nullptr; + CheckedAPICall(duckdb_v2_copy_to_batch_size_get_bind_data, + static_cast(args), &data); + return RequireCopyBindData(data); +} + +void *CopyFunction::CopyToBatchSizeInput::GetUserDataInternal() const { + void *user_data = nullptr; + CheckedAPICall(duckdb_v2_copy_to_batch_size_get_user_data, + static_cast(args), &user_data); + const auto &function = *static_cast(user_data); + return RequireCopyUserData(function.user_data); +} + +auto CopyFunction::CopyToBatchSizeInput::SetTarget(idx_t rows) -> void { + CheckedAPICall(duckdb_v2_copy_to_batch_size_set_target, static_cast(args), + rows); +} + +auto CopyFunction::CopyToBatchSizeInput::GetContext() -> Context & { + return context; +} + +void CopyFunction::CopyToInitInput::SetInitDataInternal(void *data, void (*destructor)(void *)) { + duckdb_v2_opaque opaque {data, destructor, nullptr}; + CheckedAPICall(duckdb_v2_copy_to_init_set_init_data, static_cast(args), + &opaque); +} + +void *CopyFunction::CopyToInitInput::GetBindDataInternal() const { + void *data = nullptr; + CheckedAPICall(duckdb_v2_copy_to_init_get_bind_data, static_cast(args), &data); + return RequireCopyBindData(data); +} + +void *CopyFunction::CopyToInitInput::GetUserDataInternal() const { + void *user_data = nullptr; + CheckedAPICall(duckdb_v2_copy_to_init_get_user_data, static_cast(args), + &user_data); + const auto &function = *static_cast(user_data); + return RequireCopyUserData(function.user_data); +} + +auto CopyFunction::CopyToInitInput::GetFilePath() const -> std::string { + const char *path = nullptr; + idx_t path_length = 0; + CheckedAPICall(duckdb_v2_copy_to_init_get_file_path, static_cast(args), &path, + &path_length); + return std::string(FromStr(path, path_length)); +} + +auto CopyFunction::CopyToInitInput::GetContext() -> Context & { + return context; +} + +void CopyFunction::CopyToBatchInput::SetBatchDataInternal(void *data, void (*destructor)(void *)) { + duckdb_v2_opaque opaque {data, destructor, nullptr}; + CheckedAPICall(duckdb_v2_copy_to_batch_set_batch_data, static_cast(args), + &opaque); +} + +void *CopyFunction::CopyToBatchInput::GetBindDataInternal() const { + void *data = nullptr; + CheckedAPICall(duckdb_v2_copy_to_batch_get_bind_data, static_cast(args), + &data); + return RequireCopyBindData(data); +} + +void *CopyFunction::CopyToBatchInput::GetInitDataInternal() const { + void *data = nullptr; + CheckedAPICall(duckdb_v2_copy_to_batch_get_init_data, static_cast(args), + &data); + return RequireCopyInitData(data); +} + +void *CopyFunction::CopyToBatchInput::GetUserDataInternal() const { + void *user_data = nullptr; + CheckedAPICall(duckdb_v2_copy_to_batch_get_user_data, static_cast(args), + &user_data); + const auto &function = *static_cast(user_data); + return RequireCopyUserData(function.user_data); +} + +auto CopyFunction::CopyToBatchInput::TakeBatch() -> ColumnDataCollection { + duckdb_v2_column_data_collection_handle collection = nullptr; + CheckedAPICall(duckdb_v2_copy_to_batch_take_input, static_cast(args), + &collection); + return detail::HandleFactory::Make(collection); +} + +auto CopyFunction::CopyToBatchInput::GetContext() -> Context & { + return context; +} + +void *CopyFunction::CopyToFlushInput::GetBindDataInternal() const { + void *data = nullptr; + CheckedAPICall(duckdb_v2_copy_to_flush_get_bind_data, static_cast(args), + &data); + return RequireCopyBindData(data); +} + +void *CopyFunction::CopyToFlushInput::GetInitDataInternal() const { + void *data = nullptr; + CheckedAPICall(duckdb_v2_copy_to_flush_get_init_data, static_cast(args), + &data); + return RequireCopyInitData(data); +} + +void *CopyFunction::CopyToFlushInput::GetBatchDataInternal() const { + void *data = nullptr; + CheckedAPICall(duckdb_v2_copy_to_flush_get_batch_data, static_cast(args), + &data); + return RequireCopyBatchData(data); +} + +void *CopyFunction::CopyToFlushInput::GetUserDataInternal() const { + void *user_data = nullptr; + CheckedAPICall(duckdb_v2_copy_to_flush_get_user_data, static_cast(args), + &user_data); + const auto &function = *static_cast(user_data); + return RequireCopyUserData(function.user_data); +} + +auto CopyFunction::CopyToFlushInput::GetContext() -> Context & { + return context; +} + +void *CopyFunction::CopyToFinalizeInput::GetBindDataInternal() const { + void *data = nullptr; + CheckedAPICall(duckdb_v2_copy_to_finalize_get_bind_data, static_cast(args), + &data); + return RequireCopyBindData(data); +} + +void *CopyFunction::CopyToFinalizeInput::GetInitDataInternal() const { + void *data = nullptr; + CheckedAPICall(duckdb_v2_copy_to_finalize_get_init_data, static_cast(args), + &data); + return RequireCopyInitData(data); +} + +void *CopyFunction::CopyToFinalizeInput::GetUserDataInternal() const { + void *user_data = nullptr; + CheckedAPICall(duckdb_v2_copy_to_finalize_get_user_data, static_cast(args), + &user_data); + const auto &function = *static_cast(user_data); + return RequireCopyUserData(function.user_data); +} + +auto CopyFunction::CopyToFinalizeInput::GetContext() -> Context & { + return context; +} + +void *CopyFunction::CopyToStatisticsInput::GetBindDataInternal() const { + void *data = nullptr; + CheckedAPICall(duckdb_v2_copy_to_statistics_get_bind_data, + static_cast(args), &data); + return RequireCopyBindData(data); +} + +void *CopyFunction::CopyToStatisticsInput::GetInitDataInternal() const { + void *data = nullptr; + CheckedAPICall(duckdb_v2_copy_to_statistics_get_init_data, + static_cast(args), &data); + return RequireCopyInitData(data); +} + +void *CopyFunction::CopyToStatisticsInput::GetUserDataInternal() const { + void *user_data = nullptr; + CheckedAPICall(duckdb_v2_copy_to_statistics_get_user_data, + static_cast(args), &user_data); + const auto &function = *static_cast(user_data); + return RequireCopyUserData(function.user_data); +} + +auto CopyFunction::CopyToStatisticsInput::SetRowCount(idx_t row_count) -> void { + CheckedAPICall(duckdb_v2_copy_to_statistics_set_row_count, + static_cast(args), row_count); +} + +auto CopyFunction::CopyToStatisticsInput::SetFileSize(idx_t file_size_bytes) -> void { + CheckedAPICall(duckdb_v2_copy_to_statistics_set_file_size, + static_cast(args), file_size_bytes); +} + +auto CopyFunction::CopyToStatisticsInput::GetContext() -> Context & { + return context; +} + +void *CopyFunction::CopyFromBindInput::GetUserDataInternal() const { + void *user_data = nullptr; + CheckedAPICall(duckdb_v2_copy_from_bind_get_user_data, static_cast(args), + &user_data); + const auto &function = *static_cast(user_data); + return RequireCopyUserData(function.user_data); +} + +void CopyFunction::CopyFromBindInput::SetBindDataInternal(void *data, bool (*equals)(void *a, void *b), + void (*destructor)(void *)) { + duckdb_v2_opaque opaque {data, destructor, equals}; + CheckedAPICall(duckdb_v2_copy_from_bind_set_bind_data, static_cast(args), + &opaque); +} + +auto CopyFunction::CopyFromBindInput::GetFilePath() const -> std::string { + const char *path = nullptr; + idx_t path_length = 0; + CheckedAPICall(duckdb_v2_copy_from_bind_get_file_path, static_cast(args), + &path, &path_length); + return std::string(FromStr(path, path_length)); +} + +auto CopyFunction::CopyFromBindInput::GetColumnCount() const -> idx_t { + idx_t count = 0; + CheckedAPICall(duckdb_v2_copy_from_bind_get_column_count, static_cast(args), + &count); + return count; +} + +auto CopyFunction::CopyFromBindInput::GetColumnName(idx_t index) const -> std::string { + const char *name = nullptr; + idx_t name_length = 0; + CheckedAPICall(duckdb_v2_copy_from_bind_get_column_name, static_cast(args), + index, &name, &name_length); + return std::string(FromStr(name, name_length)); +} + +auto CopyFunction::CopyFromBindInput::GetColumnType(idx_t index) const -> LogicalType { + duckdb_v2_logical_type_handle type = nullptr; + CheckedAPICall(duckdb_v2_copy_from_bind_get_column_type, static_cast(args), + index, &type); + return detail::HandleFactory::Make(type); +} + +auto CopyFunction::CopyFromBindInput::GetOptionCount() const -> idx_t { + idx_t count = 0; + CheckedAPICall(duckdb_v2_copy_from_bind_get_option_count, static_cast(args), + &count); + return count; +} + +auto CopyFunction::CopyFromBindInput::GetOptionName(idx_t index) const -> std::string { + const char *name = nullptr; + idx_t name_length = 0; + CheckedAPICall(duckdb_v2_copy_from_bind_get_option_name, static_cast(args), + index, &name, &name_length); + return std::string(FromStr(name, name_length)); +} + +auto CopyFunction::CopyFromBindInput::GetOptionValue(idx_t index) const -> Value { + duckdb_v2_value_handle value = nullptr; + CheckedAPICall(duckdb_v2_copy_from_bind_get_option_value, static_cast(args), + index, &value); + return detail::HandleFactory::Make(value); +} + +auto CopyFunction::CopyFromBindInput::SetCardinality(idx_t cardinality, bool is_exact) -> void { + CheckedAPICall(duckdb_v2_copy_from_bind_set_cardinality, static_cast(args), + cardinality, is_exact); +} + +auto CopyFunction::CopyFromBindInput::GetContext() -> Context & { + return context; +} + +void CopyFunction::CopyFromInitGlobalInput::SetGlobalStateInternal(void *data, void (*destructor)(void *)) { + duckdb_v2_opaque opaque {data, destructor, nullptr}; + CheckedAPICall(duckdb_v2_copy_from_init_global_set_global_state, + static_cast(args), &opaque); +} + +void *CopyFunction::CopyFromInitGlobalInput::GetBindDataInternal() const { + void *data = nullptr; + CheckedAPICall(duckdb_v2_copy_from_init_global_get_bind_data, + static_cast(args), &data); + return RequireCopyBindData(data); +} + +void *CopyFunction::CopyFromInitGlobalInput::GetUserDataInternal() const { + void *user_data = nullptr; + CheckedAPICall(duckdb_v2_copy_from_init_global_get_user_data, + static_cast(args), &user_data); + const auto &function = *static_cast(user_data); + return RequireCopyUserData(function.user_data); +} + +auto CopyFunction::CopyFromInitGlobalInput::SetMaxThreads(idx_t max_threads) -> void { + CheckedAPICall(duckdb_v2_copy_from_init_global_set_max_threads, + static_cast(args), max_threads); +} + +auto CopyFunction::CopyFromInitGlobalInput::GetContext() -> Context & { + return context; +} + +void CopyFunction::CopyFromInitLocalInput::SetLocalStateInternal(void *data, void (*destructor)(void *)) { + duckdb_v2_opaque opaque {data, destructor, nullptr}; + CheckedAPICall(duckdb_v2_copy_from_init_local_set_local_state, + static_cast(args), &opaque); +} + +void *CopyFunction::CopyFromInitLocalInput::GetBindDataInternal() const { + void *data = nullptr; + CheckedAPICall(duckdb_v2_copy_from_init_local_get_bind_data, + static_cast(args), &data); + return RequireCopyBindData(data); +} + +void *CopyFunction::CopyFromInitLocalInput::GetGlobalStateInternal() const { + void *data = nullptr; + CheckedAPICall(duckdb_v2_copy_from_init_local_get_global_state, + static_cast(args), &data); + return RequireCopyGlobalState(data); +} + +void *CopyFunction::CopyFromInitLocalInput::GetUserDataInternal() const { + void *user_data = nullptr; + CheckedAPICall(duckdb_v2_copy_from_init_local_get_user_data, + static_cast(args), &user_data); + const auto &function = *static_cast(user_data); + return RequireCopyUserData(function.user_data); +} + +auto CopyFunction::CopyFromInitLocalInput::GetContext() -> Context & { + return context; +} + +void *CopyFunction::CopyFromExecInput::GetBindDataInternal() const { + void *data = nullptr; + CheckedAPICall(duckdb_v2_copy_from_exec_get_bind_data, static_cast(args), + &data); + return RequireCopyBindData(data); +} + +void *CopyFunction::CopyFromExecInput::GetGlobalStateInternal() const { + void *data = nullptr; + CheckedAPICall(duckdb_v2_copy_from_exec_get_global_state, static_cast(args), + &data); + return RequireCopyGlobalState(data); +} + +void *CopyFunction::CopyFromExecInput::GetLocalStateInternal() const { + void *data = nullptr; + CheckedAPICall(duckdb_v2_copy_from_exec_get_local_state, static_cast(args), + &data); + return RequireCopyLocalState(data); +} + +void *CopyFunction::CopyFromExecInput::GetUserDataInternal() const { + void *user_data = nullptr; + CheckedAPICall(duckdb_v2_copy_from_exec_get_user_data, static_cast(args), + &user_data); + const auto &function = *static_cast(user_data); + return RequireCopyUserData(function.user_data); +} + +auto CopyFunction::CopyFromExecInput::GetOutputChunk() const -> DataChunk { + duckdb_v2_data_chunk_handle chunk = nullptr; + CheckedAPICall(duckdb_v2_copy_from_exec_get_output_chunk, static_cast(args), + &chunk); + // Borrowed: the engine owns the chunk and reuses it across invocations. + return detail::HandleFactory::Make(chunk, false); +} + +auto CopyFunction::CopyFromExecInput::GetContext() -> Context & { + return context; +} + +void *CopyFunction::CopyFromProgressInput::GetBindDataInternal() const { + void *data = nullptr; + CheckedAPICall(duckdb_v2_copy_from_progress_get_bind_data, + static_cast(args), &data); + return RequireCopyBindData(data); +} + +void *CopyFunction::CopyFromProgressInput::GetGlobalStateInternal() const { + void *data = nullptr; + CheckedAPICall(duckdb_v2_copy_from_progress_get_global_state, + static_cast(args), &data); + return RequireCopyGlobalState(data); +} + +void *CopyFunction::CopyFromProgressInput::GetUserDataInternal() const { + void *user_data = nullptr; + CheckedAPICall(duckdb_v2_copy_from_progress_get_user_data, + static_cast(args), &user_data); + const auto &function = *static_cast(user_data); + return RequireCopyUserData(function.user_data); +} + +auto CopyFunction::CopyFromProgressInput::SetProgress(double progress) -> void { + CheckedAPICall(duckdb_v2_copy_from_progress_set_progress, + static_cast(args), progress); +} + +auto CopyFunction::CopyFromProgressInput::GetContext() -> Context & { + return context; +} + +//---------------------------------------------------------------------------------------------------------------------- +// Cast Function +//---------------------------------------------------------------------------------------------------------------------- + +namespace { + +// The callback table for one registered cast: rides the C user_data slot so +// the trampoline can find it; the user's own slot (SetUserData) rides inside +// it. Owned by the registered cast, freed at engine teardown. +struct CastFunctionInfo { + CastFunction::ExecCallback exec_callback = nullptr; + detail::UserData user_data; + + CastFunctionInfo(CastFunction::ExecCallback exec_callback, detail::UserData user_data) + : exec_callback(exec_callback), user_data(std::move(user_data)) { + } + + bool operator==(const CastFunctionInfo &other) const { + return exec_callback == other.exec_callback && user_data.get() == other.user_data.get(); + } +}; + +// Guard for ExecInput::GetUserData: a clear error instead of a null deref. +void *RequireCastUserData(const detail::UserData &user_data) { + auto ptr = user_data.get(); + if (!ptr) { + throw InvalidInputException("no user data was set; call CastFunction::SetUserData before Register"); + } + return ptr; +} + +} // namespace + +CastFunction::CastFunction(void *impl) : detail::Handle(impl) { +} + +CastFunction::~CastFunction() { + auto _h = handle(); + duckdb_v2_cast_function_destroy(&_h); +} + +auto CastFunction::Create(Factory &factory) -> CastFunction { + duckdb_v2_cast_function_handle _h = nullptr; + CheckedAPICall(duckdb_v2_cast_function_create, factory.handle(), &_h); + return detail::HandleFactory::Make(_h); +} + +auto CastFunction::SetSourceType(const LogicalType &type) & -> CastFunction & { + CheckedAPICall(duckdb_v2_cast_function_set_source_type, handle(), type.handle()); + return *this; +} + +auto CastFunction::SetTargetType(const LogicalType &type) & -> CastFunction & { + CheckedAPICall(duckdb_v2_cast_function_set_target_type, handle(), type.handle()); + return *this; +} + +auto CastFunction::SetImplicitCastCost(int64_t cost) & -> CastFunction & { + CheckedAPICall(duckdb_v2_cast_function_set_implicit_cast_cost, handle(), cost); + return *this; +} + +auto CastFunction::SetUserDataInternal(void *data, void (*destructor)(void *)) -> void { + user_data = detail::UserData(data, destructor); +} + +auto CastFunction::SetExecCallback(ExecCallback callback) & -> CastFunction & { + if (!callback) { + CheckedAPICall(duckdb_v2_cast_function_set_exec_callback, handle(), nullptr); + exec_callback = nullptr; + return *this; + } + + // The C-side callback is one shared trampoline; the user's callback is looked + // up through the info table riding the user_data slot (set by Register). + static auto trampoline = [](duckdb_v2_cast_function_exec_info_handle info, duckdb_v2_context_handle context, + duckdb_v2_error_info_handle *err) { + WithExceptionGuard(err, [&]() { + void *user_data = nullptr; + CheckedAPICall(duckdb_v2_cast_function_exec_get_user_data, info, &user_data); + const auto &function = *static_cast(user_data); + + auto input = + detail::HandleFactory::Make(static_cast(info), static_cast(context)); + function.exec_callback(input); + }); + }; + + CheckedAPICall(duckdb_v2_cast_function_set_exec_callback, handle(), trampoline); + exec_callback = callback; + return *this; +} + +auto CastFunction::PrepareRegistration() -> void { + // The callback table rides the C user_data slot so the trampoline can find + // it; the user's own data (SetUserData, moved out here) rides inside it. + auto info = std::unique_ptr(new CastFunctionInfo(exec_callback, std::move(user_data))); + duckdb_v2_opaque opaque {info.get(), detail::TypedDelete, detail::TypedEquals}; + CheckedAPICall(duckdb_v2_cast_function_set_user_data, handle(), &opaque); + // The cast owns the table now. + info.release(); // NOLINT(bugprone-unused-return-value) +} + +void *CastFunction::ExecInput::GetUserDataInternal() const { + void *user_data = nullptr; + CheckedAPICall(duckdb_v2_cast_function_exec_get_user_data, + static_cast(args), &user_data); + const auto &function = *static_cast(user_data); + return RequireCastUserData(function.user_data); +} + +auto CastFunction::ExecInput::GetRowCount() const -> idx_t { + idx_t count = 0; + CheckedAPICall(duckdb_v2_cast_function_exec_get_row_count, + static_cast(args), &count); + return count; +} + +auto CastFunction::ExecInput::GetInput() const -> Vector { + duckdb_v2_vector_handle vector = nullptr; + CheckedAPICall(duckdb_v2_cast_function_exec_get_input, static_cast(args), + &vector); + return detail::HandleFactory::Make(vector); +} + +auto CastFunction::ExecInput::GetOutput() const -> Vector { + duckdb_v2_vector_handle vector = nullptr; + CheckedAPICall(duckdb_v2_cast_function_exec_get_output, static_cast(args), + &vector); + return detail::HandleFactory::Make(vector); +} + +auto CastFunction::ExecInput::GetMode() const -> CastMode { + auto mode = DUCKDB_V2_CAST_MODE_NORMAL; + CheckedAPICall(duckdb_v2_cast_function_exec_get_mode, static_cast(args), + &mode); + return static_cast(mode); +} + +auto CastFunction::ExecInput::GetContext() -> Context & { + return context; +} + +//---------------------------------------------------------------------------------------------------------------------- +// Pragma Function +//---------------------------------------------------------------------------------------------------------------------- + +namespace { + +// The callback table for one registered pragma: rides the C user_data slot so +// the trampolines can find it; the user's own slot (SetUserData) rides inside +// it. Owned by the registered pragma, freed at engine teardown. +struct PragmaFunctionInfo { + PragmaFunction::QueryCallback query_callback = nullptr; + PragmaFunction::ExecCallback exec_callback = nullptr; + detail::UserData user_data; + + PragmaFunctionInfo(PragmaFunction::QueryCallback query_callback, PragmaFunction::ExecCallback exec_callback, + detail::UserData user_data) + : query_callback(query_callback), exec_callback(exec_callback), user_data(std::move(user_data)) { + } + + bool operator==(const PragmaFunctionInfo &other) const { + return query_callback == other.query_callback && exec_callback == other.exec_callback && + user_data.get() == other.user_data.get(); + } +}; + +// Guard for the inputs' GetUserData: a clear error instead of a null deref. +void *RequirePragmaUserData(const detail::UserData &user_data) { + auto ptr = user_data.get(); + if (!ptr) { + throw InvalidInputException("no user data was set; call PragmaFunction::SetUserData before Register"); + } + return ptr; +} + +auto GetPragmaFunctionInfo(duckdb_v2_function_bind_info_handle info) -> const PragmaFunctionInfo & { + void *user_data = nullptr; + CheckedAPICall(duckdb_v2_function_bind_get_user_data, info, &user_data); + return *static_cast(user_data); +} + +} // namespace + +PragmaFunction::PragmaFunction(void *impl) : detail::Handle(impl) { +} + +PragmaFunction::~PragmaFunction() { + auto _h = handle(); + duckdb_v2_pragma_function_destroy(&_h); +} + +auto PragmaFunction::Create(Factory &factory) -> PragmaFunction { + duckdb_v2_pragma_function_handle _h = nullptr; + CheckedAPICall(duckdb_v2_pragma_function_create, factory.handle(), &_h); + return detail::HandleFactory::Make(_h); +} + +auto PragmaFunction::SetName(const std::string &name) & -> PragmaFunction & { + auto view = ToStr(name); + CheckedAPICall(duckdb_v2_pragma_function_set_name, handle(), view.data(), view.size()); + return *this; +} + +auto PragmaFunction::GetDocs() -> FunctionDocs { + duckdb_v2_function_docs_handle docs = nullptr; + CheckedAPICall(duckdb_v2_pragma_function_get_docs, handle(), &docs); + return detail::HandleFactory::Make(docs); +} + +auto PragmaFunction::GetSignature() -> FunctionSignature { + duckdb_v2_function_signature_handle sig = nullptr; + CheckedAPICall(duckdb_v2_pragma_function_get_signature, handle(), &sig); + return detail::HandleFactory::Make(sig); +} + +auto PragmaFunction::SetUserDataInternal(void *data, void (*destructor)(void *)) -> void { + user_data = detail::UserData(data, destructor); +} + +auto PragmaFunction::SetQueryCallback(QueryCallback callback) & -> PragmaFunction & { + if (!callback) { + CheckedAPICall(duckdb_v2_pragma_function_set_query_callback, handle(), nullptr); + query_callback = nullptr; + return *this; + } + + // The C-side callback is one shared trampoline; the user's callback is looked + // up through the info table riding the user_data slot (set by Register). + static auto trampoline = [](duckdb_v2_function_bind_info_handle info, + duckdb_v2_pragma_function_query_info_handle result, duckdb_v2_context_handle context, + duckdb_v2_error_info_handle *err) { + WithExceptionGuard(err, [&]() { + const auto &function = GetPragmaFunctionInfo(info); + auto input = + detail::HandleFactory::Make(static_cast(info), static_cast(context)); + auto query = function.query_callback(input); + auto query_str = ToStr(query); + CheckedAPICall(duckdb_v2_pragma_function_query_set_query, result, query_str.data(), query_str.size()); + }); + }; + + CheckedAPICall(duckdb_v2_pragma_function_set_query_callback, handle(), trampoline); + query_callback = callback; + return *this; +} + +auto PragmaFunction::SetExecCallback(ExecCallback callback) & -> PragmaFunction & { + if (!callback) { + CheckedAPICall(duckdb_v2_pragma_function_set_exec_callback, handle(), nullptr); + exec_callback = nullptr; + return *this; + } + + static auto trampoline = [](duckdb_v2_function_bind_info_handle info, duckdb_v2_context_handle context, + duckdb_v2_error_info_handle *err) { + WithExceptionGuard(err, [&]() { + const auto &function = GetPragmaFunctionInfo(info); + auto input = + detail::HandleFactory::Make(static_cast(info), static_cast(context)); + function.exec_callback(input); + }); + }; + + CheckedAPICall(duckdb_v2_pragma_function_set_exec_callback, handle(), trampoline); + exec_callback = callback; + return *this; +} + +auto PragmaFunction::PrepareRegistration() -> void { + // The callback table rides the C user_data slot so the trampolines can find + // it; the user's own data (SetUserData, moved out here) rides inside it. + auto info = std::unique_ptr( + new PragmaFunctionInfo(query_callback, exec_callback, std::move(user_data))); + duckdb_v2_opaque opaque {info.get(), detail::TypedDelete, + detail::TypedEquals}; + CheckedAPICall(duckdb_v2_pragma_function_set_user_data, handle(), &opaque); + // The pragma owns the table now. + info.release(); // NOLINT(bugprone-unused-return-value) +} + +void *PragmaFunction::QueryInput::GetUserDataInternal() const { + const auto &function = *static_cast(GetFunctionInfo()); + return RequirePragmaUserData(function.user_data); +} + +void *PragmaFunction::ExecInput::GetUserDataInternal() const { + const auto &function = *static_cast(GetFunctionInfo()); + return RequirePragmaUserData(function.user_data); +} + +//---------------------------------------------------------------------------------------------------------------------- +// Macro Function +//---------------------------------------------------------------------------------------------------------------------- + +MacroFunction::MacroFunction(void *impl) : detail::Handle(impl) { +} + +MacroFunction::~MacroFunction() { + auto _h = handle(); + duckdb_v2_macro_function_destroy(&_h); +} + +static auto CreateMacroFunction(Factory &factory, DUCKDB_V2_MACRO_FUNCTION_TYPE type) -> void * { + duckdb_v2_macro_function_handle _h = nullptr; + CheckedAPICall(duckdb_v2_macro_function_create, factory.handle(), type, &_h); + return _h; +} + +auto MacroFunction::CreateScalar(Factory &factory) -> MacroFunction { + return MacroFunction(CreateMacroFunction(factory, DUCKDB_V2_MACRO_FUNCTION_TYPE_SCALAR)); +} + +auto MacroFunction::CreateTable(Factory &factory) -> MacroFunction { + return MacroFunction(CreateMacroFunction(factory, DUCKDB_V2_MACRO_FUNCTION_TYPE_TABLE)); +} + +auto MacroFunction::SetName(const std::string &name) & -> MacroFunction & { + auto view = ToStr(name); + CheckedAPICall(duckdb_v2_macro_function_set_name, handle(), view.data(), view.size()); + return *this; +} + +auto MacroFunction::SetBody(std::string_view body) & -> MacroFunction & { + auto view = ToStr(body); + CheckedAPICall(duckdb_v2_macro_function_set_body, handle(), view.data(), view.size()); + return *this; +} + +auto MacroFunction::GetDocs() -> FunctionDocs { + duckdb_v2_function_docs_handle docs = nullptr; + CheckedAPICall(duckdb_v2_macro_function_get_docs, handle(), &docs); + return detail::HandleFactory::Make(docs); +} + +auto MacroFunction::GetSignature() -> FunctionSignature { + duckdb_v2_function_signature_handle sig = nullptr; + CheckedAPICall(duckdb_v2_macro_function_get_signature, handle(), &sig); + return detail::HandleFactory::Make(sig); +} + +//---------------------------------------------------------------------------------------------------------------------- +// Log Sink +//---------------------------------------------------------------------------------------------------------------------- + +namespace { + +// The callback table for one registered log sink: rides the C user_data +// slot so the trampolines can find it; the user's own slot (SetUserData) rides +// inside it. Owned by the registered storage, freed at engine teardown. +struct LogSinkInfo { + LogSink::WriteCallback write_callback = nullptr; + LogSink::FlushCallback flush_callback = nullptr; + detail::UserData user_data; + + LogSinkInfo(LogSink::WriteCallback write_callback, LogSink::FlushCallback flush_callback, + detail::UserData user_data) + : write_callback(write_callback), flush_callback(flush_callback), user_data(std::move(user_data)) { + } +}; + +auto WriteInfo(void *info) -> duckdb_v2_log_sink_write_info_handle { + return static_cast(info); +} + +void *RequireLogSinkUserData(const LogSinkInfo &info) { + auto ptr = info.user_data.get(); + if (!ptr) { + throw InvalidInputException("no user data was set; call LogSink::SetUserData before Register"); + } + return ptr; +} + +template +auto ReadLogEntryId(void *info, GETTER getter) -> std::optional { + idx_t id = 0; + bool present = false; + CheckedAPICall(getter, WriteInfo(info), &id, &present); + if (!present) { + return std::nullopt; + } + return id; +} + +} // namespace + +LogSink::LogSink(void *impl) : detail::Handle(impl) { +} + +LogSink::~LogSink() { + auto _h = handle(); + duckdb_v2_log_sink_destroy(&_h); +} + +auto LogSink::Create(Factory &factory) -> LogSink { + duckdb_v2_log_sink_handle _h = nullptr; + CheckedAPICall(duckdb_v2_log_sink_create, factory.handle(), &_h); + return detail::HandleFactory::Make(_h); +} + +auto LogSink::SetName(const std::string &name) & -> LogSink & { + auto view = ToStr(name); + CheckedAPICall(duckdb_v2_log_sink_set_name, handle(), view.data(), view.size()); + return *this; +} + +auto LogSink::SetUserDataInternal(void *data, void (*destructor)(void *)) -> void { + user_data = detail::UserData(data, destructor); +} + +auto LogSink::SetWriteCallback(WriteCallback callback) & -> LogSink & { + if (!callback) { + CheckedAPICall(duckdb_v2_log_sink_set_write_callback, handle(), nullptr); + write_callback = nullptr; + return *this; + } + + // The C-side callback is one shared trampoline; the user's callback is looked + // up through the info table riding the user_data slot (set by Register). + static auto trampoline = [](duckdb_v2_log_sink_write_info_handle info, void *user_data, int64_t timestamp, + DUCKDB_V2_LOG_LEVEL level, DUCKDB_V2_LOG_SCOPE scope, const char *type, + idx_t type_length, const char *message, idx_t message_length, + duckdb_v2_error_info_handle *err) { + WithExceptionGuard(err, [&]() { + const auto &sink = *static_cast(user_data); + auto entry = detail::HandleFactory::Make( + static_cast(info), user_data, timestamp, static_cast(level), + static_cast(scope), FromStr(type, type_length), FromStr(message, message_length)); + sink.write_callback(entry); + }); + }; + + CheckedAPICall(duckdb_v2_log_sink_set_write_callback, handle(), trampoline); + write_callback = callback; + return *this; +} + +auto LogSink::SetFlushCallback(FlushCallback callback) & -> LogSink & { + if (!callback) { + CheckedAPICall(duckdb_v2_log_sink_set_flush_callback, handle(), nullptr); + flush_callback = nullptr; + return *this; + } + + static auto trampoline = [](duckdb_v2_log_sink_flush_info_handle, void *user_data, + duckdb_v2_error_info_handle *err) { + WithExceptionGuard(err, [&]() { + const auto &info = *static_cast(user_data); + auto input = detail::HandleFactory::Make(user_data); + info.flush_callback(input); + }); + }; + + CheckedAPICall(duckdb_v2_log_sink_set_flush_callback, handle(), trampoline); + flush_callback = callback; + return *this; +} + +auto LogSink::PrepareRegistration() -> void { + // The callback table rides the C user_data slot so the trampolines can find + // it; the user's own data (SetUserData, moved out here) rides inside it. + auto info = std::unique_ptr(new LogSinkInfo(write_callback, flush_callback, std::move(user_data))); + duckdb_v2_opaque opaque {info.get(), detail::TypedDelete, nullptr}; + CheckedAPICall(duckdb_v2_log_sink_set_user_data, handle(), &opaque); + // The storage owns the table now. + info.release(); // NOLINT(bugprone-unused-return-value) +} + +void *LogSink::Entry::GetUserDataInternal() const { + return RequireLogSinkUserData(*static_cast(user_data)); +} + +auto LogSink::Entry::GetTimestamp() const -> timestamp_tz_t { + timestamp_tz_t result; + result.micros = timestamp; + return result; +} + +auto LogSink::Entry::GetLevel() const -> LogLevel { + return level; +} + +auto LogSink::Entry::GetLogType() const -> std::string_view { + return type; +} + +auto LogSink::Entry::GetLogMessage() const -> std::string_view { + return message; +} + +auto LogSink::Entry::GetScope() const -> LogScope { + return scope; +} + +auto LogSink::Entry::GetConnectionId() const -> std::optional { + return ReadLogEntryId(info, duckdb_v2_log_sink_write_info_get_connection_id); +} + +auto LogSink::Entry::GetTransactionId() const -> std::optional { + return ReadLogEntryId(info, duckdb_v2_log_sink_write_info_get_transaction_id); +} + +auto LogSink::Entry::GetQueryId() const -> std::optional { + return ReadLogEntryId(info, duckdb_v2_log_sink_write_info_get_query_id); +} + +auto LogSink::Entry::GetThreadId() const -> std::optional { + return ReadLogEntryId(info, duckdb_v2_log_sink_write_info_get_thread_id); +} + +void *LogSink::FlushInput::GetUserDataInternal() const { + return RequireLogSinkUserData(*static_cast(user_data)); +} + +//---------------------------------------------------------------------------------------------------------------------- +// File System +//---------------------------------------------------------------------------------------------------------------------- + +FileSystem::FileSystem(void *impl) : detail::Handle(impl) { +} + +FileSystem::~FileSystem() { + // Borrowed: the context or connection owns the file system, so there is nothing to release here. +} + +auto FileSystem::CreateOpenOptions() const -> FileOpenOptions { + return FileOpenOptions::Create(*this); +} + +auto FileSystem::Exists(const std::string &path) const -> bool { + auto path_str = ToStr(path); + bool exists = false; + CheckedAPICall(duckdb_v2_file_system_path_exists, handle(), path_str.data(), path_str.size(), &exists); + return exists; +} + +auto FileSystem::IsRemote(const std::string &path) const -> bool { + auto path_str = ToStr(path); + bool is_remote = false; + CheckedAPICall(duckdb_v2_file_system_path_is_remote, handle(), path_str.data(), path_str.size(), &is_remote); + return is_remote; +} + +auto FileSystem::Expand(const std::string &path) const -> std::string { + auto sink = [](const char *text, idx_t text_length, void *user_data, duckdb_v2_error_info_handle *err) { + WithExceptionGuard(err, [&] { + if (text && text_length) { + static_cast(user_data)->assign(text, text_length); + } + }); + }; + auto path_str = ToStr(path); + std::string out; + CheckedAPICall(duckdb_v2_file_system_path_expand, handle(), path_str.data(), path_str.size(), sink, &out); + return out; +} + +auto FileSystem::Glob(const std::string &pattern) const -> std::vector { + auto callback = [](const char *path, idx_t path_length, void *user_data, duckdb_v2_error_info_handle *err) { + WithExceptionGuard( + err, [&] { static_cast *>(user_data)->emplace_back(FromStr(path, path_length)); }); + }; + auto pattern_str = ToStr(pattern); + std::vector matches; + CheckedAPICall(duckdb_v2_file_system_path_glob, handle(), pattern_str.data(), pattern_str.size(), callback, + &matches); + return matches; +} + +auto FileSystem::Move(const std::string &source, const std::string &target) const -> void { + auto source_str = ToStr(source); + auto target_str = ToStr(target); + CheckedAPICall(duckdb_v2_file_system_path_move, handle(), source_str.data(), source_str.size(), target_str.data(), + target_str.size()); +} + +auto FileSystem::Remove(const std::string &path) const -> bool { + auto path_str = ToStr(path); + bool removed = false; + CheckedAPICall(duckdb_v2_file_system_path_remove, handle(), path_str.data(), path_str.size(), &removed); + return removed; +} + +auto FileSystem::OpenFile(const std::string &path, std::initializer_list flags) const -> FileHandle { + auto options = CreateOpenOptions(); + for (auto flag : flags) { + options.SetFlag(flag); + } + return OpenFile(path, options); +} + +auto FileSystem::OpenFile(const std::string &path, const FileOpenOptions &options) const -> FileHandle { + duckdb_v2_file_handle result = nullptr; + auto file_path_str = ToStr(path); + CheckedAPICall(duckdb_v2_file_system_open, handle(), file_path_str.data(), file_path_str.size(), options.handle(), + &result); + return detail::HandleFactory::Make(result); +} + +FileOpenOptions::FileOpenOptions(void *impl) : detail::Handle(impl) { +} + +FileOpenOptions::~FileOpenOptions() { + auto _h = handle(); + duckdb_v2_file_open_options_destroy(&_h); +} + +auto FileOpenOptions::Create(const FileSystem &fs) -> FileOpenOptions { + duckdb_v2_file_open_options_handle _h = nullptr; + CheckedAPICall(duckdb_v2_file_open_options_create, fs.handle(), &_h); + return detail::HandleFactory::Make(_h); +} + +auto FileOpenOptions::SetFlag(FileFlags flag) & -> FileOpenOptions & { + CheckedAPICall(duckdb_v2_file_open_options_set_flag, handle(), static_cast(flag)); + return *this; +} + +auto FileOpenOptions::SetValue(std::string_view name, const Value &value) & -> FileOpenOptions & { + auto name_str = ToStr(name); + CheckedAPICall(duckdb_v2_file_open_options_set_value, handle(), name_str.data(), name_str.size(), value.handle()); + return *this; +} + +namespace { + +//! The field of a file struct that holds the path of the file - every other field is an option to open it with +constexpr const char *FILE_PATH_FIELD = "filename"; + +//! Throws unless the file is a VARCHAR path or a STRUCT, and returns its type +auto GetFileType(const Value &file) -> LogicalType { + if (file.IsNull()) { + throw InvalidInputException("A file cannot be NULL"); + } + auto type = file.GetLogicalType(); + if (type.GetTypeId() != LogicalTypeId::VARCHAR && type.GetTypeId() != LogicalTypeId::STRUCT) { + throw InvalidInputException("A file must be a VARCHAR path or a STRUCT with a \"filename\" field, not " + + type.ToText()); + } + return type; +} + +} // namespace + +auto GetFilePath(const Value &file) -> std::string { + auto type = GetFileType(file); + if (type.GetTypeId() == LogicalTypeId::VARCHAR) { + return std::string(file.Get().view()); + } + for (idx_t i = 0; i < type.GetStructChildCount(); i++) { + if (type.GetStructChildName(i) != FILE_PATH_FIELD) { + continue; + } + auto path = file.GetChild(i); + if (path.IsNull() || path.GetLogicalType().GetTypeId() != LogicalTypeId::VARCHAR) { + break; + } + return std::string(path.Get().view()); + } + throw InvalidInputException("A file struct must have a non-NULL VARCHAR \"filename\" field holding the path of " + "the file"); +} + +auto FileOpenOptions::SetValues(const Value &file) & -> FileOpenOptions & { + auto type = GetFileType(file); + if (type.GetTypeId() == LogicalTypeId::VARCHAR) { + return *this; + } + // validates the path field, so that an invalid file is reported however it is used + GetFilePath(file); + for (idx_t i = 0; i < type.GetStructChildCount(); i++) { + auto name = type.GetStructChildName(i); + if (name == FILE_PATH_FIELD) { + continue; + } + auto option = file.GetChild(i); + if (option.IsNull()) { + // a NULL option is an option that was not specified + continue; + } + SetValue(name, option); + } + return *this; +} + +FileHandle::FileHandle(void *impl) : detail::Handle(impl) { +} + +FileHandle::~FileHandle() { + auto _h = handle(); + duckdb_v2_file_destroy(&_h); +} + +void FileHandle::Sync() { + CheckedAPICall(duckdb_v2_file_sync, handle()); +} + +void FileHandle::Close() { + CheckedAPICall(duckdb_v2_file_close, handle()); +} + +void FileHandle::Seek(idx_t position) { + CheckedAPICall(duckdb_v2_file_seek, handle(), position); +} + +auto FileHandle::Tell() const -> idx_t { + idx_t position = 0; + CheckedAPICall(duckdb_v2_file_tell, handle(), &position); + return position; +} + +auto FileHandle::Size() const -> idx_t { + idx_t size = 0; + CheckedAPICall(duckdb_v2_file_size, handle(), &size); + return size; +} + +auto FileHandle::Read(void *buffer, idx_t size) -> idx_t { + idx_t bytes_read = 0; + CheckedAPICall(duckdb_v2_file_read, handle(), buffer, size, &bytes_read); + return bytes_read; +} + +auto FileHandle::Write(const void *buffer, idx_t size) -> idx_t { + idx_t bytes_written = 0; + CheckedAPICall(duckdb_v2_file_write, handle(), buffer, size, &bytes_written); + return bytes_written; +} + +void FileHandle::ReadAt(void *buffer, idx_t size, idx_t location) { + CheckedAPICall(duckdb_v2_file_read_at, handle(), buffer, size, location); +} + +void FileHandle::WriteAt(const void *buffer, idx_t size, idx_t location) { + CheckedAPICall(duckdb_v2_file_write_at, handle(), buffer, size, location); +} + +//---------------------------------------------------------------------------------------------------------------------- +// Qualified Name +//---------------------------------------------------------------------------------------------------------------------- + +QualifiedName::QualifiedName(void *impl) : detail::Handle(impl) { +} + +QualifiedName::~QualifiedName() { + auto _h = handle(); + duckdb_v2_qname_destroy(&_h); +} + +auto QualifiedName::Parse(std::string_view text) -> QualifiedName { + duckdb_v2_qname_handle _h = nullptr; + auto text_str = ToStr(text); + CheckedAPICall(duckdb_v2_qname_parse, text_str.data(), text_str.size(), &_h); + return detail::HandleFactory::Make(_h); +} + +auto QualifiedName::Create(const std::vector &parts) -> QualifiedName { + StringArrays views(parts.size()); + for (auto &part : parts) { + views.Push(part); + } + duckdb_v2_qname_handle _h = nullptr; + CheckedAPICall(duckdb_v2_qname_create, views.ptrs(), views.lengths(), views.size(), &_h); + return detail::HandleFactory::Make(_h); +} + +auto QualifiedName::GetPartCount() const -> idx_t { + idx_t count = 0; + CheckedAPICall(duckdb_v2_qname_get_part_count, handle(), &count); + return count; +} + +auto QualifiedName::GetPart(idx_t index) const -> std::string_view { + const char *part = nullptr; + idx_t part_length = 0; + CheckedAPICall(duckdb_v2_qname_get_part, handle(), index, &part, &part_length); + return FromStr(part, part_length); +} + +auto QualifiedName::GetName() const -> std::string_view { + return GetPart(GetPartCount() - 1); +} + +auto QualifiedName::Render() const -> std::string { + idx_t length = 0; + CheckedAPICall(duckdb_v2_qname_render, handle(), nullptr, 0, &length); + std::string out(length, '\0'); + CheckedAPICall(duckdb_v2_qname_render, handle(), &out[0], length + 1, &length); + return out; +} + +auto QualifiedName::Equals(const QualifiedName &other) const -> bool { + bool result = false; + CheckedAPICall(duckdb_v2_qname_equals, handle(), other.handle(), &result); + return result; +} + +auto QualifiedName::Hash() const -> uint64_t { + uint64_t hash = 0; + CheckedAPICall(duckdb_v2_qname_hash, handle(), &hash); + return hash; +} + +//---------------------------------------------------------------------------------------------------------------------- +// Table Description +//---------------------------------------------------------------------------------------------------------------------- + +TableDescription::TableDescription(void *impl) : detail::Handle(impl) { +} + +TableDescription::~TableDescription() { + auto _h = handle(); + duckdb_v2_table_description_destroy(&_h); +} + +auto TableDescription::GetQualifiedName() const -> QualifiedName { + duckdb_v2_qname_handle _h = nullptr; + CheckedAPICall(duckdb_v2_table_description_get_qname, handle(), &_h); + return detail::HandleFactory::Make(_h); +} + +auto TableDescription::GetColumnCount() const -> idx_t { + idx_t count = 0; + CheckedAPICall(duckdb_v2_table_description_get_column_count, handle(), &count); + return count; +} + +auto TableDescription::GetColumn(idx_t index) const -> ColumnDescription { + duckdb_v2_column_description_handle _h = nullptr; + CheckedAPICall(duckdb_v2_table_description_get_column, handle(), index, &_h); + return detail::HandleFactory::Make(_h); +} + +auto TableDescription::IsReadOnly() const -> bool { + bool result = false; + CheckedAPICall(duckdb_v2_table_description_is_readonly, handle(), &result); + return result; +} + +//---------------------------------------------------------------------------------------------------------------------- +// Query Metrics +//---------------------------------------------------------------------------------------------------------------------- + +QueryMetrics::QueryMetrics(void *impl) : detail::Handle(impl) { +} + +QueryMetrics::~QueryMetrics() { + auto _h = handle(); + duckdb_v2_query_metrics_destroy(&_h); +} + +auto QueryMetrics::GetRoot() const -> QueryMetricsNode { + duckdb_v2_query_metrics_node_handle _h = nullptr; + CheckedAPICall(duckdb_v2_query_metrics_get_root, handle(), &_h); + return detail::HandleFactory::Make(_h); +} + +QueryMetricsNode::QueryMetricsNode(void *impl) : detail::Handle(impl) { +} + +QueryMetricsNode::~QueryMetricsNode() { + /* Nodes are borrowed from their snapshot, so we don't destroy the handle here */ +} + +auto QueryMetricsNode::GetName() const -> std::string_view { + const char *name = nullptr; + idx_t name_length = 0; + CheckedAPICall(duckdb_v2_query_metrics_node_get_name, handle(), &name, &name_length); + return FromStr(name, name_length); +} + +auto QueryMetricsNode::GetChildCount() const -> idx_t { + idx_t count = 0; + CheckedAPICall(duckdb_v2_query_metrics_node_get_child_count, handle(), &count); + return count; +} + +auto QueryMetricsNode::GetChild(idx_t index) const -> QueryMetricsNode { + duckdb_v2_query_metrics_node_handle _h = nullptr; + CheckedAPICall(duckdb_v2_query_metrics_node_get_child, handle(), index, &_h); + return detail::HandleFactory::Make(_h); +} + +auto QueryMetricsNode::GetMetricCount() const -> idx_t { + idx_t count = 0; + CheckedAPICall(duckdb_v2_query_metrics_node_get_metric_count, handle(), &count); + return count; +} + +auto QueryMetricsNode::GetMetricName(idx_t index) const -> std::string_view { + const char *name = nullptr; + idx_t name_length = 0; + CheckedAPICall(duckdb_v2_query_metrics_node_get_metric_name, handle(), index, &name, &name_length); + return FromStr(name, name_length); +} + +auto QueryMetricsNode::GetMetricValue(idx_t index) const -> Value { + duckdb_v2_value_handle value = nullptr; + CheckedAPICall(duckdb_v2_query_metrics_node_get_metric_value, handle(), index, &value); + return detail::HandleFactory::Make(value); +} + +auto QueryMetricsNode::GetMetric(std::string_view name) const -> std::optional { + const auto name_str = ToStr(name); + duckdb_v2_value_handle value = nullptr; + bool present = false; + CheckedAPICall(duckdb_v2_query_metrics_node_get_metric, handle(), name_str.data(), name_str.size(), &value, + &present); + if (!present) { + return std::nullopt; + } + return detail::HandleFactory::Make(value); +} + +//---------------------------------------------------------------------------------------------------------------------- +// Replacement Scan +//---------------------------------------------------------------------------------------------------------------------- + +namespace { + +// The callback table for one registered scan: rides the C user_data slot so +// the trampoline can find it; the user's own slot (SetUserData) rides inside +// it. Owned by the registered scan, freed when its scope ends. +struct ReplacementScanInfo { + ReplacementScan::Callback callback = nullptr; + detail::UserData user_data; + + ReplacementScanInfo(ReplacementScan::Callback callback, detail::UserData user_data) + : callback(callback), user_data(std::move(user_data)) { + } + + bool operator==(const ReplacementScanInfo &other) const { + return callback == other.callback && user_data.get() == other.user_data.get(); + } +}; + +// Guard for Input::GetUserData: a clear error instead of a null deref. +void *RequireReplacementUserData(const detail::UserData &user_data) { + auto ptr = user_data.get(); + if (!ptr) { + throw InvalidInputException("no user data was set; call ReplacementScan::SetUserData before Register"); + } + return ptr; +} + +} // namespace + +ReplacementScan::ReplacementScan(void *impl) : detail::Handle(impl) { +} + +ReplacementScan::~ReplacementScan() { + auto _h = handle(); + duckdb_v2_replacement_scan_destroy(&_h); +} + +auto ReplacementScan::Create(Factory &factory) -> ReplacementScan { + duckdb_v2_replacement_scan_handle _h = nullptr; + CheckedAPICall(duckdb_v2_replacement_scan_create, factory.handle(), &_h); + return detail::HandleFactory::Make(_h); +} + +auto ReplacementScan::SetUserDataInternal(void *data, void (*destructor)(void *)) -> void { + user_data = detail::UserData(data, destructor); +} + +auto ReplacementScan::SetCallback(Callback callback_p) & -> ReplacementScan & { + if (!callback_p) { + CheckedAPICall(duckdb_v2_replacement_scan_set_callback, handle(), nullptr); + callback = nullptr; + return *this; + } + + // The C-side callback is one shared trampoline; the user's callback is looked + // up through the info table riding the user_data slot (set by Register). + static auto trampoline = [](duckdb_v2_replacement_scan_info_handle info, duckdb_v2_context_handle context, + duckdb_v2_error_info_handle *err) { + WithExceptionGuard(err, [&]() { + void *user_data = nullptr; + CheckedAPICall(duckdb_v2_replacement_scan_get_user_data, info, &user_data); + const auto &scan = *static_cast(user_data); + + auto input = detail::HandleFactory::Make(static_cast(info), static_cast(context)); + scan.callback(input); + }); + }; + + CheckedAPICall(duckdb_v2_replacement_scan_set_callback, handle(), trampoline); + callback = callback_p; + return *this; +} + +auto ReplacementScan::PrepareRegistration() -> void { + // The callback table rides the C user_data slot so the trampoline can find + // it; the user's own data (SetUserData, moved out here) rides inside it. + auto info = std::unique_ptr(new ReplacementScanInfo(callback, std::move(user_data))); + duckdb_v2_opaque opaque {info.get(), detail::TypedDelete, + detail::TypedEquals}; + CheckedAPICall(duckdb_v2_replacement_scan_set_user_data, handle(), &opaque); + // The scan owns the table now. + info.release(); // NOLINT(bugprone-unused-return-value) +} + +void *ReplacementScan::Input::GetUserDataInternal() const { + void *user_data = nullptr; + CheckedAPICall(duckdb_v2_replacement_scan_get_user_data, static_cast(args), + &user_data); + const auto &scan = *static_cast(user_data); + return RequireReplacementUserData(scan.user_data); +} + +auto ReplacementScan::Input::GetName() const -> QualifiedName { + duckdb_v2_qname_handle name = nullptr; + CheckedAPICall(duckdb_v2_replacement_scan_get_name, static_cast(args), + &name); + return detail::HandleFactory::Make(name); +} + +auto ReplacementScan::Input::SetFunctionName(const QualifiedName &name) -> void { + CheckedAPICall(duckdb_v2_replacement_scan_set_function_name, + static_cast(args), name.handle()); +} + +auto ReplacementScan::Input::SetFunctionName(std::string_view name) -> void { + SetFunctionName(QualifiedName::Create({std::string(name)})); +} + +auto ReplacementScan::Input::AddArgument(const Value &value) -> void { + CheckedAPICall(duckdb_v2_replacement_scan_add_argument, static_cast(args), + value.handle()); +} + +auto ReplacementScan::Input::AddNamedArgument(std::string_view name, const Value &value) -> void { + auto name_str = ToStr(name); + CheckedAPICall(duckdb_v2_replacement_scan_add_named_argument, + static_cast(args), name_str.data(), name_str.size(), + value.handle()); +} + +auto ReplacementScan::Input::SetCollection(const ColumnDataCollection &collection, + const std::vector &column_names) -> void { + StringArrays names(column_names.size()); + for (auto &name : column_names) { + names.Push(name); + } + CheckedAPICall(duckdb_v2_replacement_scan_set_collection, static_cast(args), + collection.handle(), names.ptrs(), names.lengths(), names.size()); +} + +auto ReplacementScan::Input::SetSubquery(std::string_view sql) -> void { + auto sql_str = ToStr(sql); + CheckedAPICall(duckdb_v2_replacement_scan_set_subquery, static_cast(args), + sql_str.data(), sql_str.size()); +} + +auto ReplacementScan::Input::SetAlias(std::string_view alias) -> void { + auto alias_str = ToStr(alias); + CheckedAPICall(duckdb_v2_replacement_scan_set_alias, static_cast(args), + alias_str.data(), alias_str.size()); +} + +auto ReplacementScan::Input::GetContext() -> Context & { + return context; +} + +//---------------------------------------------------------------------------------------------------------------------- +// Appender +//---------------------------------------------------------------------------------------------------------------------- + +namespace { + +// Parses exactly one statement out of `sql`. +auto ParseSingleStatement(Connection &conn, const std::string &sql) -> SqlStatement { + auto statements = conn.ParseSQL(sql); + auto first = statements.Next(); + if (!first) { + throw InvalidInputException("the appender's query contains no statement"); + } + if (statements.Next()) { + throw InvalidInputException("the appender's query must contain exactly one statement"); + } + return first; +} + +// The name the table constructor's INSERT reads the buffer under. +constexpr const char *TABLE_APPENDER_BUFFER_NAME = "__duckdb_appender_buffer"; + +} // namespace + +Appender::Appender(Connection &conn, std::string_view query, std::vector column_types, + std::string_view buffer_name, const std::vector &column_names) { + Initialize(conn, std::string(query), std::move(column_types), std::string(buffer_name), column_names); +} + +void Appender::Initialize(Connection &conn, const std::string &query, std::vector column_types, + const std::string &buffer_name, const std::vector &column_names) { + connection = &conn; + types = std::move(column_types); + if (types.empty()) { + throw InvalidInputException("an appender needs at least one column type"); + } + + collection = std::make_unique(conn.GetFactory(), types); + + // Parsed once and re-executed per flush. + statement = std::make_unique(ParseSingleStatement(conn, query)); + statement->AddCollection(buffer_name, *collection, column_names); + append_state = std::make_unique(collection->CreateAppendState()); +} + +namespace { + +// The table constructor's two derived pieces: the buffer's columns, and the INSERT that drains it. +struct AppenderTablePlan { + std::vector types; + std::vector column_names; + std::string query; + std::string buffer_name; +}; + +AppenderTablePlan PlanTableAppender(Connection &conn, std::string_view table) { + AppenderTablePlan plan; + plan.buffer_name = TABLE_APPENDER_BUFFER_NAME; + + // Bind rather than execute: it resolves the table and reports its columns without reading a row. + auto probe = ParseSingleStatement(conn, "SELECT * FROM " + std::string(table)); + auto signature = conn.Bind(probe); + auto &schema = signature.output; + if (schema.GetFieldCount() == 0) { + throw InvalidInputException("table " + std::string(table) + " has no columns to append to"); + } + + std::string columns; + for (idx_t i = 0; i < schema.GetFieldCount(); i++) { + if (i > 0) { + columns += ", "; + } + columns += RenderQuotedIdentifier(schema.GetFieldName(i)); + plan.column_names.emplace_back(schema.GetFieldName(i)); + plan.types.push_back(schema.GetFieldType(i)); + } + plan.query = "INSERT INTO " + std::string(table) + " (" + columns + ") SELECT * FROM " + plan.buffer_name; + return plan; +} + +} // namespace + +Appender::Appender(Connection &conn, std::string_view table) { + auto plan = PlanTableAppender(conn, table); + Initialize(conn, plan.query, std::move(plan.types), plan.buffer_name, plan.column_names); +} + +Appender::~Appender() = default; + +void Appender::ResetBuffer() { + // Drop the append state first: it references the segments the clear releases. + append_state.reset(); + collection->Clear(); + try { + append_state = std::make_unique(collection->CreateAppendState()); + } catch (...) { + broken = true; + throw; + } +} + +void Appender::AppendChunk(DataChunk &chunk) { + if (broken) { + throw InvalidInputException("the appender is broken after a failed buffer operation; Clear or destroy it"); + } + try { + // The append validates the chunk's columns against the buffer and refuses a mismatch before copying. + collection->Append(*append_state, chunk); + } catch (const Exception &ex) { + // A validation refusal leaves the buffer untouched; anything else may have copied part of the chunk. + if (ex.GetCode() != DUCKDB_V2_ERROR_INPUT_INVALID) { + broken = true; + } + throw; + } catch (...) { + broken = true; + throw; + } +} + +void Appender::Flush() { + if (broken) { + throw InvalidInputException("the appender is broken after a failed buffer operation; Clear or destroy it"); + } + if (collection->GetRowCount() == 0) { + return; + } + try { + connection->Execute(*statement).Drain(); + } catch (const Exception &ex) { + // A busy connection or an interrupted run keeps the rows so the flush can be retried; any other failure drops + // them, so a retry does not re-run the same failing statement over the same rows. + if (ex.GetCode() != DUCKDB_V2_ERROR_RESOURCE_IN_USE && ex.GetCode() != DUCKDB_V2_ERROR_RUNTIME_INTERRUPT) { + ResetBuffer(); + } + throw; + } catch (...) { + ResetBuffer(); + throw; + } + ResetBuffer(); +} + +void Appender::Clear() { + ResetBuffer(); + broken = false; +} + +//---------------------------------------------------------------------------------------------------------------------- +// Column Description +//---------------------------------------------------------------------------------------------------------------------- + +ColumnDescription::ColumnDescription(void *impl) : detail::Handle(impl) { +} + +ColumnDescription::~ColumnDescription() { + auto _h = handle(); + duckdb_v2_column_description_destroy(&_h); +} + +auto ColumnDescription::GetName() const -> std::string_view { + const char *name = nullptr; + idx_t name_length = 0; + CheckedAPICall(duckdb_v2_column_description_get_name, handle(), &name, &name_length); + return FromStr(name, name_length); +} + +auto ColumnDescription::GetType() const -> LogicalType { + duckdb_v2_logical_type_handle borrowed = nullptr; + CheckedAPICall(duckdb_v2_column_description_get_type, handle(), &borrowed); + // get_type borrows the type; copy it into an owned handle the wrapper manages. + duckdb_v2_logical_type_handle owned = nullptr; + CheckedAPICall(duckdb_v2_logical_type_copy, borrowed, &owned); + return detail::HandleFactory::Make(owned); +} + +auto ColumnDescription::HasDefault() const -> bool { + bool result = false; + CheckedAPICall(duckdb_v2_column_description_has_default, handle(), &result); + return result; +} + +auto ColumnDescription::HasGenerated() const -> bool { + bool result = false; + CheckedAPICall(duckdb_v2_column_description_has_generated, handle(), &result); + return result; +} + +} // namespace cxx +} // namespace duckdb diff --git a/src/duckdb/tools/cpp/duckdb_cpp.hpp b/src/duckdb/tools/cpp/duckdb_cpp.hpp new file mode 100644 index 000000000..576705cf5 --- /dev/null +++ b/src/duckdb/tools/cpp/duckdb_cpp.hpp @@ -0,0 +1,7729 @@ +#pragma once + +//---------------------------------------------------------------------------------------------------------------------- +// 8888888b. 888 8888888b. 888888b. d8888 8888888b. 8888888 +// 888 "Y88b 888 888 "Y88b 888 "88b d88888 888 Y88b 888 +// 888 888 888 888 888 888 .88P d88P888 888 888 888 +// 888 888 888 888 .d8888b 888 888 888 888 8888888K. d88P 888 888 d88P 888 +// 888 888 888 888 d88P" 888 .88P 888 888 888 "Y88b d88P 888 8888888P" 888 +// 888 888 888 888 888 888888K 888 888 888 888 d88P 888 888 888 +// 888 .d88P Y88b 888 Y88b. 888 "88b 888 .d88P 888 d88P d8888888888 888 888 +// 8888888P" "Y88888 "Y8888P 888 888 8888888P" 8888888P" d88P 888 888 8888888 +//---------------------------------------------------------------------------------------------------------------------- + +/// @file duckdb_cpp.hpp +/// The DuckDB C++ API. +/// +/// Most classes here are handles: move-only, never copied and never reference-counted. A handle is either owning, +/// releasing its resource when destroyed, or borrowed, in which case its documentation says what it borrows from and +/// how long it stays valid. Whether a handle currently holds a resource is reported by its `explicit operator bool`. +/// The remaining types (`Exception`, `Signature`, the primitive value types, and the like) are ordinary copyable +/// values. +/// +/// Errors are reported by throwing; no function returns an error code. Everything thrown derives from `Exception`. +/// Failures that are part of a function's contract are documented with `\@throws`; any other failure surfaces as a +/// plain `Exception`. +/// +/// The usual path through the API: open an `Instance`, which hands out `Connection`s, and a `Connection` parses and +/// executes SQL into a streaming `QueryResult` that yields `DataChunk`s of `Vector`s. + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +// Arrow C Data and C Stream Interface structs. Forward declared only: the definitions come from `duckdb_v2.h` or from +// the consumer's own Arrow headers, under the standard ARROW_C_DATA_INTERFACE and ARROW_C_STREAM_INTERFACE guards. +struct ArrowSchema; +struct ArrowArray; +struct ArrowArrayStream; + +// defines DELETE and IGNORE, which StatementType and FunctionCollationHandling name: keep the macros out of +// this header, whatever the include order. +#ifdef DELETE +#pragma push_macro("DELETE") +#undef DELETE +#define DUCKDB_CPP_RESTORE_DELETE_MACRO +#endif +#ifdef IGNORE +#pragma push_macro("IGNORE") +#undef IGNORE +#define DUCKDB_CPP_RESTORE_IGNORE_MACRO +#endif + +namespace duckdb { +namespace cxx { + +//---------------------------------------------------------------------------------------------------------------------- +// Common Typedefs and forward declarations +//---------------------------------------------------------------------------------------------------------------------- + +/// Row indices, offsets, counts and sizes throughout the API. +typedef uint64_t idx_t; + +class Exception; +class OptionDescription; +struct OptionValue; +class Config; +class CustomOption; +class Environment; +class Instance; +class Connection; +class SqlStatement; +class StatementIterator; +class Schema; +class Signature; +class LogicalType; +class Value; +class Vector; +class Arena; +class DataChunk; +class ColumnDataCollection; +class QueryResult; +class ArrowResult; +class PreparedStatement; +class ArrowImporter; +class ArrowExporter; + +struct TypeParam; +struct NamedParam; +struct ArrowFormat; + +enum class LogicalTypeId : uint32_t; +enum class CastMode : uint8_t; + +template +class TypeBuilder; +class CustomType; +class CastFunction; +class PragmaFunction; +class LogSink; +class MacroFunction; +class ReplacementScan; +class QualifiedName; +class TableDescription; +class ColumnDescription; +class QueryMetrics; +class QueryMetricsNode; +class FileSystem; +class FileHandle; +class FileOpenOptions; +class MultiFileFunction; +class ScalarFunction; +class AggregateFunction; +class TableFunction; +class CopyFunction; +class Factory; +class Extension; +class Stats; + +//---------------------------------------------------------------------------------------------------------------------- +// Internal Implementation Details +//---------------------------------------------------------------------------------------------------------------------- + +/// @internal +/// Everything in `duckdb::cxx::detail` is an implementation detail: not part of the public API, and subject to change +/// without notice. +namespace detail { + +/// @internal +/// Maps a C++ wrapper type to its underlying C-API handle type. The primary template is intentionally left undefined: +/// each wrapper specializes it in the .cpp, so C handle types never have to appear in this header. +template +struct HandleTraits; + +/// @internal +/// Base class of every wrapper in this API: move-only custody of a single opaque handle. +template +class Handle { +public: + friend TYPE; + + Handle(const Handle &) = delete; + Handle &operator=(const Handle &) = delete; + + Handle(Handle &&other) noexcept : impl(other.impl) { + other.impl = nullptr; + } + + Handle &operator=(Handle &&other) noexcept { + std::swap(impl, other.impl); + return *this; + } + + virtual ~Handle() noexcept = default; + + /// @internal The underlying C-API handle, typed indirectly through HandleTraits. + template > + auto handle() const -> typename TR::handle { + return static_cast(impl); + } + + /// True while this wrapper holds a handle; false once it has been moved from. + explicit operator bool() const noexcept { + return impl != nullptr; + } + +private: + Handle() : impl(nullptr) { + } + explicit Handle(void *impl) : impl(impl) { + } + + /// @internal Detaches the handle and leaves this wrapper empty, for calls where the C API takes ownership. + auto release() noexcept -> void * { + auto *detached = impl; + impl = nullptr; + return detached; + } + void *impl; +}; + +/// @internal +/// Grants the .cpp access to the wrappers' private constructors, without making them public. `Handle::release` is not +/// reachable from here -- only the wrapper type itself befriends its `Handle` base, so calls where the C API takes +/// ownership release from inside a member of the consuming wrapper. +struct HandleFactory { + template + static auto Make(ARGS &&...args) -> T { + return T(std::forward(args)...); + } +}; + +template +struct always_false : std::false_type {}; + +/// @internal +/// Deletes `ptr` as a `T *`: the destructor shape the C API's opaque data slots take. +template +void TypedDelete(void *ptr) { + delete static_cast(ptr); +} + +/// @internal +/// Compares two `T *` by `operator==`: the equality shape the C API's opaque data slots take. +template +bool TypedEquals(void *ptr_a, void *ptr_b) { + return *static_cast(ptr_a) == *static_cast(ptr_b); +} + +/// @internal +/// Whether `const T` supports `operator==`. +template +struct is_equality_comparable : std::false_type {}; +template +struct is_equality_comparable() == std::declval())>> + : std::true_type {}; + +/// @internal +/// The equals callback for a `T`-typed opaque slot: `TypedEquals` when `T` is equality-comparable, null otherwise, +/// which makes the engine fall back to comparing the slots by identity. +/// @internal +/// Names `const Vector &` once per element of a type pack: lets a function declare exactly one vector parameter per +/// argument type. Routed through a class template so the pack expansion is a non-deduced context on every compiler: +/// MSVC misaligns a plain alias-template pack against the call arguments instead of fixing its length from the +/// explicitly given type list. +template +struct VectorPerArgImpl { + using type = const Vector &; +}; +template +using VectorPerArg = typename VectorPerArgImpl::type; + +template +constexpr auto SelectEquals() -> bool (*)(void *, void *) { + if constexpr (is_equality_comparable::value) { + return TypedEquals; + } else { + return nullptr; + } +} + +/// @internal +/// Move-only custody of a user-provided pointer plus the destructor that frees it. +class UserData { +public: + UserData() : data(nullptr), destructor(nullptr) { + } + UserData(void *data, void (*destructor)(void *)) : data(data), destructor(destructor) { + } + + UserData(const UserData &) = delete; + UserData &operator=(const UserData &) = delete; + + UserData(UserData &&other) noexcept : data(other.data), destructor(other.destructor) { + other.data = nullptr; + other.destructor = nullptr; + } + + UserData &operator=(UserData &&other) noexcept { + if (this != &other) { + if (data && destructor) { + destructor(data); + } + data = other.data; + destructor = other.destructor; + other.data = nullptr; + other.destructor = nullptr; + } + return *this; + } + + ~UserData() { + if (data && destructor) { + destructor(data); + } + } + + auto get() const -> void * { + return data; + } + +private: + void *data; + void (*destructor)(void *); +}; + +} // namespace detail + +//---------------------------------------------------------------------------------------------------------------------- +// Exceptions +//---------------------------------------------------------------------------------------------------------------------- +// Every failure in this API is reported by throwing. Catch `Exception` to handle any of them; the subclasses single +// out the cases worth reacting to on their own. +// TODO: add more exception types! + +/// Base class of all errors thrown by DuckDB. For errors raised by the database engine, `what()` carries the fully +/// formatted message, prefix included, e.g. "Parser Error: ...". +class Exception : public std::runtime_error { +public: + /// @param code The numeric error code. + /// @param message The full message, as later returned by `what()`. + /// @param raw_message The message body without the error-type prefix, when available. + Exception(const int code, const std::string &message, std::string raw_message = {}) + : std::runtime_error(message), code(code), raw_message(std::move(raw_message)) { + } + + /// The numeric error code identifying the kind of error. Prefer catching a typed subclass where one exists. + auto GetCode() const -> int { + return code; + } + + /// The message body alone, without the "Catalog Error:" / "Parser Error:" / ... prefix that `what()` carries. + /// Empty when no raw message is available. + auto GetRawMessage() const -> const std::string & { + return raw_message; + } + +private: + int code; + std::string raw_message; +}; + +/// Invalid input: a malformed SQL string, an argument of the wrong kind, a misused handle, and the like. +class InvalidInputException : public Exception { +public: + explicit InvalidInputException(const std::string &message, std::string raw_message = {}); +}; + +/// A running query was canceled, e.g. by `Connection::Interrupt`. +class InterruptException : public Exception { +public: + explicit InterruptException(const std::string &message, std::string raw_message = {}); +}; + +//---------------------------------------------------------------------------------------------------------------------- +// Instance Option +//---------------------------------------------------------------------------------------------------------------------- +// Configuration settings. Reached through the `Config` of an `Instance`, a `Connection` or a `Context`: `SetOption` +// writes one, `GetOption` reads its current value and the scope it came from, and `DescribeOption` describes it +// -- its default value, description, the scopes it may be written at, and aliases. Settings that can only be chosen at +// startup are passed to the `Instance` constructor. + +/// The scope a setting is written at, or its value was read from. +enum class SettingScope : uint8_t { + /// Write only: the setting's default scope (not its default value), exactly like SQL `SET name = value`. + DEFAULT = 0, + /// The whole database, like SQL `SET GLOBAL`. + GLOBAL = 1, + /// One connection's session, like SQL `SET SESSION`. + SESSION = 2, +}; + +/// The description of a configuration setting, as DuckDB declares it: the same from every source, and without its +/// current value (read that with `GetOption`). Read-only. +/// The string accessors return views borrowed from this option, valid until it is destroyed. +class OptionDescription final : public detail::Handle { + friend detail::HandleFactory; + +public: + OptionDescription(OptionDescription &&) noexcept = default; + OptionDescription &operator=(OptionDescription &&) noexcept = default; + + /// The setting's name. + auto GetName() const -> std::string_view; + + /// The value the setting falls back to when it is not set. NULL when the setting declares no default. + auto GetDefaultValue() const -> Value; + + /// A human-readable description of the setting. + auto GetDescription() const -> std::string_view; + + /// Whether the setting may be written at a scope. + /// @param scope GLOBAL or SESSION; DEFAULT asks whether it may be written at all. + auto SupportsScope(SettingScope scope) const -> bool; + + /// The scope a write at `SettingScope::DEFAULT` goes to: GLOBAL or SESSION. + auto GetDefaultScope() const -> SettingScope; + + /// How many alternative names resolve to this setting. 0 for an extension setting. + auto GetAliasCount() const -> size_t; + + /// One of the setting's aliases. + /// @param index Alias index in [0, GetAliasCount()). + auto GetAliasByIndex(size_t index) const -> std::string_view; + + ~OptionDescription() override; + +private: + explicit OptionDescription(void *impl); +}; + +/// A borrowed handle to the scope config settings are read from and written at: taken from an `Instance` (the GLOBAL +/// scope alone), a `Connection` or a `Context` (that client's cascade), and valid for as long as its source is. +class Config final : public detail::Handle { + friend detail::HandleFactory; + +public: + ~Config() override; + Config(Config &&) noexcept = default; + Config &operator=(Config &&) noexcept = default; + + /// How many settings this config's database exposes. + auto GetOptionCount() const -> size_t; + + /// The description of one setting. + /// @param index Setting index in [0, GetOptionCount()). + auto DescribeOption(size_t index) const -> OptionDescription; + + /// The description of one setting. + /// @param name The setting's name or one of its aliases; an alias resolves to the canonical setting. + /// @throws InvalidInputException When no setting goes by that name. + auto DescribeOption(std::string_view name) const -> OptionDescription; + + /// The current value of a setting in this config, and the scope it was read from. + /// @param name The setting's name or one of its aliases. + /// @throws InvalidInputException When no setting goes by that name. + auto GetOption(std::string_view name) const -> OptionValue; + + /// `GetOption` for a name that may not be a setting: an empty optional instead of an exception. + /// @param name The setting's name or one of its aliases. + auto TryGetOption(std::string_view name) const -> std::optional; + + /// Shorthand for `GetOption`. + auto operator[](std::string_view name) const -> OptionValue; + + /// Writes a setting in this config. + /// @param name The setting to write, either its canonical name or one of its aliases. + /// @param value The new value, cast to the setting's type as SQL `SET` does. + /// @param scope GLOBAL to write it database-wide, SESSION for one session only, or DEFAULT for the setting's + /// default scope. An `Instance`'s config supports only GLOBAL. + /// @throws Exception When no setting goes by that name, the value does not cast, or the scope is not supported. + auto SetOption(std::string_view name, const Value &value, SettingScope scope = SettingScope::DEFAULT) -> void; + /// The text overload of the above, for a value in the textual form SQL `SET` accepts. + auto SetOption(std::string_view name, std::string_view value, SettingScope scope = SettingScope::DEFAULT) -> void; + +private: + explicit Config(void *impl); +}; + +//---------------------------------------------------------------------------------------------------------------------- +// Context +//---------------------------------------------------------------------------------------------------------------------- +// The client context of an operation in flight, handed to code that DuckDB calls back into. +// It is more or less equivalent to a `Connection`, but viewed from the "inside" of the system. + +/// The severity of a log message, compared against the database's configured threshold. +enum class LogLevel : uint32_t { + LOG_TRACE = 10, + LOG_DEBUG = 20, + LOG_INFO = 30, + LOG_WARNING = 40, + LOG_ERROR = 50, + LOG_FATAL = 60, +}; + +/// A borrowed handle to the scope values, types and data chunks are created in: taken from an `Instance`, a +/// `Connection` or a `Context`, and valid for as long as its source is. A factory resolves in the scope of its source: +/// a connection's or a context's factory reaches the catalog and the client's settings, while an instance's factory +/// knows only the built-in types and casts. +class Factory final : public detail::Handle { + friend detail::HandleFactory; + +public: + ~Factory() override; + Factory(Factory &&) noexcept = default; + Factory &operator=(Factory &&) noexcept = default; + + /// Parses a SQL type expression into an owned type: primitives, parameterized kinds, and extension types alike. + /// @param text A type as SQL spells it, e.g. "DECIMAL(18, 3)" or "STRUCT(a INTEGER, b VARCHAR)". + /// @return The parsed type. + /// @throws Exception When the text does not name a type. + auto ParseType(std::string_view text) const -> LogicalType; + + /// Builds a type from a type name plus parameters. Like a structured version of `ParseType` + /// @param name The type's unqualified name, e.g. "LIST" or "DECIMAL". + /// @param params The type's parameters, in the order SQL takes them. A `TypeParam` with an empty name is considered + /// a positional parameter. + auto CreateType(std::string_view name, const std::vector ¶ms) const -> LogicalType; + /// Parameterless overload of the above. + auto CreateType(std::string_view name) const -> LogicalType; + + /// `CreateType` for a name that may be catalog- or schema-qualified. An unqualified name is resolved along the + /// search path and then in the system catalog; a qualified one is resolved exactly as written. + auto CreateType(const QualifiedName &name, const std::vector ¶ms) const -> LogicalType; + /// Parameterless overload of the above. + auto CreateType(const QualifiedName &name) const -> LogicalType; + + /// The id-keyed twin of `CreateType`: the id resolves to its canonical name and binds like it. + /// @param id The type's id. Without parameters, only ids that name a complete type on their own are accepted; + /// parameterized kinds such as LIST or DECIMAL require parameters. + /// @param params The type's parameters, as in the name-keyed overload. + auto CreateType(LogicalTypeId id, const std::vector ¶ms) const -> LogicalType; + /// Parameterless overload of the above. + auto CreateType(LogicalTypeId id) const -> LogicalType; + + /// Starts composing a type step by step. + /// @return A `TypeBuilder` over this factory, for composing a nested type without assembling the parameter vector + /// by hand. + auto CreateType() -> TypeBuilder; + + /// Creates a `Value` with this factory; see `Value::Create` for the accepted C++ types. + /// @param value The C++ value to convert. + template + auto CreateValue(T &&value) -> Value; + + /// Creates an empty chunk with a column per type; see `DataChunk(Factory &, types)`. + /// @param types One type per column. Types containing ANY are rejected. + auto CreateDataChunk(const std::vector &types) -> DataChunk; + + /// Creates an empty collection; see `ColumnDataCollection(Factory &, types)`. + /// @param types One type per column, at least one. Types containing ANY are rejected. + auto CreateColumnDataCollection(const std::vector &types) -> ColumnDataCollection; + +private: + explicit Factory(void *impl); +}; + +/// A borrowed handle to a client context: the one a callback is handed, valid only for the duration of that callback. +class Context final : public detail::Handle { + friend detail::HandleFactory; + +public: + ~Context() override; + Context(Context &&) noexcept = default; + Context &operator=(Context &&) noexcept = default; + + /// The config of this context: its connection's cascade. + auto GetConfig() -> Config & { + return config; + } + /// Const overload of the above: a const config reads settings, but does not write them. + auto GetConfig() const -> const Config & { + return config; + } + + /// The file system this context reads and writes through. Borrowed, and valid only while the context is. + auto GetFileSystem() const -> FileSystem; + + /// The factory values, types and data chunks are created through in this context. + auto GetFactory() -> Factory & { + return factory; + } + + /// Writes a message to DuckDB's log, readable through `SELECT * FROM duckdb_logs`. + /// Whether the entry is recorded is up to the database's log configuration; a message it filters out is dropped + /// without error. + /// @param level The severity of the message. + /// @param message The message body. + /// @param log_type The log type to record under, matched case-sensitively. Empty selects the default type. + auto Log(LogLevel level, std::string_view message, std::string_view log_type = {}) const -> void; + +private: + explicit Context(void *impl); + + Factory factory; + Config config; +}; + +//---------------------------------------------------------------------------------------------------------------------- +// Custom Option +//---------------------------------------------------------------------------------------------------------------------- + +/// A configuration setting of your own. Create one through a `Factory` of the database it will be registered in, +/// describe it (name, type, default value, scopes), then register it with `Connection::Register` or +/// `Extension::Register`. From then on it is a setting like any other: read and written through a `Config` and from +/// SQL with `SET` and `RESET`, and described by `Config::DescribeOption`. +/// +/// Registration is not transactional: a registered option is visible to every connection at once, is not undone by a +/// rollback, and lives for as long as the database does. +class CustomOption final : public detail::Handle { + friend detail::HandleFactory; + friend class Connection; + friend class Extension; + +public: + class UpdateInput; + + /// Called whenever the option is set or reset, after the new value is cast to the option's type and before it is + /// stored. May replace the value through `UpdateInput::SetValue`, or refuse it by throwing. Not called for the + /// default value at registration, nor for a value given to the database at startup. Must not write settings + /// itself. + using UpdateCallback = void (*)(UpdateInput &input); + + CustomOption(CustomOption &&) noexcept = default; + CustomOption &operator=(CustomOption &&) noexcept = default; + + ~CustomOption() override; + + /// Creates an empty CustomOption through `factory`. Register it through a `Connection` or an `Extension` of the + /// factory's database. + static auto Create(Factory &factory) -> CustomOption; + + /// Sets the option's name, as `SET` and `Config` refer to it. + auto SetName(const std::string &name) & -> CustomOption &; + /// Sets the type every value written to the option is cast to. Optional when a default value is set, whose type + /// the option then takes. + auto SetType(const LogicalType &type) & -> CustomOption &; + /// Sets the value the option has until it is set, and that `RESET` restores. Cast to the option's type at + /// registration. Without one, the option reads as NULL until it is set. + auto SetDefaultValue(const Value &value) & -> CustomOption &; + /// Sets the description `OptionDescription::GetDescription` and `duckdb_settings()` report. + auto SetDescription(std::string_view description) & -> CustomOption &; + /// Sets the scope a write at `SettingScope::DEFAULT` goes to: GLOBAL or SESSION, and one the option supports. + /// Defaults to SESSION, or to GLOBAL when the option does not support SESSION. + auto SetDefaultScope(SettingScope scope) & -> CustomOption &; + /// Sets whether the option can be written at a scope, GLOBAL or SESSION. Both are supported unless told otherwise. + auto SetSupportsScope(SettingScope scope, bool supported) & -> CustomOption &; + + /// Constructs user data of type `T`, carried by the registered option and freed at database teardown; read it from + /// the update callback via `UpdateInput::GetUserData`. Consumed by registration: set it again before + /// re-registering. + template + auto SetUserData(ARGS &&...args) & -> CustomOption & { + auto ptr = new T(std::forward(args)...); + SetUserDataInternal(ptr, detail::TypedDelete); + return *this; + } + + auto SetUpdateCallback(UpdateCallback callback) & -> CustomOption &; + +private: + explicit CustomOption(void *impl); + //! Moves what the callback needs into the C handle, right before it is registered. + auto PrepareRegistration() -> void; + + auto SetUserDataInternal(void *data, void (*destructor)(void *)) -> void; + + UpdateCallback update_callback = nullptr; + detail::UserData user_data; + +public: + /// What the update callback works with. Borrowed, valid only for the callback duration. + class UpdateInput { + friend detail::HandleFactory; + + public: + /// The user data set via `CustomOption::SetUserData`. + /// @throws InvalidInputException When none was set. + template + auto GetUserData() const -> T & { + return *static_cast(GetUserDataInternal()); + } + + /// The value the option is updated to, cast to its type. On a reset, the default value, which may be NULL. + auto GetValue() const -> Value; + /// Replaces the value the option is updated to. Cast to the option's type. + auto SetValue(const Value &value) -> void; + /// The scope the value is written at: GLOBAL or SESSION, a DEFAULT write resolved to the default scope. + auto GetScope() const -> SettingScope; + /// Whether the update is a reset to the default value, like SQL `RESET`. + auto IsReset() const -> bool; + + /// The context setting the option. When the option is written through the config of an `Instance`, or given + /// at startup, this is an internal context whose session state is discarded after the update. Borrowed, valid + /// only for the callback duration. + auto GetContext() -> Context &; + + private: + UpdateInput(void *args, void *context) : args(args), context(detail::HandleFactory::Make(context)) { + } + + void *args; + Context context; + + void *GetUserDataInternal() const; + }; +}; + +//---------------------------------------------------------------------------------------------------------------------- +// SQL statements +//---------------------------------------------------------------------------------------------------------------------- +// A SQL string is parsed once into statements, which can then be bound or executed repeatedly. Parsing is purely +// syntactic: it touches no catalog and opens no transaction, so unknown tables and type errors surface at bind or +// execution time instead. + +/// The kind of a SQL statement, as the parser classifies it. +enum class StatementType : uint8_t { + INVALID = 0, + SELECT = 1, + INSERT = 2, + UPDATE = 3, + CREATE = 4, + DELETE = 5, + PREPARE = 6, + EXECUTE = 7, + ALTER = 8, + TRANSACTION = 9, + COPY = 10, + ANALYZE = 11, + VARIABLE_SET = 12, + CREATE_FUNC = 13, + EXPLAIN = 14, + DROP = 15, + EXPORT = 16, + PRAGMA = 17, + VACUUM = 18, + CALL = 19, + SET = 20, + LOAD = 21, + RELATION = 22, + EXTENSION = 23, + LOGICAL_PLAN = 24, + ATTACH = 25, + DETACH = 26, + MULTI = 27, + COPY_DATABASE = 28, + UPDATE_EXTENSIONS = 29, + MERGE_INTO = 30, + CONNECT = 31, + DISCONNECT = 32, + EXTERNAL_RESOURCE = 33, +}; + +/// An owned, parsed SQL statement, produced by `StatementIterator::Next` and executed by `Connection::Execute`. +/// Executing borrows the statement, so the same one can be executed any number of times. +class SqlStatement final : public detail::Handle { + friend detail::HandleFactory; + +public: + SqlStatement(SqlStatement &&) noexcept = default; + SqlStatement &operator=(SqlStatement &&) noexcept = default; + + ~SqlStatement() override; + + /// The parser's classification of the statement, available without binding. It is the type before the rewrites + /// execution applies, so a PRAGMA reports PRAGMA; `QueryResult::GetStatementType` reports what it became. + auto GetStatementType() const -> StatementType; + + /// The statement's own text: its slice of the parsed string, from its first token up to the first token of the + /// next statement or the end of the input, so a trailing `;` and the whitespace after it are included. + /// @return A view borrowed from this statement, valid until it is destroyed. + auto GetText() const -> std::string_view; + + /// The names of the statement's parameters, in binding order: the order of `Connection::Bind`'s `parameters` + /// schema, so element i here names field i there. "1", "2", ... for positional parameters ($1 or ?), the + /// identifier for named ones ($name). Parse-time, so it needs no catalog; only the types wait for `Bind`. + /// @return Views borrowed from this statement, valid until it is destroyed. + auto GetParameterNames() const -> std::vector; + + /// Makes a collection visible to the statement as a table named `name`, as a common table expression. Each + /// execution reads the collection's contents at that moment, so a prepared statement can run again after the + /// collection was cleared and refilled. Only SELECT, INSERT, UPDATE, DELETE and MERGE INTO statements accept one. + /// @param name The name the statement refers to the collection by; it shadows a catalog table of that name. + /// @param collection Borrowed: it must outlive this statement, every statement copied or prepared from it, and + /// every result executing it, and must not be cleared or reset while such a result is live. + /// @param column_names Names for the collection's columns, one per column; empty names them col1..colN. + /// @throws InvalidInputException For another statement type, a name the statement already defines, or a + /// mismatched number of column names. + auto AddCollection(std::string_view name, const ColumnDataCollection &collection, + const std::vector &column_names = {}) -> void; + +private: + explicit SqlStatement(void *impl); +}; + +/// An owned iterator over the statements in a SQL string, produced by `Connection::ParseSQL`. +/// Statements it has already yielded are independent of it and stay valid after the iterator is destroyed. +class StatementIterator final : public detail::Handle { + friend detail::HandleFactory; + +public: + StatementIterator(StatementIterator &&) noexcept = default; + StatementIterator &operator=(StatementIterator &&) noexcept = default; + + ~StatementIterator() override; + + /// The next statement, or an empty handle once the string is exhausted; calling it again then keeps returning + /// empty. + /// @throws Exception When the next statement does not parse; the iterator is exhausted afterwards. + auto Next() -> SqlStatement; + +private: + explicit StatementIterator(void *impl); +}; + +/// The lexical class of a token, as `Connection::Tokenize` reports it: what the tokenizer assigns before parsing, with +/// no catalog or grammar-role refinement. +enum class TokenType : uint8_t { + /// Never the class of a token; the value of a zero-initialized `Token`. + INVALID = 0, + /// A keyword of the connection's grammar. + KEYWORD = 1, + /// A bare or double-quoted identifier, quotes included. + IDENTIFIER = 2, + /// A quoted or dollar-quoted string, delimiters included. + STRING_LITERAL = 3, + /// A numeric literal. + NUMBER_LITERAL = 4, + /// An operator or punctuation run other than the statement terminator. + OPERATOR = 5, + /// A line or block comment, delimiters included. + COMMENT = 6, + /// A statement-terminating semicolon. + TERMINATOR = 7, +}; + +/// One token of a SQL string: its class and its byte range in the input, so `sql.substr(start, length)` is the lexeme. +struct Token { + /// The token's lexical class. + TokenType type = TokenType::INVALID; + /// Byte offset of the token in the input. + idx_t start = 0; + /// Byte length of the token. + idx_t length = 0; +}; + +/// The tokens of a SQL string, as `Connection::Tokenize` reports them. +struct TokenList { + /// The tokens in input order; empty for empty or whitespace-only input. + std::vector tokens; + /// Whether the input ended before the closing delimiter of its last token: inside an open string, quoted + /// identifier, block comment or dollar-quoted string, or in a line comment with no trailing newline. When true, + /// the last token is the open one. + bool ends_unterminated = false; +}; + +/// A statement bound and planned once, executable repeatedly. Produced by `Connection::Prepare`. +/// Where `Connection::Execute` re-binds on every call, this may run the plan it built at prepare time; ask +/// `ReusesPlan` which one you got. Execution returns the same `QueryResult`, with identical behaviour, or an +/// `ArrowResult` when an `ArrowFormat` is passed. +/// It keeps its connection's session alive, so it stays usable even after the `Connection` is gone. +class PreparedStatement final : public detail::Handle { + friend detail::HandleFactory; + +public: + PreparedStatement(PreparedStatement &&) noexcept = default; + PreparedStatement &operator=(PreparedStatement &&) noexcept = default; + + ~PreparedStatement() override; + + /// Executes with positional parameters ($1 = parameters[0]), returning a lazy streaming result. + /// Non-consuming: execute the same statement again, with the same values or different ones. + /// @param parameters Values for the statement's parameters, bound positionally. + /// @param parameter_count How many values `parameters` points at. + /// @return A streaming result. Execution is deferred until the result is read; binding errors throw here. + /// @throws Exception While an earlier result on the connection is still live. A failed execution leaves the + /// prepared statement usable. + auto Execute(const Value *parameters, idx_t parameter_count) -> QueryResult; + + /// Executes a statement that takes no parameters. + auto Execute() -> QueryResult; + + /// `std::vector` overload of the positional-parameter `Execute`. + auto Execute(const std::vector ¶meters) -> QueryResult; + + /// Executes with named parameters. + /// @param parameters One binding per parameter; each binds to $name, or positionally when its name is empty. + auto Execute(const std::vector ¶meters) -> QueryResult; + + /// Executes like the positional-parameter `Execute`, into a result that produces Arrow arrays. + /// @param parameters Values for the statement's parameters, bound positionally. Not consumed. + /// @param parameter_count How many values `parameters` points at. + /// @param format The Arrow format options, chiefly the rows-per-array cap. + /// @return A streaming Arrow result. Execution is deferred until the result is read; binding errors throw here. + /// @throws Exception While an earlier result on the connection is still live, in either format. A failed + /// execution leaves the prepared statement usable. + auto Execute(const Value *parameters, idx_t parameter_count, ArrowFormat format) -> ArrowResult; + + /// The Arrow form of a statement that takes no parameters. + auto Execute(ArrowFormat format) -> ArrowResult; + + /// `std::vector` overload of the positional-parameter Arrow `Execute`. + auto Execute(const std::vector ¶meters, ArrowFormat format) -> ArrowResult; + + /// The Arrow form of the named-parameter `Execute`. + auto Execute(const std::vector ¶meters, ArrowFormat format) -> ArrowResult; + + /// Whether executions reuse the plan built at prepare time, rather than re-binding each time and being no + /// faster than `Connection::Execute`. A static property of the built plan; see the C API's + /// `duckdb_v2_prepared_statement_reuses_plan` for what qualifies. + auto ReusesPlan() const -> bool; + +private: + explicit PreparedStatement(void *impl); + + auto ExecuteArrowNamed(const NamedParam *parameters, idx_t parameter_count, ArrowFormat format) -> ArrowResult; +}; + +//---------------------------------------------------------------------------------------------------------------------- +// Connection +//---------------------------------------------------------------------------------------------------------------------- +// A session on an `Instance`: the handle that parses, binds and executes SQL, creates types and values outside of a +// callback, and carries session-scoped settings. A connection is not thread-safe -- give each thread its own, via +// `Instance::Connect` -- with the deliberate exception of `Interrupt` and `GetQueryProgress`, which exist to be called +// while another thread runs a query. + +/// A connection to a database. +/// It must not outlive the `Instance` it was opened on, and only one result may be live on it at a time. +class Connection final : public detail::Handle { + friend detail::HandleFactory; + +public: + Connection(Connection &&other) noexcept : factory(std::move(other.factory)), config(std::move(other.config)) { + std::swap(impl, other.impl); + std::swap(owned, other.owned); + } + + Connection &operator=(Connection &&other) noexcept { + std::swap(impl, other.impl); + std::swap(factory, other.factory); + std::swap(config, other.config); + std::swap(owned, other.owned); + return *this; + } + + /// A snapshot of the running query's progress. Progress is only tracked while the `enable_progress_bar` setting is + /// on; a percentage of -1 with both row counts at 0 means no information is available. + struct QueryProgress { + /// Completion in [0, 100], or -1 when unknown. + double percentage; + /// Rows processed so far. + uint64_t rows_processed; + /// Rows the query expects to process in total. + uint64_t total_rows_to_process; + }; + + ~Connection() override; + + /// The factory values, types and data chunks are created through on this connection. + auto GetFactory() -> Factory & { + return factory; + } + + /// Registers on this connection's database, in the connection's transaction: inside an explicit transaction a + /// rollback undoes catalog entries, though casts and replacement scans take effect immediately. Replacement scans + /// stay local to this connection. + /// Registers the function. The function object remains valid and may be + /// adjusted and registered again; user data set via `SetUserData` is consumed by the first registration. + /// @throws InvalidInputException When the name, exec callback, or a usable return type is missing. + auto Register(ScalarFunction &scalar_function) -> void; + /// Registers the function. The function object remains valid and may be + /// adjusted and registered again; user data set via `SetUserData` is consumed by the first registration. + /// @throws InvalidInputException When the name, a required callback, or a usable return type is missing. + auto Register(AggregateFunction &aggregate_function) -> void; + /// Registers the function. The function object remains valid and may be + /// adjusted and registered again; user data set via `SetUserData` is consumed by the first registration. + /// @throws InvalidInputException When the name, bind callback or exec callback is missing, the signature + /// declares a return type, or a partitioning callback is set without a partition data callback. + auto Register(TableFunction &table_function) -> void; + /// Registers the function. The function object remains valid. + /// @throws InvalidInputException When the name or the single-file function is missing, or the single-file + /// function does not exist or does not take the file to read as its only positional parameter. + auto Register(MultiFileFunction &multi_file_function) -> void; + /// Registers the type. The type object remains valid and may be adjusted + /// and registered again. + /// @throws InvalidInputException When the name or the base type is missing, or the base type is not concrete. + auto Register(CustomType &custom_type) -> void; + /// Registers the function. The function object remains valid and may be + /// adjusted and registered again; user data set via `SetUserData` is consumed by the first registration. + /// @throws InvalidInputException When the name is missing, neither side is configured, a configured + /// `COPY ... TO` side lacks its batch or flush callback, or a configured `COPY ... FROM` side lacks its bind or + /// exec callback. + auto Register(CopyFunction ©_function) -> void; + /// Registers the cast, replacing whatever cast was registered for the same type pair. The function object remains + /// valid and may be adjusted and registered again; user data set via `SetUserData` is consumed by the first + /// registration. + /// @throws InvalidInputException When the source type, target type, or exec callback is missing, or either type is + /// not concrete. + auto Register(CastFunction &cast_function) -> void; + /// Registers the pragma. The function object remains valid; user data set via `SetUserData` is consumed by the + /// first registration. + /// @throws InvalidInputException When the name is missing, not exactly one of the query and exec callbacks is set, + /// the signature declares a return type, or a pragma of the same name already exists. + auto Register(PragmaFunction &pragma_function) -> void; + /// Registers the option on the database, visible to every connection. Not transactional: it takes effect at once, + /// also inside an explicit transaction, and a rollback does not undo it. The option object remains valid; user + /// data set via `SetUserData` is consumed by the first registration. + /// @throws InvalidInputException When the name, or both the type and the default value, are missing, the default + /// value does not cast to the type, the scopes are inconsistent, or an option of the same name already exists. + auto Register(CustomOption &custom_option) -> void; + /// Registers the scan. Scans are consulted in registration order within + /// their scope, connection-scoped ones before database-wide ones, and the first to claim a name wins. A scan can + /// be registered only once. + /// @throws InvalidInputException When the callback is missing, or the scan is already registered. + auto Register(ReplacementScan &replacement_scan) -> void; + + /// The config of this connection: its own cascade. + auto GetConfig() -> Config & { + return config; + } + /// Const overload of the above: a const config reads settings, but does not write them. + auto GetConfig() const -> const Config & { + return config; + } + + /// The file system this connection reads and writes through, with its settings and secrets. Borrowed, and valid + /// only while the connection is. + auto GetFileSystem() const -> FileSystem; + + /// Writes a message to DuckDB's log, readable through `SELECT * FROM duckdb_logs`. + /// Whether the entry is recorded is up to the database's log configuration; a message it filters out is dropped + /// without error. + /// @param level The severity of the message. + /// @param message The message body. + /// @param log_type The log type to record under, matched case-sensitively. Empty selects the default type. + auto Log(LogLevel level, std::string_view message, std::string_view log_type = {}) const -> void; + + /// Parses a SQL string into an iterator over its statements, without binding or executing any of them. + /// Parsing happens statement by statement as the iterator advances, so a syntax error surfaces from + /// `StatementIterator::Next` rather than from this call. + /// @param sql One or more semicolon-separated SQL statements. + /// @param apply_invalidation_policy Whether a syntax error invalidates the active transaction, according to the + /// transaction invalidation policy. Pass false when the statements are only inspected, e.g. with `Bind`, instead of + /// run. + auto ParseSQL(std::string_view sql, bool apply_invalidation_policy = true) -> StatementIterator; + + /// Splits a SQL string into its tokens without parsing it: no binding, no catalog access, no transaction. The + /// connection supplies the grammar whose keyword set decides KEYWORD versus IDENTIFIER. Offsets are byte offsets + /// into `sql` exactly as given, and whitespace is not a token. Malformed input does not throw: an unterminated + /// string, block comment or dollar-quoted string yields a token that runs to the end of the input, and + /// `TokenList::ends_unterminated` reports it. + /// @param sql The SQL text; may contain interior null bytes. + /// @return The tokens in input order, and whether the input ended inside an open token. + auto Tokenize(std::string_view sql) const -> TokenList; + + /// Executes a statement, borrowing it rather than consuming it, so the same statement can be executed again. + /// @param statement The statement to execute. + /// @param parameters Values for the statement's parameters, bound positionally ($1 = parameters[0]). + /// @param parameter_count How many values `parameters` points at. + /// @return A streaming result. Execution is deferred until the result is read; binding errors throw here. + /// @throws Exception While an earlier result on this connection is still live. + auto Execute(const SqlStatement &statement, const Value *parameters, idx_t parameter_count) -> QueryResult; + + /// Executes a statement that takes no parameters. + auto Execute(const SqlStatement &statement) -> QueryResult; + + /// `std::vector` overload of the positional-parameter `Execute`. + auto Execute(const SqlStatement &statement, const std::vector ¶meters) -> QueryResult; + + /// Executes a statement with named parameters. + /// @param statement The statement to execute. + /// @param parameters One binding per parameter; each binds to $name, or positionally when its name is empty. A + /// statement cannot mix named and positional parameters. + auto Execute(const SqlStatement &statement, const std::vector ¶meters) -> QueryResult; + + /// Parses and executes a single SQL statement in one call. + /// @param sql Exactly one SQL statement. Use `ParseSQL` for multi-statement input. + /// @throws InvalidInputException When `sql` does not hold exactly one statement. + auto Execute(const std::string &sql) -> QueryResult; + + /// Executes a statement like `Execute`, into a result that produces Arrow arrays instead of `DataChunk`s. + /// @param statement The statement to execute. Not consumed, so it can be executed again. + /// @param parameters Values for the statement's parameters, bound positionally ($1 = parameters[0]). Not consumed. + /// @param parameter_count How many values `parameters` points at. + /// @param format The Arrow format options, chiefly the rows-per-array cap. + /// @return A streaming Arrow result. Execution is deferred until the result is read; binding errors throw here. + /// @throws Exception While an earlier result on this connection is still live, in either format. + auto Execute(const SqlStatement &statement, const Value *parameters, idx_t parameter_count, ArrowFormat format) + -> ArrowResult; + + /// The Arrow form of a statement that takes no parameters. + auto Execute(const SqlStatement &statement, ArrowFormat format) -> ArrowResult; + + /// `std::vector` overload of the positional-parameter Arrow `Execute`. + auto Execute(const SqlStatement &statement, const std::vector ¶meters, ArrowFormat format) + -> ArrowResult; + + /// The Arrow form of the named-parameter `Execute`. + /// @param parameters One binding per parameter; each binds to $name, or positionally when its name is empty. A + /// statement cannot mix named and positional parameters. + auto Execute(const SqlStatement &statement, const std::vector ¶meters, ArrowFormat format) + -> ArrowResult; + + /// Parses and executes a single SQL statement in one call, into a result that produces Arrow arrays. + /// @param sql Exactly one SQL statement. Use `ParseSQL` for multi-statement input. + /// @throws InvalidInputException When `sql` does not hold exactly one statement. + auto Execute(const std::string &sql, ArrowFormat format) -> ArrowResult; + + /// Binds a statement without executing it, borrowing it rather than consuming it. + /// @param statement The statement to bind. + /// @return Its signature: the columns it will produce and the parameters it expects. + /// @throws Exception With code `DUCKDB_V2_ERROR_INPUT_METADATA_DEFERRED` for a statement that expands into several, + /// whose columns are known only once it executes. + auto Bind(const SqlStatement &statement) const -> Signature; + + /// Resolves a table name and snapshots its description: where it resolved, its columns, and per-column facts. + /// @param name A possibly partial table name, resolved through the search path exactly as SQL resolves it. + /// @throws Exception When the name resolves to nothing, to a view, or is ambiguous between a schema and an attached + /// database. + auto DescribeTable(const QualifiedName &name) const -> TableDescription; + + /// Enables or disables profiling for the queries this connection runs from now on, which gathers the metrics + /// `GetQueryMetrics` reports. Profiling also prints every profile as the `enable_profiling` and `profiling_output` + /// options configure, by default to the standard output; set `enable_profiling` to `no_output` to only gather + /// metrics. Unstable API. + auto EnableProfiling(bool enabled = true) -> void; + + /// Takes a snapshot of the metrics of the last query this connection profiled, which is not necessarily the last + /// query it ran: see GetProfilingInformation. What it holds is decided by the profiling configuration, e.g. + /// `SET enable_profiling = 'no_output'`. Unstable API. + /// @throws Exception While a result on this connection has not been drained or destroyed. + auto GetQueryMetrics() const -> QueryMetrics; + + /// Renders the profile of the last query this connection profiled, as the text the profiler prints for it. The + /// profiler keeps that profile while profiling is disabled, so after profiling is enabled again it describes the + /// last query run while profiling was enabled until the next query finishes. What it holds is decided by the + /// profiling configuration, e.g. `SET enable_profiling = 'json'`; without profiling it is the profiler's note that + /// profiling is disabled. Unstable API. + /// @param format The profiler format name: "json", "text", "query_tree", "query_tree_optimizer", "html", + /// "graphviz", "yaml", "mermaid" or "no_output", which renders nothing. Empty selects the configured format, or a + /// query tree when that is "no_output". + /// @throws Exception For an unknown format, or while a result on this connection has not been drained or + /// destroyed. + auto GetProfilingInformation(std::string_view format = {}) const -> std::string; + + /// Prepares a statement into a handle that can be executed repeatedly, borrowing it rather than consuming it. + /// @param statement The statement to prepare. + /// @param require_cacheable When true, fail rather than return a statement whose plan is re-bound on every + /// execution, so a caller who wants the handle only for the speedup finds out here. + /// @throws Exception On a bind or catalog error, while a result on this connection is still live, or when + /// `require_cacheable` is set and the plan would not be reused. + auto Prepare(const SqlStatement &statement, bool require_cacheable = false) -> PreparedStatement; + + /// Asks the running query to stop. `QueryResult::Step` then reports CANCELLED, and `FetchChunk` / `Drain` throw + /// `InterruptException`. An `ArrowResult` reacts the same way, with `FetchArray` in place of `FetchChunk`. + /// Callable from any thread, and a no-op when no query is running. + auto Interrupt() -> void; + + /// Reads how far the running query has come. Callable from any thread. + auto GetQueryProgress() const -> QueryProgress; + + /// Wraps a connection handle owned by someone else. + /// @param opaque The borrowed handle; must be a connection handle of the DuckDB C API. + /// @return A non-owning `Connection`: it must not outlive the handle, and it will not disconnect on destruction. + static auto FromOpaque(void *opaque) -> Connection { + return Connection(opaque, false); + } + +private: + explicit Connection(void *impl, bool owned); + Factory factory; + Config config; + + auto ExecuteArrowNamed(const SqlStatement &statement, const NamedParam *parameters, idx_t parameter_count, + ArrowFormat format) -> ArrowResult; + + bool owned = false; // TODO: This should be fixed C++ side +}; + +//---------------------------------------------------------------------------------------------------------------------- +// Instance +//---------------------------------------------------------------------------------------------------------------------- +// An open database: the catalog, the storage behind it, and the settings shared by every session on it. Databases are +// opened by constructing an `Instance` and worked with through the `Connection`s they hand out. Every instance lives in +// an `Environment`, and a file can only be open in one instance of an environment at a time. Instances opened without +// an explicit environment share the process-wide default one. + +/// The environment database instances are created in. Optional: an `Instance` constructed without one lives in the +/// process-wide `Environment::Default()`. Create one explicitly to control the lifetime of the environment, or to keep +/// a group of instances apart from the default one. It must outlive every `Instance` created in it; destroying it +/// while instances are still alive leaks it. +class Environment final : public detail::Handle { +public: + /// Creates a new environment. + Environment(); + ~Environment() override; + Environment(Environment &&) noexcept = default; + Environment &operator=(Environment &&) noexcept = default; + + /// The process-wide environment instances are created in when none is given. Created on first use and never + /// destroyed, so it outlives every instance, including ones destroyed during static destruction. + static auto Default() -> Environment &; + + /// How many database instances are currently alive in this environment. + auto GetInstanceCount() const -> size_t; +}; + +/// The options an `Instance` can only be given when it is created: once it exists they can no longer change, or only +/// become stricter. Each setter returns the options, so they chain: `StartupOptions().EnableUnsignedExtensions(true)`. +/// An option left unset keeps DuckDB's default. +class StartupOptions { + friend class Instance; + +public: + StartupOptions() = default; + + /// Whether extensions built by the community can be loaded. Defaults to true. + auto EnableCommunityExtensions(bool value) -> StartupOptions & { + allow_community_extensions = value; + return *this; + } + + /// Whether extensions with an invalid or missing signature can be loaded. Defaults to false. + auto EnableUnsignedExtensions(bool value) -> StartupOptions & { + allow_unsigned_extensions = value; + return *this; + } + + /// Whether a fatal error invalidates the instance, refusing every further query on it. Disabling this should be + /// done with great care: DuckDB cannot guarantee correct behavior after a fatal error. Defaults to true. + auto EnableDatabaseInvalidation(bool value) -> StartupOptions & { + disable_database_invalidation = !value; + return *this; + } + + /// Whether secrets can be printed unredacted. Defaults to false. + auto EnableUnredactedSecrets(bool value) -> StartupOptions & { + allow_unredacted_secrets = value; + return *this; + } + + /// Metadata added to the user agent of the HTTP requests DuckDB makes, so callers and wrappers can tag their own + /// traffic. Defaults to none. + auto SetCustomUserAgent(std::string_view value) -> StartupOptions & { + custom_user_agent = std::string(value); + return *this; + } + + /// Sets any option by name, for options without a dedicated setter above, e.g. `duckdb_api` or `access_mode`. + /// Options are applied in the order they are set, after the dedicated setters, so a later value wins. An option + /// that needs a running instance (such as `allowed_directories`) makes `Instance` construction throw: write it + /// through `Instance::GetConfig` instead. + /// @param name The option's canonical name or one of its aliases. + /// @param value The value, in the textual form SQL `SET` accepts. + auto Set(std::string_view name, std::string_view value) -> StartupOptions & { + options.emplace_back(std::string(name), std::string(value)); + return *this; + } + +private: + std::optional allow_community_extensions; + std::optional allow_unsigned_extensions; + std::optional allow_unredacted_secrets; + std::optional disable_database_invalidation; + std::optional custom_user_agent; + std::vector> options; +}; + +class Instance final : public detail::Handle { + friend detail::HandleFactory; + +public: + /// Creates a database instance with nothing attached, in the default environment. Attach a database with + /// `Attach` and make it the default with `SetDefault`. + Instance(); + + /// Creates a database instance with nothing attached, in the default environment, with the options that can only + /// be chosen at startup. + explicit Instance(const StartupOptions &options); + + /// Creates a database instance in the default environment, attaches `path`, and makes it the default database. + /// @param path The database file, or ":memory:" / the empty string for an in-memory database. + /// @param options The options that can only be chosen at startup. + explicit Instance(const std::string &path, const StartupOptions &options = {}); + + /// Creates a database instance with nothing attached, in `env`. + /// @param env The environment to create the instance in. Must outlive the instance. + /// @param options The options that can only be chosen at startup. + explicit Instance(Environment &env, const StartupOptions &options = {}); + + /// Creates a database instance in `env`, attaches `path`, and makes it the default database. + /// @param env The environment to create the instance in. Must outlive the instance. + /// @param path The database file, or ":memory:" / the empty string for an in-memory database. + /// @param options The options that can only be chosen at startup. + Instance(Environment &env, const std::string &path, const StartupOptions &options = {}); + + /// Opens the database file `path` in an instance shared through the default environment: a new handle to the + /// instance that already has the file open, or else to a new instance with the file attached as its default + /// database. Every handle for the same file sees the same database; it is closed once the last handle and the last + /// connection on it are destroyed, and opening it meanwhile waits for that rather than opening it twice. See + /// `duckdb_v2_instance_open_shared` for the details. + /// @param path The database file, or ":memory:" / the empty string for a new in-memory database, which is never + /// shared. + /// @param options The options that can only be chosen at startup. An instance that is already open is shared only + /// when it was created with options that give the same settings: an alias counts as its option, and a value + /// counts as equal once converted to the option's type, text regardless of case. + /// @throws Exception When the file is open in an instance created with other options, or attached to an instance + /// that is not shared. + static auto OpenShared(const std::string &path, const StartupOptions &options = {}) -> Instance; + + /// `OpenShared` through `env`, which must outlive the instance. + static auto OpenShared(Environment &env, const std::string &path, const StartupOptions &options = {}) -> Instance; + + /// Initializes an instance that `OpenShared` has just created. The instance is borrowed for the duration of the + /// call, and must not be moved from: configure it, or connect to it and run SQL. + using InitCallback = std::function; + + /// `OpenShared`, calling `init` when this call creates the instance, before another call can share it: calls for + /// the same file wait for `init` to return. When `init` throws, the instance is destroyed and the exception + /// propagates; the next call for the file creates an instance again. `init` is not called when the call shares + /// an existing instance, and must not open the same file with `OpenShared`. + static auto OpenShared(const std::string &path, const StartupOptions &options, const InitCallback &init) + -> Instance; + + /// `OpenShared` through `env`, which must outlive the instance, calling `init` when this call creates it. + static auto OpenShared(Environment &env, const std::string &path, const StartupOptions &options, + const InitCallback &init) -> Instance; + + ~Instance() override; + Instance(Instance &&) noexcept = default; + Instance &operator=(Instance &&) noexcept = default; + + /// Attaches a database to this instance, like SQL `ATTACH 'path'`, under the name derived from the path: `memory` + /// for an in-memory database, else the file name up to its first `.` (`/data/sales.2024.db` -> `sales`). + /// @param path The database file, or ":memory:" / the empty string for an in-memory database. + /// @param make_default Whether to make it the default database for sessions opened afterwards, as `SetDefault` + /// would; false leaves the default alone. + /// @throws Exception When the path is already attached in this process, or a database of that name exists. + auto Attach(const std::string &path, bool make_default = false) -> void; + + /// Attaches a database under a name and with the per-database options SQL `ATTACH` takes, like + /// `ATTACH 'path' AS name (KEY value, ...)`. + /// @param path The database file, or ":memory:" / the empty string for an in-memory database. + /// @param name The name to attach under; empty for the name derived from the path. + /// @param options The `(KEY value)` options, e.g. `{{"READ_ONLY", "true"}, {"BLOCK_SIZE", "16384"}}`. Keys match + /// case-insensitively and values are passed on as the text a quoted SQL literal carries; the engine casts the + /// ones it knows and hands the rest to the storage extension owning the database. + /// @param make_default Whether to make it the default database for sessions opened afterwards. + auto Attach(const std::string &path, const std::string &name, + const std::unordered_map &options, bool make_default = false) -> void; + + /// Detaches the database attached under `name`, like SQL `DETACH name`. Connections still using it keep it alive + /// until they let go; if it was the default database, new sessions have no default until `SetDefault` names + /// another. + /// @throws InvalidInputException When no database is attached under `name`. + auto Detach(const std::string &name) -> void; + + /// Makes the database attached under `name` the default database for sessions opened from now on: where their + /// unqualified DDL and unqualified table lookups that miss the temporary catalog go, unless they `USE` another. + /// Sessions already open keep the default they connected with. + /// @throws InvalidInputException When no database is attached under `name`. + auto SetDefault(const std::string &name) -> void; + + /// The config of this database: the GLOBAL scope. Settings that can only be chosen at startup are passed to the + /// constructor instead. + auto GetConfig() -> Config & { + return config; + } + /// Const overload of the above: a const config reads settings, but does not write them. + auto GetConfig() const -> const Config & { + return config; + } + + /// Opens a new session on this database, starting the instance if this is its first use. + /// @return An owning `Connection`, which disconnects when destroyed. Open one per thread. + auto Connect() -> Connection; + + /// The factory for the built-in types, their values and casts, and data chunks on this instance. Anything that + /// needs a catalog throws; use a connection's or a context's factory for that. + auto GetFactory() -> Factory & { + return factory; + } + + /// Registers a replacement scan on this database, visible to every connection. Not thread-safe against queries + /// binding on other connections: register before issuing queries. + /// Registers the scan. Scans are consulted in registration order within + /// their scope, connection-scoped ones before database-wide ones, and the first to claim a name wins. A scan can + /// be registered only once. + /// @throws InvalidInputException When the callback is missing, or the scan is already registered. + auto Register(ReplacementScan &replacement_scan) -> void; + /// Registers the log sink, making it available to the logging configuration under its name. Not transactional; + /// the sink lives as long as the database. User data set via `SetUserData` is consumed by registration. + /// @throws InvalidInputException When the name or write callback is missing, or the name is taken, by a sink + /// DuckDB provides itself or by one registered before. + auto Register(LogSink &log_sink) -> void; + + /// The file system of this database, with its GLOBAL settings and secrets. Borrowed, and valid only while the + /// instance is. + auto GetFileSystem() const -> FileSystem; + + /// Writes a message to DuckDB's log, readable through `SELECT * FROM duckdb_logs`. + /// Whether the entry is recorded is up to the database's log configuration; a message it filters out is dropped + /// without error. + /// @param level The severity of the message. + /// @param message The message body. + /// @param log_type The log type to record under, matched case-sensitively. Empty selects the default type. + auto Log(LogLevel level, std::string_view message, std::string_view log_type = {}) const -> void; + +private: + explicit Instance(void *impl); + //! The (name, value) pairs of the options that were set, in the textual form SQL `SET` accepts. + static auto StartupOptionPairs(const StartupOptions &options) -> std::vector>; + + Factory factory; + Config config; +}; + +//---------------------------------------------------------------------------------------------------------------------- +// Extension +//---------------------------------------------------------------------------------------------------------------------- +// Loading an extension is how catalog entries (functions, types, casts) and database-level hooks get installed under +// the extension's identity, so DuckDB can attribute them to the extension that provided them. Outside a load, the same +// objects are registered on a `Connection` or an `Instance` instead. + +/// The extension being loaded, handed to its load entry point. +/// Borrowed for the duration of the load: never store or outlive one. +class Extension final : public detail::Handle { + friend detail::HandleFactory; + +public: + ~Extension() override; + + /// Registers on the loading extension's database, attributed to the extension and visible to every connection. + /// Registers the function. The function object remains valid and may be + /// adjusted and registered again; user data set via `SetUserData` is consumed by the first registration. + /// @throws InvalidInputException When the name, exec callback, or a usable return type is missing. + auto Register(ScalarFunction &scalar_function) -> void; + /// Registers the function. The function object remains valid and may be + /// adjusted and registered again; user data set via `SetUserData` is consumed by the first registration. + /// @throws InvalidInputException When the name, a required callback, or a usable return type is missing. + auto Register(AggregateFunction &aggregate_function) -> void; + /// Registers the function. The function object remains valid and may be + /// adjusted and registered again; user data set via `SetUserData` is consumed by the first registration. + /// @throws InvalidInputException When the name, bind callback or exec callback is missing, the signature + /// declares a return type, or a partitioning callback is set without a partition data callback. + auto Register(TableFunction &table_function) -> void; + /// Registers the function. The function object remains valid. + /// @throws InvalidInputException When the name or the single-file function is missing, or the single-file + /// function does not exist or does not take the file to read as its only positional parameter. + auto Register(MultiFileFunction &multi_file_function) -> void; + /// Registers the type. The type object remains valid and may be adjusted + /// and registered again. + /// @throws InvalidInputException When the name or the base type is missing, or the base type is not concrete. + auto Register(CustomType &custom_type) -> void; + /// Registers the function. The function object remains valid and may be + /// adjusted and registered again; user data set via `SetUserData` is consumed by the first registration. + /// @throws InvalidInputException When the name is missing, neither side is configured, a configured + /// `COPY ... TO` side lacks its batch or flush callback, or a configured `COPY ... FROM` side lacks its bind or + /// exec callback. + auto Register(CopyFunction ©_function) -> void; + /// Registers the cast, replacing whatever cast was registered for the same type pair. The function object remains + /// valid and may be adjusted and registered again; user data set via `SetUserData` is consumed by the first + /// registration. + /// @throws InvalidInputException When the source type, target type, or exec callback is missing, or either type is + /// not concrete. + auto Register(CastFunction &cast_function) -> void; + /// Registers the pragma. The function object remains valid; user data set via `SetUserData` is consumed by the + /// first registration. + /// @throws InvalidInputException When the name is missing, not exactly one of the query and exec callbacks is set, + /// the signature declares a return type, or a pragma of the same name already exists. + auto Register(PragmaFunction &pragma_function) -> void; + /// Registers the macro function. The function object remains valid. + /// @throws InvalidInputException When the name or the body is missing, the body does not parse, the signature has + /// a parameter that is not a standard one or declares a return type, or a function of the same name exists. + auto Register(MacroFunction ¯o_function) -> void; + /// Registers the option on the database, visible to every connection. Not transactional: it takes effect at once, + /// also inside an explicit transaction, and a rollback does not undo it. The option object remains valid; user + /// data set via `SetUserData` is consumed by the first registration. + /// @throws InvalidInputException When the name, or both the type and the default value, are missing, the default + /// value does not cast to the type, the scopes are inconsistent, or an option of the same name already exists. + auto Register(CustomOption &custom_option) -> void; + /// Registers the scan. Scans are consulted in registration order within + /// their scope, connection-scoped ones before database-wide ones, and the first to claim a name wins. A scan can + /// be registered only once. + /// @throws InvalidInputException When the callback is missing, or the scan is already registered. + auto Register(ReplacementScan &replacement_scan) -> void; + /// Registers the log sink, making it available to the logging configuration under its name. Not transactional; + /// the sink lives as long as the database. User data set via `SetUserData` is consumed by registration. + /// @throws InvalidInputException When the name or write callback is missing, or the name is taken, by a sink + /// DuckDB provides itself or by one registered before. + auto Register(LogSink &log_sink) -> void; + +private: + explicit Extension(void *impl); +}; + +namespace detail { +/// Backs `DUCKDB_CPP_EXTENSION_ENTRYPOINT` in duckdb_cpp_extension.hpp: wraps the raw loader handles and runs the +/// extension's body, reporting a thrown `Exception` through the error slot so it fails the load. The handles are +/// passed untyped to keep the C loader types out of this header. +auto RunExtensionEntry(void (*body)(Extension &, Context &), void *extension, void *context, void *err) -> void; +} // namespace detail + +/// The version of the DuckDB library this program is linked against, e.g. "v1.5.0", with a suffix such as +/// "v1.5.0-dev123" on development builds. +auto LibraryVersion() -> std::string; + +/// Renders a name as a SQL identifier, quoting and escaping only when required: the name itself when it is a legal +/// bare identifier, or double-quoted with interior quotes doubled when it is a keyword or contains characters that +/// require quoting. Use it for every name embedded in SQL text rather than quoting by hand. +/// @param name The name to render. +auto RenderQuotedIdentifier(std::string_view name) -> std::string; + +//---------------------------------------------------------------------------------------------------------------------- +// Logical Type +//---------------------------------------------------------------------------------------------------------------------- +// The SQL type of a column, value or parameter. Types are built through a `Context` or `Connection`: by parsing SQL +// text, by name and parameters, or with a `TypeBuilder`. Once built, a `LogicalType` is an owned, self-contained value +// that can be inspected without any scope. + +/// The "id" of a built-in SQL type. +/// Parameterized kinds such as LIST and DECIMAL are represented by their id plus parameters, the id alone does not name +/// a complete type. +enum class LogicalTypeId : uint32_t { + INVALID = 0, + SQLNULL = 1, + UNKNOWN = 2, + ANY = 3, + TYPE = 6, + BOOLEAN = 10, + TINYINT = 11, + SMALLINT = 12, + INTEGER = 13, + BIGINT = 14, + DATE = 15, + TIME = 16, + TIMESTAMP_SEC = 17, + TIMESTAMP_MS = 18, + TIMESTAMP = 19, + TIMESTAMP_NS = 20, + DECIMAL = 21, + FLOAT = 22, + DOUBLE = 23, + VARCHAR = 25, + BLOB = 26, + INTERVAL = 27, + UTINYINT = 28, + USMALLINT = 29, + UINTEGER = 30, + UBIGINT = 31, + TIMESTAMP_TZ = 32, + TIMESTAMP_TZ_NS = 33, + TIME_TZ = 34, + TIME_NS = 35, + BIT = 36, + BIGNUM = 39, + UHUGEINT = 49, + HUGEINT = 50, + UUID = 54, + GEOMETRY = 60, + STRUCT = 100, + LIST = 101, + MAP = 102, + ENUM = 104, + UNION = 107, + ARRAY = 108, + VARIANT = 109, + TUPLE = 110, +}; + +/// An owned SQL type: a kind plus its parameters, e.g. DECIMAL(18, 3) or STRUCT(a INTEGER, b VARCHAR), and in the case +/// of extension-defined types, its "alias" +class LogicalType final : public detail::Handle { + friend detail::HandleFactory; + +public: + LogicalType(LogicalType &&) noexcept = default; + LogicalType &operator=(LogicalType &&) noexcept = default; + + ~LogicalType() override; + + /// A copy of this type carrying `alias` as its name: the same representation under a distinct identity. + /// The alias is by default not registered anywhere; parsing or creating a type with this name does not resolve to + /// this type, unless it is explicitly registered in the catalog separately. + /// @param factory The factory to create the copy with. + /// @param alias The name the copy carries. Must not be empty. + auto WithAlias(Factory &factory, std::string_view alias) const -> LogicalType; + + /// An owned copy of this type. + auto Copy() const -> LogicalType; + + /// The kind of this type, e.g. `LogicalTypeId::DECIMAL` for any DECIMAL regardless of its parameters. + auto GetTypeId() const -> LogicalTypeId; + + /// The type's name: its alias when it has one, otherwise the fixed name of its kind. Never empty. + /// @return A view borrowed from this type, valid until it is destroyed. + auto GetName() const -> std::string_view; + + /// Whether both types are the same type, parameters and alias included. + bool operator==(const LogicalType &other) const; + + bool operator!=(const LogicalType &other) const { + return !(*this == other); + } + + /// Renders the type as SQL text. An aliased type is rendered as its alias. + auto ToText() const -> std::string; + + /// How many parameters the type carries: + /// - DECIMAL 2 (width, scale) + /// - LIST 1 (element type) + /// - ARRAY 2 (element type, size) + /// - MAP 2 (key, value types) + /// - STRUCT and TUPLE one per field + /// - UNION one per member + /// - ENUM one per dictionary entry; + /// - VARCHAR 1 when a collation is set; + /// - GEOMETRY 1 when a coordinate system is set; + /// anything else 0. + auto GetParamCount() const -> idx_t; + + /// Get one of the type's parameters. The parameter's name is empty when it is positional, otherwise it is the name + /// of the field or member it describes. + /// @param index Parameter index in [0, GetParamCount()). + /// @return An owned name and an owned value. Child types arrive as TYPE values. + auto GetParam(idx_t index) const -> TypeParam; + + // Per-kind shorthands over `GetParam` / `GetParamCount`. They do not verify the type's kind: on a type of another + // kind they misread that type's parameters or throw, so check the kind first. Names and dictionary entries come + // back as owned strings. + + /// The total number of digits a DECIMAL holds; any `uint32_t`, widths above 38 are BIGNUM-backed. + auto GetDecimalWidth() const -> uint32_t; + + /// The number of digits a DECIMAL keeps after the point. + auto GetDecimalScale() const -> uint32_t; + + /// How many entries an ENUM's dictionary holds. + auto GetEnumSize() const -> idx_t; + + /// One ENUM dictionary entry. + /// @param index Entry index in [0, GetEnumSize()). + auto GetEnumValue(idx_t index) const -> std::string; + + /// The element type of a LIST. + auto GetListChildType() const -> LogicalType; + + /// The element type of an ARRAY. + auto GetArrayChildType() const -> LogicalType; + + /// How many elements every row of an ARRAY holds. + auto GetArraySize() const -> idx_t; + + /// The key type of a MAP. + auto GetMapKeyType() const -> LogicalType; + + /// The value type of a MAP. + auto GetMapValueType() const -> LogicalType; + + /// How many fields a STRUCT has. + auto GetStructChildCount() const -> idx_t; + + /// The name of one STRUCT field, empty for the fields of an unnamed STRUCT. + /// @param index Field index in [0, GetStructChildCount()). + auto GetStructChildName(idx_t index) const -> std::string; + + /// The type of one STRUCT field. + /// @param index Field index in [0, GetStructChildCount()). + auto GetStructChildType(idx_t index) const -> LogicalType; + + /// How many members a UNION has. + auto GetUnionMemberCount() const -> idx_t; + + /// The tag of one UNION member. + /// @param index Member index in [0, GetUnionMemberCount()). + auto GetUnionMemberName(idx_t index) const -> std::string; + + /// The type of one UNION member. + /// @param index Member index in [0, GetUnionMemberCount()). + auto GetUnionMemberType(idx_t index) const -> LogicalType; + + /// The type a DECIMAL's digits are stored in, which is what its vector elements are; determined by the width: + /// SMALLINT, INTEGER, BIGINT or HUGEINT up to 38 digits, BIGNUM (`bignum_t` elements) beyond. + auto GetDecimalInternalTypeId() const -> LogicalTypeId; + + /// The unsigned integer type an ENUM's dictionary indices are stored in, which is what its vector elements are; + /// determined by the dictionary size. + auto GetEnumInternalTypeId() const -> LogicalTypeId; + +private: + explicit LogicalType(void *impl); +}; + +//---------------------------------------------------------------------------------------------------------------------- +// Schema +//---------------------------------------------------------------------------------------------------------------------- +// The shape of a row: which fields it has, in order, and of what type. Used both for what a statement produces and +// for what it expects. + +/// An ordered list of (name, type) fields. Names may repeat, and a schema may have no fields at all. +class Schema final : public detail::Handle { + friend detail::HandleFactory; + +public: + Schema(Schema &&) noexcept = default; + Schema &operator=(Schema &&) noexcept = default; + + ~Schema() override; + + /// How many fields the schema has. + auto GetFieldCount() const -> idx_t; + + /// The name of one field. + /// @param index Field index in [0, GetFieldCount()). + /// @return A view borrowed from this schema, valid until it is destroyed. + auto GetFieldName(idx_t index) const -> std::string_view; + + /// An owned copy of one field's type. + /// @param index Field index in [0, GetFieldCount()). + auto GetFieldType(idx_t index) const -> LogicalType; + +private: + explicit Schema(void *impl); +}; + +/// What `Connection::Bind` learns about a statement without running it. +class Signature { +public: + /// The columns the statement will produce. + Schema output; + /// The statement's parameters, ordered by binding key. A field's name is the key: "1", "2", ... for positional + /// parameters, the name for named ones. + Schema parameters; +}; + +//---------------------------------------------------------------------------------------------------------------------- +// Primitive data types +//---------------------------------------------------------------------------------------------------------------------- +// One C++ type per SQL type, laid out exactly as it appears as an element of a vector. These are what +// `VectorView::Data` reads arrays of, and what `Value::Get` and `Value::Create` are keyed on, so the type picked +// here also selects the SQL type read or written. +// +// A few of them store their value in an encoded form. Those carry `Decode` / `Encode` or named accessors, and the raw +// field is not the value you want. +// +// DATE and the TIMESTAMP types reserve their most extreme values as +/- infinity sentinels. + +/// HUGEINT: a 128-bit signed integer, in two halves. +struct int128_t { + /// The low 64 bits. + uint64_t lower; + /// The high 64 bits, carrying the sign. + int64_t upper; +}; + +/// UHUGEINT: a 128-bit unsigned integer, in two halves. +struct uint128_t { + /// The low 64 bits. + uint64_t lower; + /// The high 64 bits. + uint64_t upper; +}; + +/// DATE: days since 1970-01-01. +struct date_t { + int32_t days = 0; +}; + +/// TIME: microseconds since midnight. +struct dtime_t { + int64_t micros = 0; +}; + +/// TIME_NS: nanoseconds since midnight. +struct dtime_ns_t { + int64_t nanos = 0; +}; + +/// TIME_TZ: a time of day together with its UTC offset, packed into one integer -- time in the high 40 bits, the +/// offset reverse-ordered in the low 24. Read it through the accessors; a plain shift gives neither. +struct dtime_tz_t { + static constexpr int OFFSET_BITS = 24; + static constexpr uint64_t OFFSET_MASK = (uint64_t(1) << OFFSET_BITS) - 1; + static constexpr int32_t MAX_OFFSET = 16 * 60 * 60 - 1; // +/-15:59:59 + + dtime_tz_t() = default; + + /// Wraps the packed form, as it appears as a vector element. + explicit dtime_tz_t(uint64_t bits) : bits(bits) { + } + + /// Packs a time and an offset. + /// @param micros Microseconds since midnight. + /// @param offset_seconds The UTC offset in seconds, positive east, in [-MAX_OFFSET, MAX_OFFSET]. + dtime_tz_t(int64_t micros, int32_t offset_seconds) + : bits((static_cast(micros) << OFFSET_BITS) | + (static_cast(MAX_OFFSET - offset_seconds) & OFFSET_MASK)) { + } + + /// Microseconds since midnight. + auto GetMicros() const -> int64_t { + return static_cast(bits >> OFFSET_BITS); + } + + /// The UTC offset in seconds, positive east. + auto GetOffset() const -> int32_t { + return MAX_OFFSET - static_cast(bits & OFFSET_MASK); + } + + /// The packed form, as it appears as a vector element. + auto GetBits() const -> uint64_t { + return bits; + } + +private: + uint64_t bits = 0; +}; + +/// TIMESTAMP: microseconds since 1970-01-01 00:00:00. +struct timestamp_t { + int64_t micros = 0; +}; + +/// TIMESTAMP_SEC: seconds since 1970-01-01 00:00:00. +struct timestamp_s_t { + int64_t seconds = 0; +}; + +/// TIMESTAMP_MS: milliseconds since 1970-01-01 00:00:00. +struct timestamp_ms_t { + int64_t millis = 0; +}; + +/// TIMESTAMP_NS: nanoseconds since 1970-01-01 00:00:00. +struct timestamp_ns_t { + int64_t nanos = 0; +}; + +/// TIMESTAMP_TZ: microseconds since the epoch, in UTC. The display time zone is a session setting, not part of the +/// value. +struct timestamp_tz_t { + int64_t micros = 0; +}; + +/// TIMESTAMP_TZ_NS: nanoseconds since the epoch, in UTC. +struct timestamp_tz_ns_t { + int64_t nanos = 0; +}; + +/// INTERVAL: a span of time, kept in three separate units because months and days are not fixed lengths of time. +struct interval_t { + int32_t months; + int32_t days; + int64_t micros; +}; + +/// The element of a LIST vector: where a row's elements are in the child vector, rather than the elements themselves. +struct list_entry_t { + /// Index of the row's first element in the child vector. + uint64_t offset = 0; + /// How many elements the row has. + uint64_t length = 0; +}; + +/// DECIMAL(WIDTH, SCALE): an exact number, kept as an integer of WIDTH digits with the point SCALE digits from the +/// right. The width picks the storage integer, so DECIMAL(9, 2) and DECIMAL(18, 2) are different C++ types and their +/// payloads are not interchangeable. This covers the fixed-size decimals of up to 38 digits; a wider DECIMAL stores +/// its digits as a `bignum_t`, see `LogicalType::GetDecimalInternalTypeId`. +template +struct decimal_t { + static_assert(WIDTH >= 1 && WIDTH <= 38, "decimal_t covers fixed-size decimals, with a width between 1 and 38"); + static_assert(SCALE <= WIDTH, "DECIMAL scale must be less than or equal to width"); + using storage_type = std::conditional_t< + (WIDTH <= 4), int16_t, + std::conditional_t<(WIDTH <= 9), int32_t, std::conditional_t<(WIDTH <= 18), int64_t, int128_t>>>; + + storage_type value; +}; + +/// BLOB: a string of bytes, in the form it takes as a vector element. Up to INLINE_LENGTH bytes live in the element +/// itself; longer ones live elsewhere and the element only points at them. +/// +/// A blob never owns its bytes. Constructing one from a `std::string_view` borrows that memory rather than copying it, +/// so a long blob is only valid while whatever holds the bytes is: use `Arena::AddBlob` / `Vector::AssignString` to +/// put bytes somewhere that lives as long as the vector. +struct blob_t { + /// The longest byte string that fits in a vector element without being stored elsewhere. + static constexpr uint32_t INLINE_LENGTH = 12; + /// How many leading bytes a non-inlined blob keeps alongside the pointer, for comparisons. + static constexpr uint32_t PREFIX_LENGTH = 4; + + union { + struct { + uint32_t length; + char prefix[PREFIX_LENGTH]; + char *ptr; + } pointer; + struct { + uint32_t length; + char inlined[INLINE_LENGTH]; + } inlined; + } value; + + /// An empty blob. + blob_t() { + std::memset(&value, 0, sizeof(value)); + } + + /// Borrows the bytes of `str`, which must outlive the blob unless they fit inline. + // NOLINTNEXTLINE + blob_t(std::string_view str) : blob_t(str.data(), static_cast(str.size())) { + } + + /// Borrows `size` bytes at `data`, which must outlive the blob unless they fit inline. + blob_t(const char *data, uint32_t size) { + if (!data || size == 0) { + std::memset(&value, 0, sizeof(value)); + value.inlined.length = size; + return; + } + if (size <= INLINE_LENGTH) { + std::memset(&value, 0, sizeof(value)); + value.inlined.length = size; + std::memcpy(value.inlined.inlined, data, size); + } else { + std::memset(&value, 0, sizeof(value)); + value.pointer.length = size; + value.pointer.ptr = const_cast(data); // NOLINT + std::memcpy(value.pointer.prefix, data, PREFIX_LENGTH); + } + } + + explicit operator std::string_view() const { + return std::string_view(data(), size()); + } + + explicit operator std::string() const { + return std::string(data(), size()); + } + + /// Whether the bytes live in the value itself rather than behind the pointer. + auto is_inlined() const -> bool { + return value.inlined.length <= INLINE_LENGTH; + } + + /// The number of bytes. + auto size() const -> uint32_t { + return value.inlined.length; + } + + /// The bytes, wherever they live. Not null-terminated. + auto data() const -> const char * { + return is_inlined() ? value.inlined.inlined : value.pointer.ptr; + } + + /// Mutable access to the bytes. Editing a non-inlined blob's bytes leaves its cached prefix stale, so prefer + /// building a new value over patching one in place. + auto data_mut() -> char * { + return is_inlined() ? value.inlined.inlined : value.pointer.ptr; + } + + /// The bytes as a view, valid as long as the blob and whatever holds its bytes are. + auto view() const -> std::string_view { + return std::string_view(data(), size()); + } +}; + +/// Validates a byte string, throwing InvalidInputException for malformed UTF-8. +void ValidateUTF8(std::string_view text); + +/// VARCHAR: like `blob_t`, but naming a string of UTF-8 text rather than of arbitrary bytes. +/// Constructing a `varchar_t` does not validate UTF-8; use `Arena::AddString` or `Vector::AssignString` for checked +/// construction. +struct varchar_t : blob_t { + using blob_t::blob_t; +}; + +/// BIT: a string of bits, stored as a padding-count byte followed by the data bytes. The count says how many leading +/// bits of the first data byte are not part of the bit string, and those padding bits are set to 1. The raw bytes are +/// not the bits: read them through the accessors, and note that the constructors inherited from `blob_t` take these +/// encoded bytes, not a bit string. +struct bit_t : blob_t { + using blob_t::blob_t; + + /// How many leading bits of the first data byte are padding. + auto GetPaddingBits() const -> uint8_t { + return size() > 0 ? static_cast(data()[0]) : 0; + } + + /// The data bytes, past the padding-count byte. + auto GetBits() const -> const char * { + return size() > 0 ? data() + 1 : data(); + } + + /// How many data bytes there are. + auto GetBitsSize() const -> uint32_t { + return size() > 0 ? size() - 1 : 0; + } + + /// How many bits the string actually holds, padding excluded. + auto GetBitCount() const -> uint64_t { + return GetBitsSize() == 0 ? 0 : static_cast(GetBitsSize()) * 8 - GetPaddingBits(); + } +}; + +/// BIGNUM: an arbitrary-precision integer. Its bytes are encoded so that comparing them matches numeric order, which +/// among other things bit-inverts negative values, so they are not the magnitude. `Decode` and `Encode` translate; the +/// constructors inherited from `blob_t` take the encoded bytes. +struct bignum_t : blob_t { + using blob_t::blob_t; + + /// A BIGNUM as a number: the integer is (-1)^is_negative * unsigned_big_endian(magnitude). Owns its bytes. + struct Decoded { + /// The magnitude, big-endian, without leading zeroes; zero is a single 0x00. + std::vector magnitude; + /// Whether the integer is negative. + bool is_negative; + }; + + /// The magnitude and sign this value stands for. + auto Decode() const -> Decoded; + + /// The inverse: the bytes to build a BIGNUM value from. + /// @param value The magnitude and sign, with the magnitude canonical: at least one byte, no leading zeroes, and + /// zero written as a single 0x00 with `is_negative` false. + static auto Encode(const Decoded &value) -> std::vector; +}; + +/// UUID: a 128-bit identifier, stored as an integer with its high bit flipped so that comparing the integers matches +/// UUID order. The canonical bytes only come out through `Decode`. Distinct from `int128_t`, which names HUGEINT. +struct uuid_t { + int128_t value {}; + + uuid_t() = default; + + /// Wraps the stored form, as it appears as a vector element. + explicit uuid_t(int128_t storage) : value(storage) { + } + + /// A UUID as its canonical 16 big-endian bytes. + struct Decoded { + uint8_t bytes[16]; + }; + + /// The canonical 16 big-endian bytes. + auto Decode() const -> Decoded { + const uint64_t upper = static_cast(value.upper) ^ (static_cast(1) << 63); + Decoded out {}; + for (int i = 0; i < 8; i++) { + out.bytes[i] = static_cast((upper >> (56 - 8 * i)) & 0xFF); + out.bytes[8 + i] = static_cast((value.lower >> (56 - 8 * i)) & 0xFF); + } + return out; + } + + /// The inverse: the stored form for a set of canonical bytes. + /// @param bytes The UUID's 16 big-endian bytes. + static auto Encode(const Decoded &bytes) -> uuid_t { + uint64_t upper = 0; + uint64_t lower = 0; + for (int i = 0; i < 8; i++) { + upper = (upper << 8) | bytes.bytes[i]; + lower = (lower << 8) | bytes.bytes[8 + i]; + } + return uuid_t(int128_t {lower, static_cast(upper ^ (static_cast(1) << 63))}); + } +}; + +//---------------------------------------------------------------------------------------------------------------------- +// Value +//---------------------------------------------------------------------------------------------------------------------- +// A single SQL value, type included: what a statement parameter binds to, what a type parameter carries, and the way +// to read or write one cell of a vector without caring how it is represented. Values are owned and self-contained; +// creating one is scoped to a `Context` or `Connection`. +// +// For bulk data, go through `Vector` instead: a value costs an allocation, so it is the wrong tool per row. + +/// An owned SQL value. +class Value final : public detail::Handle { + friend detail::HandleFactory; + +public: + ~Value() override; + + Value(Value &&) noexcept = default; + Value &operator=(Value &&) noexcept = default; + + /// Whether this is SQL NULL. A NULL value still has a type. + auto IsNull() const -> bool; + + /// An owned copy of the value's type. + auto GetLogicalType() const -> LogicalType; + + /// The value rendered the way DuckDB prints it, e.g. in query output. + auto ToText() const -> std::string; + + /// Casts the value to another type, following the same rules as a SQL cast. + /// @param factory The factory supplying the casts. + /// @param target The type to cast to. + /// @return The converted value. Throws when the cast is not allowed or the value does not fit. + auto Cast(Factory &factory, const LogicalType &target) const -> Value; + + /// Reads the value as `T`, where `T` is one of the primitive types above, or `LogicalType` for a TYPE value. + /// Numeric, temporal and boolean values of another type are converted, following cast rules; the remaining `T`s + /// require a value of the matching type. Types with no specialization here do not compile. + /// @return The value. For `varchar_t` / `blob_t` / `bit_t` / `bignum_t` the bytes are borrowed from this value and + /// stay valid only as long as it does. + /// @throws Exception When the value is NULL, or when it cannot be read as `T`. + template + auto Get() const -> T = delete; + + /// Reads the value as a DECIMAL, e.g. `value.Get<18, 3>()`, spelled with the width and scale instead of a type. + /// @return The value. + /// @throws InvalidInputException Unless the value is a DECIMAL of exactly this width and scale; payloads are not + /// interchangeable between widths. + template + auto Get() const -> decimal_t { + int128_t value {}; + GetDecimal(value, WIDTH, SCALE); + if constexpr (std::is_same_v::storage_type, int128_t>) { + return decimal_t {value}; + } else { + return decimal_t {static_cast::storage_type>(value.lower)}; + } + } + + /// A DECIMAL of a width and scale that are only known at runtime, by its backing integer. + struct RuntimeDecimal { + /// The unscaled value: the DECIMAL is `value / 10^scale`, e.g. 12345 for 123.45 at scale 2. + int128_t value; + uint32_t width; + uint32_t scale; + }; + + /// Reads a DECIMAL of any width and scale, for when they are not known at compile time; `Get` is the + /// typed alternative. + /// @throws Exception When the value is NULL or not a DECIMAL, or when the backing integer of a DECIMAL wider than + /// 38 digits does not fit in 128 bits; `Get()` reads the backing integer of any wide DECIMAL exactly. + auto GetDecimal() const -> RuntimeDecimal; + + /// A NULL of the given type. + /// @param factory The factory to create the value with. + /// @param type The type the NULL carries. + static auto CreateNull(Factory &factory, const LogicalType &type) -> Value; + + /// Creates a value from a C++ value. The overload picked decides the SQL type, so `dtime_t` yields TIME and + /// `dtime_ns_t` yields TIME_NS; a `LogicalType` yields a TYPE value. Types with no overload here do not compile -- + /// cast or build them through the composite constructors instead. Byte strings are copied in, so the value does not + /// borrow from the `varchar_t` / `blob_t` handed to it. + /// @param factory The factory to create the value with. + /// @param value The C++ value to convert. + + static auto Create(Factory &factory, bool value) -> Value; + static auto Create(Factory &factory, uint8_t value) -> Value; + static auto Create(Factory &factory, uint16_t value) -> Value; + static auto Create(Factory &factory, uint32_t value) -> Value; + static auto Create(Factory &factory, uint64_t value) -> Value; + static auto Create(Factory &factory, uint128_t value) -> Value; + static auto Create(Factory &factory, int8_t value) -> Value; + static auto Create(Factory &factory, int16_t value) -> Value; + static auto Create(Factory &factory, int32_t value) -> Value; + static auto Create(Factory &factory, int64_t value) -> Value; + static auto Create(Factory &factory, int128_t value) -> Value; + static auto Create(Factory &factory, float value) -> Value; + static auto Create(Factory &factory, double value) -> Value; + static auto Create(Factory &factory, varchar_t value) -> Value; + static auto Create(Factory &factory, blob_t value) -> Value; + static auto Create(Factory &factory, const LogicalType &type) -> Value; + static auto Create(Factory &factory, date_t value) -> Value; + static auto Create(Factory &factory, dtime_t value) -> Value; + static auto Create(Factory &factory, dtime_ns_t value) -> Value; + static auto Create(Factory &factory, dtime_tz_t value) -> Value; + static auto Create(Factory &factory, timestamp_t value) -> Value; + static auto Create(Factory &factory, timestamp_s_t value) -> Value; + static auto Create(Factory &factory, timestamp_ms_t value) -> Value; + static auto Create(Factory &factory, timestamp_ns_t value) -> Value; + static auto Create(Factory &factory, timestamp_tz_t value) -> Value; + static auto Create(Factory &factory, timestamp_tz_ns_t value) -> Value; + static auto Create(Factory &factory, interval_t value) -> Value; + + template + static auto Create(Factory &factory, decimal_t value) -> Value { + return CreateDecimal(factory, WidenDecimal(value.value), WIDTH, SCALE); + } + + /// Creates a DECIMAL of a width and scale chosen at runtime; `Create(factory, decimal_t)` is the + /// typed alternative. + /// @param factory The factory to create the value with. + /// @param value The unscaled value, e.g. 12345 for 123.45 at scale 2. + /// @param width The number of digits, at least 1 and at most the `max_decimal_width` setting of the factory's + /// connection (its default, 1000000, for the factory of an instance); widths above 38 are stored as BIGNUM. + /// @param scale The number of digits after the decimal point, at most `width`. + /// @throws Exception When the width or scale is out of range, or the value does not fit in `width` digits. + static auto CreateDecimal(Factory &factory, int128_t value, uint32_t width, uint32_t scale) -> Value; + + static auto Create(Factory &factory, bit_t value) -> Value; + static auto Create(Factory &factory, bignum_t value) -> Value; + static auto Create(Factory &factory, uuid_t value) -> Value; + template + static auto Create(Factory &factory, T value) -> Value = delete; + + // Composite construction. Each constructor infers the composite's type from the children it is given, which is why + // only the built-in composites are reachable this way: build an aliased or extension-registered composite by + // casting one of these to it. + // + // Children are borrowed for the duration of the call and copied into the result, so the caller keeps its inputs + // and nothing in the result points back at them. + using ValueList = const std::vector &; + using NamedValueList = const std::vector> &; + using KeyValueList = const std::vector> &; + + /// A LIST of the given elements. + /// @param factory The factory to create the value with. + /// @param values The elements. The element type is the common type of all of them and each is cast to it, so + /// mixing INTEGER and VARCHAR yields VARCHAR elements. Must not be empty: with no element there is no type to + /// infer, so use the child-type overload for an empty LIST. + /// @throws Exception When the elements have no common type. + static auto CreateList(Factory &factory, ValueList values) -> Value; + + /// An empty LIST. + /// @param factory The factory to create the value with. + /// @param child_type The element type, not the LIST type. + static auto CreateList(Factory &factory, const LogicalType &child_type) -> Value; + + /// An ARRAY of the given elements, its size being how many there are. + /// @param factory The factory to create the value with. + /// @param values The elements, typed as in `CreateList`. Must not be empty: the smallest ARRAY holds one element. + static auto CreateArray(Factory &factory, ValueList values) -> Value; + + /// A TUPLE, i.e. a struct whose fields have no names. + /// @param factory The factory to create the value with. + /// @param values The fields, in order. May be empty: the empty tuple is a type of its own. + static auto CreateTuple(Factory &factory, ValueList values = {}) -> Value; + + /// A STRUCT of the given fields. + /// @param factory The factory to create the value with. + /// @param values The (name, value) fields, in order. Names should be unique and either all set or all empty; this + /// is not validated. May be empty: the empty struct is a type of its own. + static auto CreateStruct(Factory &factory, NamedValueList values = {}) -> Value; + + /// A MAP of the given entries. + /// @param factory The factory to create the value with. + /// @param values The (key, value) entries. The key and value types are the common types over all entries, and each + /// entry is cast to them, as in `CreateList`. Keys must be unique and not NULL. Must not be empty: with no entry + /// there are no types to infer, so use the key/value-type overload for an empty MAP. + static auto CreateMap(Factory &factory, KeyValueList values) -> Value; + + /// An empty MAP. + /// @param factory The factory to create the value with. + /// @param key_type The key type, not the MAP type. + /// @param value_type The value type, not the MAP type. + static auto CreateMap(Factory &factory, const LogicalType &key_type, const LogicalType &value_type) -> Value; + + /// How many children a composite value has: elements for LIST and ARRAY, fields for STRUCT and TUPLE, two per + /// entry for MAP, 2 for UNION, and 0 for anything else. A NULL value has no children. + auto GetChildCount() const -> idx_t; + + /// An owned copy of one child. A MAP's children alternate key and value, so entry `i` is children 2*i and 2*i+1; a + /// UNION's children are its tag, then its active member. + /// @param index Child index in [0, GetChildCount()). + auto GetChild(idx_t index) const -> Value; + + /// The value that a VARIANT value holds, with the type that it was stored with: a TINYINT, a VARCHAR, a LIST of + /// STRUCTs, ... A stored list gives a LIST of its elements, a stored object a STRUCT of its fields; elements that + /// were stored with different types stay VARIANT values (a LIST of VARIANT), convert those in turn. A NULL VARIANT + /// gives a NULL value. The inverse is `Cast` to the VARIANT type, `factory.ParseType("VARIANT")`. + /// @throws InvalidInputException When the value is not a VARIANT. + auto VariantToValue() const -> Value; + + /// Shorthand for `GetChild`. + auto operator[](idx_t index) const -> Value { + return GetChild(index); + } + +private: + /// @internal Reads the backing integer, throwing unless the value's own width and scale are the ones asked for. + void GetDecimal(int128_t &out, uint32_t width, uint32_t scale) const; + + /// @internal Sign-extends a DECIMAL's backing integer to the widest storage tier, so one entry point can carry + /// every tier. + static auto WidenDecimal(int64_t value) -> int128_t { + return int128_t {static_cast(value), value < 0 ? -1 : 0}; + } + static auto WidenDecimal(int128_t value) -> int128_t { + return value; + } + + explicit Value(void *impl); +}; + +template <> +auto Value::Get() const -> bool; +template <> +auto Value::Get() const -> uint8_t; +template <> +auto Value::Get() const -> uint16_t; +template <> +auto Value::Get() const -> uint32_t; +template <> +auto Value::Get() const -> uint64_t; +template <> +auto Value::Get() const -> uint128_t; +template <> +auto Value::Get() const -> int8_t; +template <> +auto Value::Get() const -> int16_t; +template <> +auto Value::Get() const -> int32_t; +template <> +auto Value::Get() const -> int64_t; +template <> +auto Value::Get() const -> int128_t; +template <> +auto Value::Get() const -> float; +template <> +auto Value::Get() const -> double; +template <> +auto Value::Get() const -> varchar_t; +template <> +auto Value::Get() const -> blob_t; +template <> +auto Value::Get() const -> date_t; +template <> +auto Value::Get() const -> dtime_t; +template <> +auto Value::Get() const -> dtime_ns_t; +template <> +auto Value::Get() const -> dtime_tz_t; +template <> +auto Value::Get() const -> timestamp_t; +template <> +auto Value::Get() const -> timestamp_s_t; +template <> +auto Value::Get() const -> timestamp_ms_t; +template <> +auto Value::Get() const -> timestamp_ns_t; +template <> +auto Value::Get() const -> timestamp_tz_t; +template <> +auto Value::Get() const -> timestamp_tz_ns_t; +template <> +auto Value::Get() const -> interval_t; +template <> +auto Value::Get() const -> bit_t; +template <> +auto Value::Get() const -> bignum_t; +template <> +auto Value::Get() const -> uuid_t; +template <> +auto Value::Get() const -> LogicalType; + +template +auto Factory::CreateValue(T &&value) -> Value { + return Value::Create(*this, std::forward(value)); +} + +/// The current value of a setting, and the scope it was read from. Destructures: +/// `auto [value, scope] = config.GetOption(name)`. +struct OptionValue { + /// The value, typed as the setting. + Value value; + /// GLOBAL or SESSION, as DuckDB attributes the value. + SettingScope scope; +}; + +/// One parameter of a type: a value, plus a name when the parameter is a named one. A parameter with an empty name is +/// positional. +struct TypeParam { + /// A named parameter. + /// @param name The parameter's name. + /// @param value The parameter's value; moved in. + TypeParam(std::string_view name, Value value) : name(name), value(std::move(value)) { + } + + /// A positional parameter. + /// @param value The parameter's value; moved in. + explicit TypeParam(Value value) : name(""), value(std::move(value)) { + } + + /// The parameter's name, empty when it is positional. + auto GetName() const -> const std::string & { + return name; + } + + /// The parameter's value. + auto GetValue() const -> const Value & { + return value; + } + + /// The parameter's value, mutably. + auto GetValue() -> Value & { + return value; + } + +private: + std::string name; + Value value; +}; + +/// Builds a type a piece at a time, without assembling a parameter vector by hand. Start one from +/// `Factory::CreateType()`, chain the setters, and call `Build`. +/// Nested types are added by passing a callback that fills in a builder of its own. +template +class TypeBuilder { +public: + explicit TypeBuilder(CTX &context) : ctx(context) { + } + + /// Identifies the type to build by its id. Takes precedence over `SetName`. + auto SetTypeId(LogicalTypeId type_id_p) -> TypeBuilder & { + type_id = type_id_p; + return *this; + } + + /// Identifies the type to build by name, which is how extension-registered types are reached. + auto SetName(std::string_view name_p) -> TypeBuilder & { + name = name_p; + return *this; + } + + /// Appends a positional type parameter. + auto AddParam(const LogicalType &type) -> TypeBuilder & { + params.emplace_back("", ctx.CreateValue(type)); + return *this; + } + + /// Appends a named type parameter, e.g. a STRUCT field. + auto AddParam(std::string_view name_p, const LogicalType &type) -> TypeBuilder & { + params.emplace_back(name_p, ctx.CreateValue(type)); + return *this; + } + + /// Appends a named value parameter, e.g. a VARCHAR's collation. + template >> + auto AddParam(std::string_view name_p, const T &value) -> TypeBuilder & { + params.emplace_back(name_p, ctx.CreateValue(value)); + return *this; + } + + /// Appends a positional value parameter, e.g. a DECIMAL's width. + template >> + auto AddParam(const T &value) -> TypeBuilder & { + params.emplace_back("", ctx.CreateValue(value)); + return *this; + } + + /// Appends a named parameter holding a nested type. + /// @param name_p The parameter's name. + /// @param builder Called with a fresh builder; whatever it composes becomes the parameter. + template >> + auto AddParam(std::string_view name_p, F &&builder) -> TypeBuilder & { + TypeBuilder nested_builder(ctx); + builder(nested_builder); + params.emplace_back(name_p, ctx.CreateValue(nested_builder.Build())); + return *this; + } + + /// Appends a positional parameter holding a nested type. + /// @param builder Called with a fresh builder; whatever it composes becomes the parameter. + template >> + auto AddParam(F &&builder) -> TypeBuilder & { + TypeBuilder nested_builder(ctx); + builder(nested_builder); + params.emplace_back("", ctx.CreateValue(nested_builder.Build())); + return *this; + } + + /// Builds the type, by id when one was set and by name otherwise. The builder keeps its name, id and parameters, so + /// a later `Build` repeats the same type. + auto Build() -> LogicalType { + if constexpr (std::is_same_v) { + if (type_id != LogicalTypeId::INVALID) { + return ctx.CreateType(type_id, params); + } else { + return ctx.CreateType(name, params); + } + } else if constexpr (std::is_same_v) { + if (type_id != LogicalTypeId::INVALID) { + return ctx.CreateType(type_id, params); + } else { + return ctx.CreateType(name, params); + } + } else { + static_assert(detail::always_false::value, "TypeBuilder can only be used with Connection or Context"); + return ctx.CreateType(name, params); + } + } + +private: + LogicalTypeId type_id = LogicalTypeId::INVALID; + std::string name; + std::vector params; + CTX &ctx; +}; + +/// One parameter binding for the named-parameter `Connection::Execute` overload. +struct NamedParam { + /// The parameter to bind, matching $name case-insensitively. When empty, the binding is positional instead: the + /// first `NamedParam` binds $1, the second $2, and so on. A statement cannot mix named and positional parameters. + std::string name; + /// The value to bind. + Value value; +}; + +//---------------------------------------------------------------------------------------------------------------------- +// Arena +//---------------------------------------------------------------------------------------------------------------------- +// Vectors of variable-length types like strings, blobs, bits, bignums and geometries contain an auxiliary arena +// allocator called the "String Heap", which lives for as long as the vector itself lives. This is used to store the +// actual bytes e.g. a `blob_t` references in the non-inlined case. Writing a string or a blob to a vector is +// therefore usually done in two steps: allocate the bytes in the arena (heap), then place the resulting blob_t in the +// vector, referencing the bytes. `Vector::AssignString` does both at once and is what most fills want. Go through the +// heap directly when the bytes and their placement are decided separately, e.g. to write one copy of a value that +// several rows point at. + +/// A borrowed handle to a vector's string heap, valid until that vector is destroyed or reshaped, e.g. by a `Flatten`. +class Arena final : public detail::Handle { + friend detail::HandleFactory; + +public: + Arena(Arena &&) noexcept = default; + Arena &operator=(Arena &&) noexcept = default; + + ~Arena() override; + + /// Reserves uninitialized bytes in the heap, to build a value in place rather than copy one in. + /// @param byte_len How many bytes to reserve. + /// @return The reserved memory, valid as long as the heap is. Write it, wrap it in a `varchar_t` / `blob_t`, and + /// place that with `Vector::SetString`. + auto Allocate(idx_t byte_len) -> uint8_t *; + + /// Copies a string into the heap. + /// @param data The bytes to copy. Up to `varchar_t::INLINE_LENGTH` bytes are stored directly in the returned value. + /// @return The string as a `varchar_t`, with validated UTF-8, valid as long as the heap is. + /// Place it in the vector owning this heap with `Vector::SetString`. + /// @throws Exception On malformed UTF-8 or when the data exceeds the 4 GiB an element can describe. + auto AddString(std::string_view data) -> varchar_t { + if (data.size() > (std::numeric_limits::max)()) { + ThrowStringTooLong(data.size()); + } + ValidateUTF8(data); + return AddStringUnsafe(data); + } + + /// Copies text without UTF-8 validation. The caller must ensure that the text is valid. + auto AddStringUnsafe(std::string_view data) -> varchar_t { + auto bytes = AddBlob(data); + return varchar_t(bytes.data(), bytes.size()); + } + + /// `AddString` for arbitrary bytes rather than text. + auto AddBlob(std::string_view data) -> blob_t { + if (data.size() > (std::numeric_limits::max)()) { + ThrowStringTooLong(data.size()); + } + const auto size = static_cast(data.size()); + if (size <= blob_t::INLINE_LENGTH) { + return blob_t(data.data(), size); + } + auto *bytes = Allocate(size); + std::memcpy(bytes, data.data(), size); + return blob_t(reinterpret_cast(bytes), size); + } + +private: + explicit Arena(void *impl); + + /// @internal Throws when a value exceeds the maximum byte string length. + [[noreturn]] static void ThrowStringTooLong(idx_t size); +}; + +//---------------------------------------------------------------------------------------------------------------------- +// Vector +//---------------------------------------------------------------------------------------------------------------------- +// A column of values: one array of a primitive type, a validity mask saying which rows are NULL, and child vectors +// for the nested types. This is the preferred way to write/read data in and out of DuckDB. One call to +// `Vector::GetView` or `Vector::GetDataMutable` and the per-row work is plain array indexing -- as opposed to `Value`, +// which handles one cell at a time, and cost a lot in e.g. allocation overhead. +// +// The same column can be laid out in more than one way: a vector whose rows all share a value is stored once, and one +// that selects from another is stored as a selection over it. Reading through `VectorView` handles all of those. +// When writing you will generally produce a FLAT vector, but you can also call `Flatten` to force any vector into the +// basic contiguous data layout. + +/// How a vector is laid out. +enum class VectorType : uint8_t { + /// A layout with no direct read support here, such as a compressed or shredded one. `Flatten` first. + OTHER = 0, + /// One element per row. + FLAT = 1, + /// A single element standing for every row. + CONSTANT = 2, + /// A selection over another vector's elements. + DICTIONARY = 3, +}; + +/// A read view over a vector: its data, validity, selection and row count, fetched in a single call so that everything +/// below is plain inline arithmetic. +/// +/// The pointers are borrowed from the vector and stay valid until the chunk that owns it is destroyed -- or until the +/// vector is reshaped, e.g. by `Flatten` or `SetSize`, so re-take the view after any such call. +struct VectorView { + /// The buffer holding the elements, to be read as an array of the primitive type matching the vector's type. + const void *data; + /// The validity mask, or `nullptr` when every row is valid. + const uint64_t *validity; + /// The selection: which element each row reads, or nullptr when row `i` reads element `i`. + const uint32_t *sel; + /// How many rows the view covers. + idx_t count; + + /// The buffer, typed. + template + auto Data() const -> const T * { + return static_cast(data); + } + + /// The element row `i` reads. A CONSTANT vector sends every row to element 0. + auto SelAt(idx_t i) const -> idx_t { + return sel ? static_cast(sel[i]) : i; + } + + /// Whether an element is a value rather than NULL. + /// @param row An element index, i.e. one already put through `SelAt`. + auto RowIsValid(idx_t row) const -> bool { + return !validity || (validity[row >> 6] & (static_cast(1) << (row & 63))) != 0; + } + + /// Whether a row holds a value rather than NULL. Validity follows the selection, so this is the one to use with a + /// loop counter. + /// @param i A row index in [0, count). + auto IsValid(idx_t i) const -> bool { + return RowIsValid(SelAt(i)); + } + + /// Whether every row in [0, count) holds a value rather than NULL. + auto AllValid() const -> bool { + if (!validity) { + return true; + } + if (sel) { + for (idx_t i = 0; i < count; i++) { + if (!IsValid(i)) { + return false; + } + } + return true; + } + // Compare whole words, masking out the bits past `count` in the last one + const auto whole_words = count / 64; + for (idx_t i = 0; i < whole_words; i++) { + if (validity[i] != ~static_cast(0)) { + return false; + } + } + const auto tail_bits = count % 64; + if (tail_bits != 0) { + const auto tail_mask = (static_cast(1) << tail_bits) - 1; + if ((validity[whole_words] & tail_mask) != tail_mask) { + return false; + } + } + return true; + } +}; + +/// A writer over a FLAT vector's validity mask, from `Vector::GetValidityMutable`. Word W bit N covers row W*64+N, and +/// a set bit means the row holds a value rather than NULL. +/// +/// Writes here touch one vector's mask and nothing else. Since a NULL STRUCT or ARRAY row requires its descendant +/// elements to be NULL as well, use `Vector::SetNull` (which will set the validity of child vectors recursively) for +/// those rather than clearing the parent's bit. When filling nested masks by hand, use `SetAllInvalid` to clear the +/// child masks up front and then set the individual bits as values are written. +struct ValidityMask { + /// The raw mask words, for writes this struct does not cover. + uint64_t *words; + + /// Marks a row as holding a value. + auto SetValid(idx_t row) -> void { + words[row >> 6] |= uint64_t(1) << (row & 63); + } + + /// Marks a row as NULL. + auto SetInvalid(idx_t row) -> void { + words[row >> 6] &= ~(uint64_t(1) << (row & 63)); + } + + /// Whether a row holds a value rather than NULL. + auto RowIsValid(idx_t row) const -> bool { + return (words[row >> 6] & (uint64_t(1) << (row & 63))) != 0; + } + + /// Marks rows [0, count) NULL. Writes whole words, so bits past `count` in the last word are cleared too, which + /// only matters if the vector grows afterwards. + auto SetAllInvalid(idx_t count) -> void { + for (idx_t i = 0; i < (count + 63) / 64; i++) { + words[i] = 0; + } + } + + /// Marks rows [0, count) as holding values: the counterpart of `SetAllInvalid`, to reset a mask before refilling + /// rather than setting each bit as it is written. Writes whole words, so bits past `count` in the last word are + /// set too, which only matters if the vector grows afterwards. + auto SetAllValid(idx_t count) -> void { + for (idx_t i = 0; i < (count + 63) / 64; i++) { + words[i] = ~uint64_t(0); + } + } +}; + +/// A borrowed handle to one column of a chunk, or to one child of another vector. Valid for as long as the chunk or +/// parent vector it belongs to is valid. +class Vector final : public detail::Handle { + friend detail::HandleFactory; + +public: + Vector(Vector &&) noexcept = default; + Vector &operator=(Vector &&) noexcept = default; + + ~Vector() override; + + /// The buffer for writing, typed. The vector must be FLAT or CONSTANT, and `T` must match its type. + /// Raw writes to VARCHAR storage must preserve valid UTF-8. + template + auto GetDataMutable() -> T * { + return static_cast(GetDataMutable()); + } + + /// The buffer for writing, untyped. + /// @throws InvalidInputException Unless the vector is FLAT or CONSTANT. + auto GetDataMutable() -> void *; + + /// How many child vectors this one has: 1 for LIST, MAP and ARRAY, one per field for STRUCT and TUPLE, one per + /// member plus the leading tag for UNION, and 0 for anything else. A MAP's child is its entries, a STRUCT of the + /// keys and the values. + auto GetChildCount() const -> idx_t; + + /// One child vector, e.g. a LIST's elements or a STRUCT's field. A LIST's child is sized to its capacity, not to + /// the parent's row count. + /// @param index Child index in [0, GetChildCount()). + /// @return A borrowed handle, valid until this vector is destroyed or reshaped. + auto GetChild(idx_t index) const -> Vector; + + /// Rewrites the vector as a FLAT one, materializing one element per row. Pointers and views taken from it + /// beforehand do not survive this. + auto Flatten() const -> void; + + /// Repoints the vector at another vector's data, without copying: the two then alias the same buffers, in the + /// source's layout, until one of them is reset or re-referenced. Works for any type, including nested ones, and + /// is the way to hand an already-materialized vector to an output vector without a per-row copy. Pointers and + /// views taken from this vector beforehand do not survive this. + /// @param source The vector to reference. Its data must outlive every read of this vector. + /// @throws InvalidInputException When the source's type does not match the vector's. + auto Reference(const Vector &source) -> void; + + /// Casts every row into `target`, like SQL `CAST`, from this vector's type to the target's. `target` is replaced + /// by the result, taking this vector's size; pointers and views taken from it beforehand do not survive this. + /// A connection's or callback's factory casts with that client's cast functions and settings, an + /// instance's factory with the built-in casts only. + /// @throws Exception When a row does not convert; `target` is then unspecified. + auto Cast(Factory &factory, Vector &target) const -> void; + + /// `Cast` like SQL `TRY_CAST`: a row that does not convert becomes NULL in `target` instead of failing the cast. + /// @param error_message Optional. When not every row converted, receives the conversion error of one that did not. + /// @return Whether every row converted. + auto TryCast(Factory &factory, Vector &target, std::string *error_message = nullptr) const -> bool; + + /// How many rows the vector holds. + auto GetSize() const -> idx_t; + + /// Sets how many rows the vector holds, reallocating if needed, which invalidates views and pointers taken + /// earlier. A chunk derives its row count from its vectors, so this is also how a hand-filled chunk gets its + /// cardinality: size every column alike. + auto SetSize(idx_t size) -> void; + + /// Reads the vector in a single call, so that the per-row work afterwards is inline. + /// @return A view borrowed from the vector. Taking the view of a DICTIONARY vector may flatten the vector it + /// selects from, which invalidates views taken from that one earlier. + /// @throws InvalidInputException On `VectorType::OTHER`; `Flatten` first. + auto GetView() const -> VectorView; + + /// How the vector is laid out. + auto GetVectorType() const -> VectorType; + + /// The logical type of the vector's rows. + auto GetLogicalType() const -> LogicalType; + + /// The validity mask for writing, allocating it if the vector does not have one yet. + /// @throws InvalidInputException Unless the vector is FLAT. + auto GetValidityMutable() -> ValidityMask; + + /// Sets a row NULL, including the descendant elements of a STRUCT or ARRAY row. LIST (and MAP) children are left + /// alone, since a NULL list has no elements to speak of. Use this rather than clearing mask bits for any nested + /// type. + /// @param row A row index within the vector's size. + /// @throws InvalidInputException On a non-FLAT vector or an out-of-range row. + auto SetNull(idx_t row) -> void; + + /// Sets the single validity bit of a CONSTANT vector. Setting it valid writes no value: element 0 keeps whatever + /// was last written to it. + /// @param valid Whether the vector holds a value rather than NULL. + /// @throws InvalidInputException Unless the vector is CONSTANT. + auto SetConstantValid(bool valid) -> void; + + /// Rewrites the vector as a CONSTANT one: a single value standing for every row. + /// @param value The value every row takes. + /// @param count How many rows the vector then holds. + /// @throws InvalidInputException When the value's type does not match the vector's. + auto MakeConstant(const Value &value, idx_t count) -> void; + + /// Rewrites the vector as the arithmetic sequence start, start + increment, ... The result reads as + /// `VectorType::OTHER`, so `Flatten` before reading it through `GetView`. + /// @param start The first row's value. + /// @param increment The step between rows. + /// @param count How many rows the vector then holds. + auto MakeSequence(int64_t start, int64_t increment, idx_t count) -> void; + + /// Reads one cell as a `Value`, whatever the layout and whatever the type -- including the types without a view + /// layout, such as VARIANT -- and without flattening. Costs an owned value per call, so read bulk data through + /// `GetView` instead. + /// @param row A row index within the vector's size. + auto GetValue(idx_t row) const -> Value; + + /// Writes one cell from a `Value`, whatever the type. The value is copied in and cast to the vector's type. Costs + /// a value write per call, so fill bulk data through `GetDataMutable` instead. + /// @param row A row index within the vector's size. + /// @param value The value to write. + /// @throws InvalidInputException On a non-FLAT vector or an out-of-range row; flatten first. + auto SetValue(idx_t row, const Value &value) -> void; + + /// Borrows this vector's string heap, to write bytes whose placement is decided separately -- deduplicating, + /// scattering, reordering. For a straightforward fill prefer `AssignString`. + /// @return The heap. The vector must be of a string-backed type such as VARCHAR, BLOB, BIT or BIGNUM. + auto GetHeap() -> Arena; + + /// Copies bytes into the vector's heap and places the string value with `SetString`. + /// VARCHAR values are constructed with `Arena::AddString`; binary values are copied without UTF-8 validation. + /// Looks the heap up per call, so flattening in between is safe. + /// @param index The element to write: any index within the size of a FLAT vector, only 0 for a CONSTANT one. + /// @param data The bytes to copy. The vector must be of a string-backed type such as VARCHAR, BLOB, BIT or BIGNUM. + /// @throws InvalidInputException On malformed VARCHAR text, before changing the slot. + auto AssignString(idx_t index, std::string_view data) -> void; + + /// Like `AssignString`, but skips UTF-8 validation. The caller must ensure VARCHAR values contain valid UTF-8. + auto AssignStringUnsafe(idx_t index, std::string_view data) -> void; + + /// Writes a string value into the vector without UTF-8 validation. + /// @param index The element to write: any index within the size of a FLAT vector, only 0 for a CONSTANT one. + /// @param value A string value from this vector's own heap. A non-inlined value from another vector dangles. + /// VARCHAR values must contain valid UTF-8. + auto SetString(idx_t index, varchar_t value) -> void; + +private: + explicit Vector(void *impl); + + /// @internal Throws `InvalidInputException` if [start, start + count) is not writable: a CONSTANT vector has a + /// single element, so only index 0 may be written. + auto CheckWriteRange(idx_t start, idx_t count) const -> void; +}; + +//---------------------------------------------------------------------------------------------------------------------- +// DataChunk +//---------------------------------------------------------------------------------------------------------------------- +// A batch of rows: one `Vector` per column, all of the same logical length. +// Chunks are the main "unit of execution" in DuckDB, and usually contain a couple of thousand rows at a time. + +/// A batch of rows, column by column. A chunk owns its vectors, so it must outlive any `Vector`, `VectorView` or +/// pointer taken from it. +class DataChunk final : public detail::Handle { + friend detail::HandleFactory; + +public: + /// An empty chunk with a column per type, ready to be filled: write the columns' data and give every column its + /// row count with `Vector::SetSize`. The chunk's memory is allocated through the factory's database, so it is + /// accounted to that database. + /// @param factory The factory whose database supplies the chunk's memory. + /// @param types One type per column. Types containing ANY are rejected. + DataChunk(Factory &factory, const std::vector &types); + + DataChunk(DataChunk &&other) noexcept { + std::swap(impl, other.impl); + std::swap(owned, other.owned); + } + DataChunk &operator=(DataChunk &&other) noexcept { + std::swap(impl, other.impl); + std::swap(owned, other.owned); + return *this; + } + + ~DataChunk() override; + + /// How many columns the chunk has. + auto GetVectorCount() const -> idx_t; + + /// How many rows the chunk holds. + auto GetRowCount() const -> idx_t; + + /// How many rows the chunk can hold, e.g. how many rows a table function may write into its output chunk in one + /// call. Unstable API. + auto GetCapacity() const -> idx_t; + + /// Empties the chunk so it can be filled again: its row count becomes 0, and its vectors writable FLAT vectors of + /// their types, as on creation. Pointers and views taken from the chunk or its vectors beforehand do not survive + /// this. Not for a chunk DuckDB lends to a callback for reading. + auto Clear() -> void; + + /// Access one column, e.g. to read or write its data. + /// @param index Column index in [0, GetVectorCount()). + /// @return A borrowed handle, valid for as long as this chunk is. + auto GetVector(idx_t index) const -> Vector; + + /// A deep copy of this chunk, its memory allocated through the factory's database. The copy is flattened and + /// owns all its data, so it stays valid after this chunk -- or whatever backs it, such as a + /// `ColumnDataCollection` scan -- is gone. + /// @param factory The factory whose database supplies the copy's memory. + auto Copy(Factory &factory) const -> DataChunk; + +private: + explicit DataChunk(void *impl, bool owned); + bool owned = false; // TODO: This should be fixed C++ side +}; + +//---------------------------------------------------------------------------------------------------------------------- +// Column Data Collection +//---------------------------------------------------------------------------------------------------------------------- +// A buffer-managed set of rows: append chunks in, scan them back out in order. DuckDB owns the memory and spills the +// rows to disk when they outgrow it, so a collection can hold far more than memory allows. A collection must not be +// scanned while it is being appended to, and must not be appended to concurrently: for parallel appends, fill one +// collection per thread and `Combine` them at the end. + +/// An owned collection of rows, all sharing one set of column types fixed at construction. +/// It must not outlive the `Connection` or `Context` it was created from. +class ColumnDataCollection final : public detail::Handle { + friend detail::HandleFactory; + +public: + /// Opaque state for appending, from `CreateAppendState`. Only meaningful with the collection that created it, and + /// invalidated by `Reset`. + class AppendState final : public detail::Handle { + friend detail::HandleFactory; + + public: + AppendState(AppendState &&) noexcept = default; + AppendState &operator=(AppendState &&) noexcept = default; + ~AppendState() override; + + private: + explicit AppendState(void *impl); + }; + + /// Opaque state shared by every thread of one scan, from `CreateSharedScanState`: it coordinates which rows each + /// worker reads and tracks the scan's overall progress. Only meaningful with the collection that created it, and + /// invalidated by `Reset`. + class SharedScanState final : public detail::Handle { + friend detail::HandleFactory; + + public: + SharedScanState(SharedScanState &&) noexcept = default; + SharedScanState &operator=(SharedScanState &&) noexcept = default; + ~SharedScanState() override; + + private: + explicit SharedScanState(void *impl); + }; + + /// Opaque per-thread state of one scan, from `CreateWorkerScanState`. It also keeps the buffers backing the chunk + /// its thread most recently scanned alive: scans are zero-copy, so a scanned chunk's data is only valid until this + /// state's next `Scan` or its destruction. + class WorkerScanState final : public detail::Handle { + friend detail::HandleFactory; + + public: + WorkerScanState(WorkerScanState &&) noexcept = default; + WorkerScanState &operator=(WorkerScanState &&) noexcept = default; + ~WorkerScanState() override; + + private: + explicit WorkerScanState(void *impl); + }; + + /// An empty collection, its memory managed by the factory's database. + /// @param factory The factory whose database supplies the collection's memory. + /// @param types One type per column, at least one; every chunk appended must match them exactly. Types containing + /// ANY are rejected. + ColumnDataCollection(Factory &factory, const std::vector &types); + + ColumnDataCollection(ColumnDataCollection &&) noexcept = default; + ColumnDataCollection &operator=(ColumnDataCollection &&) noexcept = default; + + ~ColumnDataCollection() override; + + /// How many rows the collection holds. + auto GetRowCount() const -> idx_t; + + /// Drops all rows and releases their memory, keeping the column types; the collection is immediately appendable + /// again. Outstanding append and scan states are invalidated: create new ones. Prefer `Clear` when the collection + /// is about to be refilled. + auto Reset() -> void; + + /// Drops all rows but keeps their memory, so the next appends write into buffers that are already allocated; + /// prefer it over `Reset` when the collection is refilled repeatedly. The column types are unchanged and the + /// collection is immediately appendable again. Outstanding append and scan states are invalidated: create new + /// ones. + auto Clear() -> void; + + /// Moves another collection's rows to the end of this one, consuming it. The source must have the same column + /// types, and both collections must come from the same database -- the rows keep their original buffers rather + /// than being copied. + /// @param source The collection to consume. Left untouched when the merge is refused. + /// @throws InvalidInputException When the column types differ, or when `source` is this collection. + auto Combine(ColumnDataCollection &&source) -> void; + + /// Starts appending: the returned state carries the append's progress between `Append` calls. + auto CreateAppendState() -> AppendState; + + /// Copies a chunk's rows to the end of the collection. + /// @param state The append state to append through. + /// @param chunk The rows to append. The chunk's column types must equal the collection's exactly, and the chunk is + /// only borrowed: it can be reused, refilled and appended again. + /// VARCHAR values must already be valid UTF-8; append does not validate text. + /// @throws InvalidInputException When the chunk's columns do not match the collection's. + auto Append(AppendState &state, const DataChunk &chunk) -> void; + + /// One-shot `Append`, creating and discarding an append state internally. Prefer keeping a state across calls when + /// appending more than once. + auto Append(const DataChunk &chunk) -> void; + + /// Starts a scan over the collection's rows. One shared state per scan; each participating thread additionally + /// gets its own `CreateWorkerScanState`. + auto CreateSharedScanState() const -> SharedScanState; + + /// Per-thread state for a scan started with `CreateSharedScanState`. + auto CreateWorkerScanState() const -> WorkerScanState; + + /// Reads the next rows of the scan into a chunk. Threads sharing one `SharedScanState` each receive disjoint rows, + /// so together they scan the collection exactly once. + /// + /// The scan is zero-copy where possible: the chunk's vectors may reference the collection's buffers, kept alive by + /// the worker state, so the chunk's data is only valid until that state's next `Scan` or its destruction. + /// Make a copy with `DataChunk::Copy` to keep the scanned data longer. + /// @param shared The scan's shared state. + /// @param worker This thread's worker state. + /// @param chunk The chunk to read into; its column types must equal the collection's exactly. Reset to empty once + /// the scan is exhausted. + /// @return Whether rows were produced; false once the scan is exhausted. + /// @throws InvalidInputException When the chunk's columns do not match the collection's. + auto Scan(SharedScanState &shared, WorkerScanState &worker, DataChunk &chunk) const -> bool; + +private: + explicit ColumnDataCollection(void *impl); +}; + +//---------------------------------------------------------------------------------------------------------------------- +// Appender +//---------------------------------------------------------------------------------------------------------------------- + +/// Buffers rows on the client side and writes them to the database in bulk. +/// An appender pairs a `ColumnDataCollection` with a statement that reads it: `AppendChunk` fills the buffer without +/// touching the database, and `Flush` runs the statement over everything buffered so far and empties the buffer. +/// Many small inserts thereby become one bulk insert. +/// +/// The appender is built on the public API alone: `SqlStatement::AddCollection` exposes the buffer to the statement +/// under a name. The same can be done by hand when a different shape is needed. +/// +/// An appender is bound to the connection it was created on and can only be flushed there. It is not thread-safe: +/// append from one thread at a time, or give each thread its own appender. It must not outlive its `Connection`. +/// +/// Destroying an appender does not flush: rows buffered but not flushed are dropped. +class Appender { +public: + /// Creates an appender that inserts into `table`. + /// The buffer takes the table's columns, in order, with their types, resolved once at construction: the appender + /// keeps targeting that table even if the search path changes later. + /// @param conn The connection to buffer against and flush on. + /// @param table The table to append to, optionally qualified. + /// @throws Exception When the table cannot be resolved. + /// @note A table with generated columns needs the query constructor instead: this one lists every column, and + /// the engine refuses an INSERT that names a generated one. + Appender(Connection &conn, std::string_view table); + + /// Creates an appender that flushes by running `query`, which reads the buffer as a table named `buffer_name`. + /// Use this when a plain INSERT of every column is not what is needed: a subset of columns, an UPDATE or MERGE + /// driven by the buffer, or an INSERT with an ON CONFLICT clause. + /// @param conn The connection to buffer against and flush on. + /// @param query Exactly one SELECT, INSERT, UPDATE, DELETE or MERGE INTO statement, referring to the buffer by + /// `buffer_name`. + /// @param column_types One type per buffer column, at least one. + /// @param buffer_name The name `query` reads the buffer under. It shadows a table of that name, and must not be + /// the name of a common table expression `query` defines itself. + /// @param column_names Names for the buffer's columns; empty names them col1..colN. + /// @throws InvalidInputException When `column_types` is empty, `query` is not exactly one statement of a + /// supported type, or it already defines `buffer_name`. + Appender(Connection &conn, std::string_view query, std::vector column_types, + std::string_view buffer_name, const std::vector &column_names = {}); + + Appender(const Appender &) = delete; + Appender &operator=(const Appender &) = delete; + Appender(Appender &&) noexcept = default; + Appender &operator=(Appender &&) noexcept = default; + + /// Drops whatever is still buffered. Does not flush. + ~Appender(); + + /// The buffer's column types, in order. Build a chunk over these to fill and append, e.g. + /// `DataChunk chunk(appender.ColumnTypes())`. Valid for the appender's lifetime. + auto ColumnTypes() const -> const std::vector & { + return types; + } + + /// Buffers a whole chunk. Its column types must equal `ColumnTypes()` exactly; a mismatch is refused before + /// anything is copied. VARCHAR values must already be valid UTF-8; append does not validate text. + /// @throws InvalidInputException When the chunk's columns do not match, or a previous buffer operation failed. + void AppendChunk(DataChunk &chunk); + + /// Runs the statement over everything buffered and empties the buffer, keeping its memory for the next batch. + /// Does nothing when the buffer is empty. + /// @throws Exception When the statement fails. The rows are kept when the connection was busy or the run was + /// interrupted, so the flush can be retried; any other failure drops them. + void Flush(); + + /// Empties the buffer without running the statement, and recovers from a failed buffer operation. + void Clear(); + +private: + // The shared body of both constructors. + void Initialize(Connection &conn, const std::string &query, std::vector column_types, + const std::string &buffer_name, const std::vector &column_names); + void ResetBuffer(); + + // The connection the statement runs on. + Connection *connection = nullptr; + std::vector types; + // The buffer, declared before the statement that borrows it so it is destroyed after it. + std::unique_ptr collection; + // The statement, parsed once and re-executed per flush, and the append state, recreated after every reset. + std::unique_ptr statement; + std::unique_ptr append_state; + // Set when a buffer operation failed mid-flight, leaving the buffered rows indeterminate: appends and flushes + // refuse until Clear recovers. + bool broken = false; +}; + +//---------------------------------------------------------------------------------------------------------------------- +// Arrow +//---------------------------------------------------------------------------------------------------------------------- +// Interop with the Arrow C Data Interface, in both directions. `ArrowExporter` fills caller-allocated Arrow structs, +// which the caller then releases; `ArrowImporter` hands an Arrow array's buffers to `DataChunk`s zero-copy. Both +// resolve their schema once, at construction, and both gather rows up to a batch size across inputs, so the last +// input is marked with `flush`. To execute SQL straight into Arrow arrays, pass an `ArrowFormat` to `Execute` and +// read the `ArrowResult`. + +/// Converts Arrow arrays into `DataChunk`s against one resolved `ArrowSchema`. Construct it once, for example at a +/// table function's bind time, and reuse it for every array of that shape. Give it an array with `Append`, then call +/// `NextChunk` until it returns an empty handle. Pass `flush` on the last array, or call `Flush`. +/// The importer borrows the context it was created with and must not outlive it. One array is in flight at a time, +/// and an importer must not be used from two threads at once. +class ArrowImporter final : public detail::Handle { + friend detail::HandleFactory; + +public: + /// Resolves `schema` against `context`, extension types included. + /// @param context A context with an active transaction: resolving reads the catalog. + /// @param schema The schema to resolve. Read, not consumed; the caller keeps ownership. + /// @param batch_size Maximum rows per chunk. A long array is split across several chunks, and rows left over + /// that do not fill a batch are held back and joined with the next array unless flushed. 0 means no maximum: + /// one chunk per array. + ArrowImporter(Context &context, ArrowSchema &schema, idx_t batch_size = 0); + + ArrowImporter(ArrowImporter &&) noexcept = default; + ArrowImporter &operator=(ArrowImporter &&) noexcept = default; + + ~ArrowImporter() override; + + /// The resolved DuckDB schema: the name and logical type of every column, which is how a table function declares + /// its result columns from an Arrow schema. + auto GetSchema() const -> Schema; + + /// Gives the importer one array to convert. Take the chunks with `NextChunk`. + /// @param array The array to convert. + /// @param consume True to hand it over: its `release` is set to NULL, and the chunks reference its buffers + /// zero-copy and keep them alive. False to keep it, in which case it must stay valid until the drain finishes and + /// every chunk is a copy. A chunk that joins rows held back from the previous array is a copy either way. + /// @param flush True to mark the end of the input, releasing rows that do not fill a batch as a final short chunk. + /// @throws InvalidInputException When the previous array is not drained, or the array's shape does not match the + /// resolved schema. + auto Append(ArrowArray &array, bool consume = true, bool flush = false) -> void; + + /// Releases the held rows as a short chunk without supplying another array. Same as `Append` with no array and + /// `flush` set. + auto Flush() -> void; + + /// The next chunk of the appended array, or an empty handle once the array is drained. Rows that do not fill a + /// batch are held back for the next array unless flushed, so an empty handle does not mean every row has come + /// out. Runs under the context the importer was created with, which must still be alive. + auto NextChunk() -> DataChunk; + +private: + explicit ArrowImporter(void *impl); +}; + +/// Converts `DataChunk`s into Arrow arrays for one fixed column list. The session's Arrow settings are captured at +/// construction, so the schema it reports and the arrays it produces always agree. Give it a chunk with `Append`, +/// then call `NextArray` until it returns false. Pass `flush` on the last chunk, or call `Flush`. +/// An exporter must not be used from two threads at once. +class ArrowExporter final : public detail::Handle { + friend detail::HandleFactory; + +public: + /// @param context A context with an active transaction, whose Arrow settings are captured. + /// @param types The column types. + /// @param names The column names, one per type. + /// @param batch_size Maximum rows per array. A long chunk is split across several arrays, and rows left over + /// that do not fill a batch are held back and joined with the next chunk unless flushed. 0 means no maximum: + /// one array per chunk. + ArrowExporter(Context &context, const std::vector &types, const std::vector &names, + idx_t batch_size = 0); + + ArrowExporter(ArrowExporter &&) noexcept = default; + ArrowExporter &operator=(ArrowExporter &&) noexcept = default; + + ~ArrowExporter() override; + + /// The Arrow schema of the arrays this exporter produces, written into the caller-allocated `out`, which the + /// caller then owns and releases with `out.release(&out)`. `out` is left released on any throw. + auto GetSchema(ArrowSchema &out) const -> void; + + /// Converts one chunk in full, making the arrays it completed available from `NextArray`. The chunk is borrowed + /// and read before this returns, since the conversion copies. Rows that do not complete a batch are held back + /// and finished by the next chunk. + /// @param flush True to mark the end of the input, releasing the held rows as a final short array. + /// @throws InvalidInputException When the chunk's types do not match the exporter's. + auto Append(const DataChunk &chunk, bool flush = false) -> void; + + /// Releases the held rows as a short array without supplying another chunk. Same as `Append` with `flush` set. + auto Flush() -> void; + + /// Takes the next completed array into the caller-allocated `out`, which the caller then owns and releases. + /// @return False when none is ready, leaving `out` released; it is also left released on any throw. Rows held + /// back towards an unfinished batch are not an array yet; they come out after a further `Append` or a `Flush`. + auto NextArray(ArrowArray &out) -> bool; + +private: + explicit ArrowExporter(void *impl); +}; + +//---------------------------------------------------------------------------------------------------------------------- +// Result +//---------------------------------------------------------------------------------------------------------------------- +// A `QueryResult` is a lazily executed stream of chunks, produced by a query. +// Execution is deferred until the result is asked for its first chunk, and only one result may be live on a connection +// at a time, so read a result to the end (or destroy it) before executing again. +// +// There are two ways to consume a result, synchronously or asynchronously +// - `FetchChunk` blocks until the next chunk is ready, and is what most callers probably want. +// - `Step` performs a bounded amount of work and reports what came of it, which allows an async runtime to drive a +// query without necessarily occupying a thread indefinitely. +// An `ArrowResult` (below) is the same stream in Arrow form, read the same two ways. + +/// The status of one `QueryResult::Step` or `ArrowResult::Step`. +enum class StepStatus : uint8_t { + /// Nothing was produced by this step; call `Wait`, or come back later. + WAITING = 0, + /// A chunk was produced, or for an `ArrowResult`, an array. + CHUNK = 1, + /// The result is exhausted. Sticky. + FINISHED = 2, + /// The query was canceled. Sticky. + CANCELLED = 3, +}; + +/// The shape of a result, as `QueryResult::GetResultType` and `ArrowResult::GetResultType` report it. +enum class ResultType : uint8_t { + /// Produces rows: SELECT, EXPLAIN, RETURNING, and other row-producing statements. + QUERY_RESULT = 0, + /// Carries a count of affected rows: INSERT / UPDATE / DELETE and the like, without RETURNING. + CHANGED_ROWS = 1, + /// Produces no rows: most DDL and utility statements. + NOTHING = 2, +}; + +/// A streaming query result. +class QueryResult final : public detail::Handle { + friend detail::HandleFactory; + +public: + /// The status of one `Step`; see `cxx::StepStatus`. + using StepStatus = cxx::StepStatus; + /// The shape of a result; see `cxx::ResultType`. + using ResultType = cxx::ResultType; + /// The kind of SQL statement a result came from; see `cxx::StatementType`. + using StatementType = cxx::StatementType; + + /// The outcome of one `Step`. + struct StepResult { + /// What the step accomplished. + StepStatus status; + /// The chunk produced, empty unless `status` is CHUNK. + DataChunk chunk; + }; + + QueryResult(QueryResult &&) noexcept = default; + QueryResult &operator=(QueryResult &&) noexcept = default; + + ~QueryResult() override; + + /// The result's columns, their names and types, as one owned `Schema`. + /// @throws Exception With code `DUCKDB_V2_ERROR_INPUT_METADATA_DEFERRED` when the schema is not available yet, for + /// a statement that expands into several; step the result first. + auto GetSchema() const -> Schema; + + /// The shape of the result, so a caller can decide between consuming rows and draining without inspecting the SQL. + /// @throws Exception With code `DUCKDB_V2_ERROR_INPUT_METADATA_DEFERRED` when the shape is not available yet, for a + /// statement that expands into several; step the result first. + auto GetResultType() const -> ResultType; + + /// The kind of SQL statement this result came from, as written: MULTI for one that expands into several. + auto GetStatementType() const -> StatementType; + + /// Does a bounded amount of work and returns without blocking. + /// @return What the step accomplished, and the chunk if it produced one. + /// @throws Exception On an execution error; the error is sticky, and later `Step`s rethrow it. + auto Step() -> StepResult; + + /// Blocks until `Step` may be able to make progress, returning immediately once the result is finished or + /// canceled. May not block at all. + /// @throws Exception On an execution error. + auto Wait() -> void; + + /// The next chunk, blocking until it is ready. + /// @return The chunk, or an empty one at the end of the stream; calling it again then keeps returning empty. + /// @throws InterruptException When the query was canceled. + auto FetchChunk() -> DataChunk; + + /// Runs the result to the end, applying its side effects and discarding any rows. + /// @return The number of rows affected for a CHANGED_ROWS result, 0 otherwise. + /// @throws InterruptException When the query was canceled. + auto Drain() -> idx_t; + + /// Renders the result as the boxed table the CLI prints, consuming it. Whatever has not been read yet is + /// materialized in memory first. + /// @param max_rows How many rows to print before eliding the middle, 0 for the default. + /// @param max_width How wide the table may be, 0 for the default. + /// @param max_col_width How wide a single column may be, 0 for the default. + /// @param null_value What to print for a NULL cell; empty prints "NULL". + /// @param render_mode 0 to lay the result out in rows, 1 in columns; anything else throws. + /// @param limit The LIMIT the query itself applied, 0 for none. When the result fills it exactly, the footer reads + /// "? rows", since there may have been more. + auto RenderBox(idx_t max_rows = 0, idx_t max_width = 0, idx_t max_col_width = 0, const std::string &null_value = "", + idx_t render_mode = 0, idx_t limit = 0) -> std::string; + +private: + explicit QueryResult(void *impl); +}; + +//---------------------------------------------------------------------------------------------------------------------- +// Arrow Result +//---------------------------------------------------------------------------------------------------------------------- +// An `ArrowResult` is the same lazily executed stream in Arrow form: `Execute` with an `ArrowFormat` produces one, and +// it is read through `FetchArray` and `Step` the way a `QueryResult` is read through `FetchChunk` and `Step`. + +/// Selects the Arrow result format: passing one to `Execute` yields an `ArrowResult` instead of a `QueryResult`. +struct ArrowFormat { + /// Explicit so a braced argument cannot silently turn a parameter value into a batch size. + explicit ArrowFormat(idx_t batch_size = 0) : batch_size(batch_size) { + } + + /// Maximum rows per array; arrays can be shorter. 0 means the engine's default, 131072 today. + idx_t batch_size; +}; + +/// A streaming query result that produces Arrow arrays: the Arrow form of `QueryResult`, produced by passing an +/// `ArrowFormat` to `Connection::Execute` or `PreparedStatement::Execute`. It behaves like a `QueryResult` in all but +/// the format: execution is deferred until the result is read, it is the connection's one live result, and +/// `Connection::Interrupt` cancels it. Every array holds at most the batch size chosen at execution, and can hold +/// fewer. Arrays and schemas are written into caller-allocated structs, which the caller then owns and releases +/// through their `release` callback; they stay valid after the result, its connection, instance and environment are +/// destroyed. Use a result from one thread at a time. +class ArrowResult final : public detail::Handle { + friend detail::HandleFactory; + +public: + /// The status of one `Step`; see `cxx::StepStatus`. + using StepStatus = cxx::StepStatus; + /// The shape of a result; see `cxx::ResultType`. + using ResultType = cxx::ResultType; + /// The kind of SQL statement a result came from; see `cxx::StatementType`. + using StatementType = cxx::StatementType; + + ArrowResult(ArrowResult &&) noexcept = default; + ArrowResult &operator=(ArrowResult &&) noexcept = default; + + ~ArrowResult() override; + + /// The Arrow schema of the result's arrays, a struct with one child per column. Each call writes an independent + /// copy. Available as soon as `QueryResult::GetSchema` would be: at once for most statements, after stepping for + /// one that expands into several, such as PIVOT. + /// @param out Caller-allocated; overwritten. The caller then owns it and releases it with `out.release(&out)`. + /// @throws Exception With code `DUCKDB_V2_ERROR_INPUT_METADATA_DEFERRED` when the schema is not available yet; + /// step the result first. `out` is left released on any throw. + auto GetSchema(ArrowSchema &out) const -> void; + + /// The shape of the result, so a caller can decide between reading arrays and draining without inspecting the SQL. + /// @throws Exception With code `DUCKDB_V2_ERROR_INPUT_METADATA_DEFERRED` when the shape is not available yet, for a + /// statement that expands into several; step the result first. + auto GetResultType() const -> ResultType; + + /// The kind of SQL statement this result came from, as written: MULTI for one that expands into several. + auto GetStatementType() const -> StatementType; + + /// Does a bounded amount of work and returns without blocking. + /// @param out Caller-allocated; overwritten. On CHUNK it holds the next array, which the caller then owns and + /// releases; otherwise, and on any throw, it is left released. + /// @return What the step accomplished. + /// @throws Exception On an execution error; the error is sticky, and later `Step`s rethrow it. + auto Step(ArrowArray &out) -> StepStatus; + + /// Blocks until `Step` may be able to make progress, returning immediately once the result is finished or + /// canceled. May not block at all. + /// @throws Exception On an execution error. + auto Wait() -> void; + + /// Takes the next array, blocking until it is ready. + /// @param out Caller-allocated; overwritten. Holds the array, which the caller then owns and releases, when this + /// returns true; left released otherwise, and on any throw. + /// @return False at the end of the stream; calling it again then keeps returning false. + /// @throws InterruptException When the query was canceled. + auto FetchArray(ArrowArray &out) -> bool; + + /// Runs the result to the end, applying its side effects and discarding any rows. + /// @return The number of rows affected for a CHANGED_ROWS result, 0 otherwise. + /// @throws InterruptException When the query was canceled. + auto Drain() -> idx_t; + + /// Turns the result into an Arrow C stream, consuming it: the stream takes the result over, and this wrapper is + /// empty afterwards. The stream continues where `Step` and `FetchArray` left off, so arrays already taken are not + /// repeated. Converting runs no part of the query, but the stream's `get_schema` can: for a statement that expands + /// into several, such as PIVOT, it runs the ones before the statement that returns rows. The stream keeps the + /// result alive, with its connection busy and its instance open; releasing the stream destroys the result and + /// frees the connection. A failing `get_next` or `get_schema` returns EIO, and `get_last_error` has the message. + /// @param out Caller-allocated; overwritten. The caller then owns the stream and releases it with + /// `out.release(&out)`. + /// @throws Exception When the conversion fails; the result then stays with this wrapper, and `out` is left + /// released. + auto ToArrowStream(ArrowArrayStream &out) -> void; + +private: + explicit ArrowResult(void *impl); +}; + +//---------------------------------------------------------------------------------------------------------------------- +// Function Signature +//---------------------------------------------------------------------------------------------------------------------- + +/// How a caller passes the argument for a parameter, following Python's parameter kinds. A signature orders its +/// parameters by kind, in the order the values are listed here. +enum class FunctionParameterKind : uint8_t { + /// Passed by position only. A named argument with the parameter's name is received by `**kwargs`. + POSITIONAL_ONLY = 0, + /// Passed by position or by name. + STANDARD = 1, + /// `*args`: receives the positional arguments left over after the positional-only and standard parameters. + POSITIONAL_VARIADIC = 2, + /// Passed by name only. + NAMED_ONLY = 3, + /// `**kwargs`: receives the named arguments that match no other parameter. + NAMED_VARIADIC = 4, +}; + +/// A function's declared parameters and return type. +/// Borrowed from the function it was read from via `GetSignature`. +/// Valid for as long as the owning function is. +/// Setters mutate the function's signature in place. +class FunctionSignature final : public detail::Handle { + friend detail::HandleFactory; + +public: + FunctionSignature(FunctionSignature &&) noexcept = default; + FunctionSignature &operator=(FunctionSignature &&) noexcept = default; + + ~FunctionSignature() override; + + /// Adds a parameter without a default value. The signature orders its parameters by kind, and parameters of the + /// same kind in the order they were added. `LogicalTypeId::ANY` is accepted and leaves the argument un-cast. + /// @param name The parameter's name. + /// @param type The parameter's type. + /// @param kind How a caller passes the argument. + /// @throws InvalidInputException When the kind is not a `FunctionParameterKind`. + auto AddParameter(const std::string &name, const LogicalType &type, + FunctionParameterKind kind = FunctionParameterKind::STANDARD) -> FunctionSignature &; + + /// Adds a parameter with a default value: the caller may omit it, the function still receives the default. + /// `*args` and `**kwargs` cannot have a default value; registration rejects one. + /// @param name The parameter's name. + /// @param type The parameter's type. + /// @param default_value The value the parameter takes when the caller omits it. + /// @param kind How a caller passes the argument. + /// @throws InvalidInputException When the kind is not a `FunctionParameterKind`. + auto AddParameter(const std::string &name, const LogicalType &type, const Value &default_value, + FunctionParameterKind kind = FunctionParameterKind::STANDARD) -> FunctionSignature &; + + /// Adds the `*args` parameter, receiving any number of extra positional arguments. Pass `LogicalTypeId::ANY` to + /// leave them un-cast. + /// @param name The parameter's name. + /// @param type The type every extra positional argument is cast to. + auto AddArgs(const std::string &name, const LogicalType &type) -> FunctionSignature &; + + /// Adds the `**kwargs` parameter, receiving the named arguments that match no other parameter. Pass + /// `LogicalTypeId::ANY` to leave them un-cast. + /// @param name The parameter's name. + /// @param type The type every such named argument is cast to. + auto AddKwargs(const std::string &name, const LogicalType &type) -> FunctionSignature &; + + /// Sets the return type. Overwrites any prior return type. + /// @param type The return type. + auto SetReturnType(const LogicalType &type) -> FunctionSignature &; + +private: + explicit FunctionSignature(void *impl); +}; + +/// The documentation of a function overload, as `duckdb_functions()` reports it. +/// Borrowed from the function it was read from via `GetDocs`, and valid for as long as that function is. +/// Setters mutate the function's documentation in place, and return the documentation so they chain. +class FunctionDocs final : public detail::Handle { + friend detail::HandleFactory; + +public: + FunctionDocs(FunctionDocs &&) noexcept = default; + FunctionDocs &operator=(FunctionDocs &&) noexcept = default; + + ~FunctionDocs() override; + + /// Sets the description of the overload. Replaces any previous description. + auto SetDescription(std::string_view description) -> FunctionDocs &; + + /// Adds an example of calling the overload, e.g. a SQL expression. + /// @param title The title of the example; empty for none. + /// @param example The example. + auto AddExample(std::string_view title, std::string_view example) -> FunctionDocs &; + + /// Adds a category the overload belongs to, e.g. "string" or "aggregate". + auto AddCategory(std::string_view category) -> FunctionDocs &; + +private: + explicit FunctionDocs(void *impl); +}; + +/// The sizes of the four parts of a function call's argument list, which follow each other in this order. +struct ArgumentCounts { + /// One argument per positional-only and standard parameter, in declaration order. + idx_t positional_fixed = 0; + /// The arguments `*args` received, in call order. + idx_t positional_variadic = 0; + /// One argument per named-only parameter, in declaration order. + idx_t named_fixed = 0; + /// The arguments `**kwargs` received, in call order. + idx_t named_variadic = 0; + + /// The index of the first named argument. + auto NamedOffset() const -> idx_t { + return positional_fixed + positional_variadic; + } + /// The number of arguments in all four parts. + auto Total() const -> idx_t { + return NamedOffset() + named_fixed + named_variadic; + } +}; + +/// What every function's bind callback works with: the arguments of the call being bound, and the bind data. +/// Borrowed, valid only for the callback duration. +/// +/// The arguments form one list in the four parts of `ArgumentCounts`. A standard parameter passed by name is at its +/// declared position, and a parameter the call omitted carries its default value. +class FunctionBindInput { +public: + /// Constructs bind data of type `T`, owned by the bound function call and readable from every later callback via + /// `GetBindData`. The engine compares bind data when it compares expressions: by `operator==` when `T` has one, + /// by identity otherwise. + template + void SetBindData(ARGS &&...args) { + auto ptr = new T(std::forward(args)...); + SetBindDataInternal(ptr, detail::SelectEquals(), detail::TypedDelete); + } + + /// How many arguments the call passes, in all four parts. Valid indices for the other argument accessors are + /// [0, GetArgCount()). + auto GetArgCount() const -> idx_t; + + /// The sizes of the four parts of the argument list. + auto GetArgumentCounts() const -> ArgumentCounts; + + /// The resolved type of one argument. An ANY parameter reports the type the caller passed. + /// @param index Argument index in [0, GetArgCount()). + /// @throws InvalidInputException When the index is out of range. + auto GetArgType(idx_t index) const -> LogicalType; + + /// The constant value of one argument, folded at bind time. Use it for arguments the function needs to know + /// before execution, e.g. a format string or a target type. A table function's arguments are always constant. + /// @param index Argument index in [0, GetArgCount()). + /// @throws InvalidInputException When the index is out of range. + /// @throws Exception When the argument is not a constant expression, e.g. a column reference. + auto GetConstantArgument(idx_t index) const -> Value; + + /// `GetConstantArgument` without the failure: nullopt instead of an exception when the argument carries no + /// constant value, i.e. it is not a constant expression, its value is not yet known (an unresolved + /// prepared-statement parameter), or the index is out of range. + /// @param index Argument index in [0, GetArgCount()). + auto TryGetConstantArgument(idx_t index) const -> std::optional; + + /// The name of one argument: the parameter name for a declared parameter, the name the caller passed for an + /// argument `**kwargs` received, and an empty name for an argument `*args` received. + /// @param index Argument index in [0, GetArgCount()). + /// @throws InvalidInputException When the index is out of range. + auto GetArgName(idx_t index) const -> std::string; + + /// The index of the argument a caller passes by the given name, matched case-insensitively, or nullopt when the + /// call passed no argument of that name. Positional-only parameters are skipped, as a caller cannot pass them by + /// name. + /// @param name The name to look up. + auto FindArg(const std::string &name) const -> std::optional; + + /// The binding context. Borrowed, valid only for the callback duration. + auto GetContext() -> Context &; + +protected: + FunctionBindInput(void *args, void *context) : args(args), context(detail::HandleFactory::Make(context)) { + } + + /// The user data slot of the function, which carries the function's info table + void *GetFunctionInfo() const; + + void *args; + Context context; + +private: + void SetBindDataInternal(void *data, bool (*equals)(void *a, void *b), void (*destructor)(void *)); +}; + +//---------------------------------------------------------------------------------------------------------------------- +// Function Properties +//---------------------------------------------------------------------------------------------------------------------- +// Properties shared by every function category, set with the function classes' property setters (`SetStability`, +// `SetFallibility`, ...) to configure metadata that influences planning and execution. Category-specific properties +// (e.g. aggregate order/DISTINCT dependence) are declared as nested enums on the relevant function class. + +/// How stable/deterministic a function's result is, used by the optimizer. +enum class FunctionStability : uint8_t { + /// Always returns the same result for the same input. + CONSISTENT = 0, + /// The result may differ per row (e.g. random()). + VOLATILE = 1, + /// Stable within a single query/transaction but may change across queries (e.g. now()). + CONSISTENT_WITHIN_QUERY = 2, +}; + +/// Whether a function handles NULL inputs itself. +enum class FunctionNullHandling : uint8_t { + /// If any argument is NULL the result is NULL and the function is not invoked for that row. + DEFAULT = 0, + /// The function is invoked even when arguments are NULL and decides the result itself. + SPECIAL = 1, +}; + +/// Whether a function can raise a runtime error. +enum class FunctionFallibility : uint8_t { + /// The function never raises a runtime error. Declaring this promises the callbacks never throw; an exception + /// thrown anyway becomes an internal error. + INFALLIBLE = 0, + /// The function may raise a runtime error for some inputs (default). + FALLIBLE = 1, +}; + +/// How a function interacts with collations on its arguments. +enum class FunctionCollationHandling : uint8_t { + /// Combines collations from its inputs and propagates them to its result (default). + PROPAGATE = 0, + /// Combinable collations are executed on the input arguments before the function runs. + PUSH_COMBINABLE = 1, + /// Collations are ignored by the function. + IGNORE = 2, +}; + +/// The order guarantee a producer of rows makes about its output. +enum class OrderPreservation : uint8_t { + /// The rows have no meaningful order and may be reordered freely. + NO_ORDER = 0, + /// The rows are in insertion order, kept unless the `preserve_insertion_order` setting is disabled (default). + INSERTION_ORDER = 1, + /// The rows are in an order that must be kept, as if sorted by an `ORDER BY`, even when the + /// `preserve_insertion_order` setting is disabled. + FIXED_ORDER = 2, +}; + +//---------------------------------------------------------------------------------------------------------------------- +// Statistics +//---------------------------------------------------------------------------------------------------------------------- + +/// The statistics of an expression or a column: what values it can produce. A function's stats callback reads the +/// statistics of its arguments and narrows those of its result, and the engine uses them to simplify the query, e.g. +/// folding `x IS NULL` to false when `x` cannot be NULL. +/// +/// Every statistic states what can occur: `true` means a kind of value may be present, `false` guarantees it is +/// absent. The engine relies on the guarantees, so claiming less than the data holds produces wrong query results. +/// Borrowed: valid only for the duration of the callback that handed it out. Unstable API. +class Stats final : public detail::Handle { + friend detail::HandleFactory; + +public: + Stats(Stats &&) noexcept = default; + Stats &operator=(Stats &&) noexcept = default; + ~Stats() override = default; + + /// Whether a value can be NULL. False guarantees every value is non-NULL. + auto CanHaveNull() const -> bool; + /// Whether a value can be valid, i.e. non-NULL. False guarantees every value is NULL. When both this and + /// `CanHaveNull` are false, there are no values at all. + auto CanHaveValid() const -> bool; + + /// Sets whether a value can be NULL. Setting false is a guarantee the engine relies on; setting true is always + /// safe. + /// @throws InvalidInputException When the statistics are read-only, such as those of an argument. + auto SetCanHaveNull(bool value) -> void; + /// Sets whether a value can be valid, i.e. non-NULL. Setting false is a guarantee the engine relies on; setting + /// true is always safe. + /// @throws InvalidInputException When the statistics are read-only, such as those of an argument. + auto SetCanHaveValid(bool value) -> void; + + /// The statistics as a STRUCT value with one field per known statistic, the shape of the SQL function `stats()`: + /// `min` and `max` (values of the column's type), `has_null`, `has_no_null`, `approx_unique`, `child_stats` for + /// nested types, ... A field is absent when that statistic is unknown. Unstable API. + auto GetValue() const -> Value; + + /// Narrows the statistics from a STRUCT value in the shape `GetValue` returns: a field that is set replaces that + /// statistic, a NULL or absent field leaves it unchanged. `{'min': 20, 'max': 30, 'has_null': false}` on an + /// INTEGER column reports exactly those bounds and the absence of NULLs. A bound is a value of the column's type, + /// or one that casts to it. Every statistic states what can occur: a bound that excludes a value the scan then + /// produces, or `has_null: false` for a column with NULLs, produces wrong query results. Unstable API. + /// @throws InvalidInputException When the value is not a STRUCT, a field does not exist for the type or does not + /// convert, or the statistics are read-only, such as those of an argument. + auto SetValue(const Value &value) -> void; + +private: + explicit Stats(void *impl); +}; + +//---------------------------------------------------------------------------------------------------------------------- +// Scalar Function +//---------------------------------------------------------------------------------------------------------------------- + +/// A user-defined scalar function, built up with the setters and made live with `Connection::Register` or +/// `Extension::Register`. Create one through a `Factory` of the database it will be registered in, describe it (name, +/// signature, callbacks), then register it with `Connection::Register` or `Extension::Register`. The function object +/// may be destroyed after registration; the registered function lives on in the catalog. +/// +/// The callbacks receive their state through the input objects: `SetUserData` plants data readable from every +/// callback, the resolve types callback may resolve the return type, the bind callback may plant bind data for init +/// and exec, and the init callback may plant init data for exec. A callback reports failure by throwing; the exception +/// surfaces as the query's error. +class ScalarFunction final : public detail::Handle { + friend detail::HandleFactory; + friend class Connection; + friend class Extension; + +public: + class ResolveTypesInput; + class BindInput; + class InitInput; + class ExecInput; + class StatsInput; + + /// Called once per query while the function call is bound, before the arguments are cast to the parameter types. + /// Optional; required when the return type is ANY. + using ResolveTypesCallback = void (*)(ResolveTypesInput &input); + /// Called once per query while the function call is bound, after the arguments are cast to the parameter types. + /// Optional. + using BindCallback = void (*)(BindInput &input); + /// Called once per execution thread before the first `ExecCallback` on it. Optional. + using InitCallback = void (*)(InitInput &input); + /// Called for every batch of rows; must fill the result vector. Required. + using ExecCallback = void (*)(ExecInput &input); + /// Called while the query is optimized, possibly more than once, to narrow the statistics of the result from + /// those of the arguments. Optional; without it the engine knows nothing about the result. Unstable API. + using StatsCallback = void (*)(StatsInput &input); + + ScalarFunction(ScalarFunction &&) noexcept = default; + ScalarFunction &operator=(ScalarFunction &&) noexcept = default; + + ~ScalarFunction() override; + + /// Creates an empty ScalarFunction through `factory`. Register it through a `Connection` or an `Extension` of the + /// factory's database. + static auto Create(Factory &factory) -> ScalarFunction; + + /// Sets the function's name, as SQL will call it. + auto SetName(const std::string &name) & -> ScalarFunction &; + /// Sets the schema of the system catalog the function is registered in, for example `encodings`. Without it the + /// function is registered in the default schema. The schema must exist when the function is registered. + auto SetSchema(const std::string &schema) & -> ScalarFunction &; + /// The documentation of this overload, borrowed for in-place mutation. + auto GetDocs() -> FunctionDocs; + + /// Calls `configure` with the documentation of this overload, borrowed for in-place mutation. + template + auto WithDocs(F &&configure) & -> ScalarFunction & { + auto docs = GetDocs(); + configure(docs); + return *this; + } + + /// The function's signature, borrowed for in-place mutation. Registration requires a return type that is either + /// a fully defined concrete type, or ANY combined with a resolve types callback that resolves it. + auto GetSignature() -> FunctionSignature; + + /// Calls `configure` with the function's signature, borrowed for in-place mutation. Registration requires a return + /// type that is either a fully defined concrete type, or ANY combined with a resolve types callback that resolves + /// it. + template + auto WithSignature(F &&configure) & -> ScalarFunction & { + auto sig = GetSignature(); + configure(sig); + return *this; + } + + /// Constructs user data of type `T`, carried by the registered function and freed at engine teardown; read it from + /// any callback via the inputs' `GetUserData`. Consumed by registration: set it again before + /// re-registering. + template + auto SetUserData(ARGS &&...args) & -> ScalarFunction & { + auto ptr = new T(std::forward(args)...); + SetUserDataInternal(ptr, detail::TypedDelete); + return *this; + } + + auto SetResolveTypesCallback(ResolveTypesCallback callback) & -> ScalarFunction &; + auto SetBindCallback(BindCallback callback) & -> ScalarFunction &; + auto SetInitCallback(InitCallback callback) & -> ScalarFunction &; + auto SetExecCallback(ExecCallback callback) & -> ScalarFunction &; + auto SetStatsCallback(StatsCallback callback) & -> ScalarFunction &; + + /// How stable the function's result is across rows and queries. Defaults to `CONSISTENT`. + auto SetStability(FunctionStability value) & -> ScalarFunction &; + /// Whether the function handles NULL inputs itself. Defaults to `DEFAULT` (NULL in, NULL out). + auto SetNullHandling(FunctionNullHandling value) & -> ScalarFunction &; + /// Whether the function can raise a runtime error. Defaults to `FALLIBLE`; declaring `INFALLIBLE` promises the + /// callbacks never throw. + auto SetFallibility(FunctionFallibility value) & -> ScalarFunction &; + /// How the function interacts with collations on its arguments. Defaults to `PROPAGATE`. + auto SetCollationHandling(FunctionCollationHandling value) & -> ScalarFunction &; + +private: + explicit ScalarFunction(void *impl); + //! Moves what the callbacks need into the C handle, right before it is registered. + auto PrepareRegistration() -> void; + + auto SetUserDataInternal(void *data, void (*destructor)(void *)) -> void; + + ResolveTypesCallback resolve_types_callback = nullptr; + BindCallback bind_callback = nullptr; + InitCallback init_callback = nullptr; + ExecCallback exec_callback = nullptr; + StatsCallback stats_callback = nullptr; + detail::UserData user_data; + +public: + /// What the resolve types callback works with. The argument types are the types the caller passed, before they + /// are cast to the parameter types. Borrowed, valid only for the callback duration. + class ResolveTypesInput final : public FunctionBindInput { + friend detail::HandleFactory; + + public: + /// The user data set via `ScalarFunction::SetUserData`. + /// @throws InvalidInputException When none was set. + template + auto GetUserData() const -> T & { + return *static_cast(GetUserDataInternal()); + } + + /// Resolves the declared return type; required, and only permitted, when the signature declared it as ANY. + /// @param type The concrete return type of this bound call. + auto SetReturnType(const LogicalType &type) -> void; + + private: + ResolveTypesInput(void *args, void *result, void *context) : FunctionBindInput(args, context), result(result) { + } + + /// The bind data can only be set from the bind callback + using FunctionBindInput::SetBindData; + + void *result; + + void *GetUserDataInternal() const; + }; + + /// What the bind callback works with. The argument types are the parameter types the arguments were cast to. + /// Borrowed, valid only for the callback duration. + class BindInput final : public FunctionBindInput { + friend detail::HandleFactory; + + public: + /// Constructs bind data of type `T`, owned by the bound function call and readable from the init and exec + /// callbacks via `GetBindData`. The engine compares bind data when it compares expressions: by + /// `operator==` when `T` has one, by identity otherwise. + template + void SetBindData(ARGS &&...args) { + auto ptr = new T(std::forward(args)...); + SetBindDataInternal(ptr, detail::SelectEquals(), detail::TypedDelete); + } + + /// The user data set via `ScalarFunction::SetUserData`. + /// @throws InvalidInputException When none was set. + template + auto GetUserData() const -> T & { + return *static_cast(GetUserDataInternal()); + } + + private: + BindInput(void *args, void *result, void *context) : FunctionBindInput(args, context), result(result) { + } + + void *result; + + void SetBindDataInternal(void *data, bool (*equals)(void *a, void *b), void (*destructor)(void *)); + void *GetUserDataInternal() const; + }; + + /// What the init callback works with. Borrowed, valid only for the callback duration. + class InitInput { + friend detail::HandleFactory; + + public: + /// Constructs init data of type `T`, owned by this execution thread's function state and readable from the + /// exec callback via `GetInitData`. + template + void SetInitData(ARGS &&...args) { + auto ptr = new T(std::forward(args)...); + SetInitDataInternal(ptr, detail::TypedDelete); + } + + /// The bind data set via `BindInput::SetBindData`. + /// @throws InvalidInputException When none was set. + template + auto GetBindData() const -> const T & { + return *static_cast(GetBindDataInternal()); + } + + /// The user data set via `ScalarFunction::SetUserData`. + /// @throws InvalidInputException When none was set. + template + auto GetUserData() const -> T & { + return *static_cast(GetUserDataInternal()); + } + + /// The context the function is initialized in. Borrowed, valid only for the callback duration. + auto GetContext() -> Context &; + + private: + InitInput(void *args, void *context) : args(args), context(detail::HandleFactory::Make(context)) { + } + + void *args; + Context context; + + void SetInitDataInternal(void *data, void (*destructor)(void *)); + void *GetBindDataInternal() const; + void *GetUserDataInternal() const; + }; + + /// What the exec callback works with. Borrowed, valid only for the callback duration. + class ExecInput { + friend detail::HandleFactory; + + public: + /// The bind data set via `BindInput::SetBindData`. + /// @throws InvalidInputException When none was set. + template + auto GetBindData() const -> const T & { + return *static_cast(GetBindDataInternal()); + } + + /// The init data set via `InitInput::SetInitData`. + /// @throws InvalidInputException When none was set. + template + auto GetInitData() const -> T & { + return *static_cast(GetInitDataInternal()); + } + + /// The user data set via `ScalarFunction::SetUserData`. + /// @throws InvalidInputException When none was set. + template + auto GetUserData() const -> T & { + return *static_cast(GetUserDataInternal()); + } + + /// How many rows this execution must produce: the exec callback writes exactly this many rows to the result + /// vector. May be less than a full vector; with all-constant arguments the function runs for a single row and + /// the engine expands the result. + auto GetRowCount() const -> idx_t; + + /// How many argument vectors this execution carries, in all four parts. Valid indices for `GetArg` are + /// [0, GetArgCount()). + auto GetArgCount() const -> idx_t; + + /// The sizes of the four parts of the argument list, as the bind callback saw them. + auto GetArgumentCounts() const -> ArgumentCounts; + + /// One argument vector, at the index the bind callback used for the argument. + /// @param index Argument index in [0, GetArgCount()). + auto GetArg(idx_t index) const -> Vector; + + /// The result vector to fill. + auto GetResult() const -> Vector; + + /// The execution context. Borrowed, valid only for the callback duration. + auto GetContext() -> Context &; + + private: + ExecInput(void *args, void *context) : args(args), context(detail::HandleFactory::Make(context)) { + } + + void *args; + Context context; + + void *GetBindDataInternal() const; + void *GetInitDataInternal() const; + void *GetUserDataInternal() const; + }; + + /// What the stats callback works with. Borrowed, valid only for the callback duration. + /// + /// The result statistics start out unknown, with every kind of value possible. A callback that leaves them + /// unchanged tells the engine nothing. + class StatsInput { + friend detail::HandleFactory; + + public: + /// The bind data set via `BindInput::SetBindData`. + /// @throws InvalidInputException When none was set. + template + auto GetBindData() const -> const T & { + return *static_cast(GetBindDataInternal()); + } + + /// The user data set via `ScalarFunction::SetUserData`. + /// @throws InvalidInputException When none was set. + template + auto GetUserData() const -> T & { + return *static_cast(GetUserDataInternal()); + } + + /// How many arguments the call has, in all four parts. Valid indices for `GetArgStats` are + /// [0, GetArgCount()). + auto GetArgCount() const -> idx_t; + + /// The sizes of the four parts of the argument list, as the bind callback saw them. + auto GetArgumentCounts() const -> ArgumentCounts; + + /// The statistics of one argument, at the index the bind callback used for it. Read-only. + /// @param index Argument index in [0, GetArgCount()). + auto GetArgStats(idx_t index) const -> Stats; + + /// The statistics of the result, for the callback to narrow. + auto GetResultStats() const -> Stats; + + /// The query's context. Borrowed, valid only for the callback duration. + auto GetContext() -> Context &; + + private: + StatsInput(void *args, void *context) : args(args), context(detail::HandleFactory::Make(context)) { + } + + void *args; + Context context; + + void *GetBindDataInternal() const; + void *GetUserDataInternal() const; + }; +}; + +//---------------------------------------------------------------------------------------------------------------------- +// Aggregate Function +//---------------------------------------------------------------------------------------------------------------------- + +/// A user-defined aggregate function, built up with the setters and made live with `Connection::Register` or +/// `Extension::Register`. Create one through a `Factory` of the database it will be registered in, describe it (name, +/// signature, callbacks), then register it with `Connection::Register` or `Extension::Register`. The function object +/// may be destroyed after registration; the registered function lives on in the catalog. +/// +/// The aggregate keeps one state per group. The size callback reports how large a single state is; the init callback +/// constructs a batch of freshly allocated states; the update callback folds a batch of input rows into their rows' +/// states; the combine callback merges partial states (e.g. across threads); the finalize callback turns a batch of +/// states into result rows; and the optional destroy callback releases resources a state owns. +/// +/// The callbacks receive their state through the input objects: `SetUserData` plants data readable from every +/// callback, and the bind callback may plant bind data readable from every later callback. A callback reports failure +/// by throwing; the exception surfaces as the query's error -- except in the destroy callback, whose errors are +/// dropped, as it runs on a path that must not fail. +class AggregateFunction final : public detail::Handle { + friend detail::HandleFactory; + friend class Connection; + friend class Extension; + +public: + /// Whether the aggregate's result depends on the order in which rows are aggregated. + enum class OrderDependence : uint8_t { + /// The result depends on input order (default). + DEPENDENT = 0, + /// The result does not depend on input order. + INDEPENDENT = 1, + }; + + /// Whether the aggregate's result is affected by a DISTINCT modifier. + enum class DistinctDependence : uint8_t { + /// The result is affected by DISTINCT (default). + DEPENDENT = 0, + /// The result is not affected by DISTINCT. + INDEPENDENT = 1, + }; + + class BindInput; + class SizeInput; + class InitInput; + class UpdateInput; + class CombineInput; + class FinalizeInput; + class DestroyInput; + class StatsInput; + + /// Called once per query while the function call is bound. Optional; required when the return type is ANY. + using BindCallback = void (*)(BindInput &input); + /// Called to size a single aggregate state; must call `SetStateSize`. Required. + using SizeCallback = void (*)(SizeInput &input); + /// Called to initialize a batch of freshly allocated states in place. Required. + using InitCallback = void (*)(InitInput &input); + /// Called to fold a batch of input rows into their rows' states. Required. + using UpdateCallback = void (*)(UpdateInput &input); + /// Called to merge a batch of source states into their target states. Required. + using CombineCallback = void (*)(CombineInput &input); + /// Called to turn a batch of states into result rows. Required. + using FinalizeCallback = void (*)(FinalizeInput &input); + /// Called to release resources a batch of states owns. Optional; must not fail. + using DestroyCallback = void (*)(DestroyInput &input); + /// Called while the query is optimized, possibly more than once, to narrow the statistics of the result from + /// those of the arguments. Optional; without it the engine knows nothing about the result. Unstable API. + using StatsCallback = void (*)(StatsInput &input); + + AggregateFunction(AggregateFunction &&) noexcept = default; + AggregateFunction &operator=(AggregateFunction &&) noexcept = default; + + ~AggregateFunction() override; + + /// Creates an empty AggregateFunction through `factory`. Register it through a `Connection` or an `Extension` of + /// the factory's database. + static auto Create(Factory &factory) -> AggregateFunction; + + /// Sets the function's name, as SQL will call it. + auto SetName(const std::string &name) & -> AggregateFunction &; + /// The documentation of this overload, borrowed for in-place mutation. + auto GetDocs() -> FunctionDocs; + + /// Calls `configure` with the documentation of this overload, borrowed for in-place mutation. + template + auto WithDocs(F &&configure) & -> AggregateFunction & { + auto docs = GetDocs(); + configure(docs); + return *this; + } + + /// The function's signature, borrowed for in-place mutation. Registration requires a return type that is either + /// a fully defined concrete type, or ANY combined with a bind callback that resolves it. + auto GetSignature() -> FunctionSignature; + + /// Calls `configure` with the function's signature, borrowed for in-place mutation. Registration requires a return + /// type that is either a fully defined concrete type, or ANY combined with a bind callback that resolves it. + template + auto WithSignature(F &&configure) & -> AggregateFunction & { + auto sig = GetSignature(); + configure(sig); + return *this; + } + + /// Constructs user data of type `T`, carried by the registered function and freed at engine teardown; read it from + /// any callback via the inputs' `GetUserData`. Consumed by registration: set it again before + /// re-registering. + template + auto SetUserData(ARGS &&...args) & -> AggregateFunction & { + auto ptr = new T(std::forward(args)...); + SetUserDataInternal(ptr, detail::TypedDelete); + return *this; + } + + auto SetBindCallback(BindCallback callback) & -> AggregateFunction &; + auto SetSizeCallback(SizeCallback callback) & -> AggregateFunction &; + auto SetInitCallback(InitCallback callback) & -> AggregateFunction &; + auto SetUpdateCallback(UpdateCallback callback) & -> AggregateFunction &; + auto SetCombineCallback(CombineCallback callback) & -> AggregateFunction &; + auto SetFinalizeCallback(FinalizeCallback callback) & -> AggregateFunction &; + auto SetDestroyCallback(DestroyCallback callback) & -> AggregateFunction &; + auto SetStatsCallback(StatsCallback callback) & -> AggregateFunction &; + + /// How stable the function's result is across rows and queries. Defaults to `CONSISTENT`. + auto SetStability(FunctionStability value) & -> AggregateFunction &; + /// Whether the function handles NULL inputs itself. Defaults to `DEFAULT` (NULL in, NULL out). + auto SetNullHandling(FunctionNullHandling value) & -> AggregateFunction &; + /// Whether the function can raise a runtime error. Defaults to `FALLIBLE`; declaring `INFALLIBLE` promises the + /// callbacks never throw. + auto SetFallibility(FunctionFallibility value) & -> AggregateFunction &; + /// How the function interacts with collations on its arguments. Defaults to `PROPAGATE`. + auto SetCollationHandling(FunctionCollationHandling value) & -> AggregateFunction &; + /// Whether the result depends on the order in which rows are aggregated. Defaults to `DEPENDENT`. + auto SetOrderDependence(OrderDependence value) & -> AggregateFunction &; + /// Whether the result is affected by a DISTINCT modifier. Defaults to `DEPENDENT`. + auto SetDistinctDependence(DistinctDependence value) & -> AggregateFunction &; + +private: + explicit AggregateFunction(void *impl); + //! Moves what the callbacks need into the C handle, right before it is registered. + auto PrepareRegistration() -> void; + + auto SetUserDataInternal(void *data, void (*destructor)(void *)) -> void; + + BindCallback bind_callback = nullptr; + SizeCallback size_callback = nullptr; + InitCallback init_callback = nullptr; + UpdateCallback update_callback = nullptr; + CombineCallback combine_callback = nullptr; + FinalizeCallback finalize_callback = nullptr; + DestroyCallback destroy_callback = nullptr; + StatsCallback stats_callback = nullptr; + detail::UserData user_data; + +public: + /// What the bind callback works with. Borrowed, valid only for the callback duration. + class BindInput final : public FunctionBindInput { + friend detail::HandleFactory; + + public: + /// The user data set via `AggregateFunction::SetUserData`. + /// @throws InvalidInputException When none was set. + template + auto GetUserData() const -> T & { + return *static_cast(GetUserDataInternal()); + } + + /// Resolves the declared return type; required, and only permitted, when the signature declared it as ANY. + /// @param type The concrete return type of this bound call. + auto SetReturnType(const LogicalType &type) -> void; + + private: + BindInput(void *args, void *result, void *context) : FunctionBindInput(args, context), result(result) { + } + + void *result; + + void *GetUserDataInternal() const; + }; + + /// What the size callback works with. Borrowed, valid only for the callback duration. + class SizeInput { + friend detail::HandleFactory; + + public: + /// The bind data set via `BindInput::SetBindData`. + /// @throws InvalidInputException When none was set. + template + auto GetBindData() const -> const T & { + return *static_cast(GetBindDataInternal()); + } + + /// The user data set via `AggregateFunction::SetUserData`. + /// @throws InvalidInputException When none was set. + template + auto GetUserData() const -> T & { + return *static_cast(GetUserDataInternal()); + } + + /// Reports the size of a single aggregate state, in bytes; the callback must call this. + /// @param size The state size, in bytes. + auto SetStateSize(idx_t size) -> void; + + private: + explicit SizeInput(void *args) : args(args) { + } + + void *args; + + void *GetBindDataInternal() const; + void *GetUserDataInternal() const; + }; + + /// What the init callback works with. Borrowed, valid only for the callback duration. + class InitInput { + friend detail::HandleFactory; + + public: + /// The bind data set via `BindInput::SetBindData`. + /// @throws InvalidInputException When none was set. + template + auto GetBindData() const -> const T & { + return *static_cast(GetBindDataInternal()); + } + + /// The user data set via `AggregateFunction::SetUserData`. + /// @throws InvalidInputException When none was set. + template + auto GetUserData() const -> T & { + return *static_cast(GetUserDataInternal()); + } + + /// How many states this invocation must initialize: the length of `GetStates`. + auto GetStateCount() const -> idx_t; + + /// The states to initialize, one pointer per state. Each points to uninitialized memory of the size the size + /// callback reported; the callback must initialize all of them in place. + auto GetStates() const -> void **; + + private: + explicit InitInput(void *args) : args(args) { + } + + void *args; + + void *GetBindDataInternal() const; + void *GetUserDataInternal() const; + }; + + /// What the update callback works with. Borrowed, valid only for the callback duration. + class UpdateInput { + friend detail::HandleFactory; + + public: + /// The bind data set via `BindInput::SetBindData`. + /// @throws InvalidInputException When none was set. + template + auto GetBindData() const -> const T & { + return *static_cast(GetBindDataInternal()); + } + + /// The user data set via `AggregateFunction::SetUserData`. + /// @throws InvalidInputException When none was set. + template + auto GetUserData() const -> T & { + return *static_cast(GetUserDataInternal()); + } + + /// How many input rows this invocation carries: the length of the argument vectors and of `GetStates`. + auto GetRowCount() const -> idx_t; + + /// How many argument vectors this invocation carries, in all four parts. Valid indices for `GetArg` are + /// [0, GetArgCount()). + auto GetArgCount() const -> idx_t; + + /// The sizes of the four parts of the argument list, as the bind callback saw them. + auto GetArgumentCounts() const -> ArgumentCounts; + + /// One argument vector, at the index the bind callback used for the argument. + /// @param index Argument index in [0, GetArgCount()). + auto GetArg(idx_t index) const -> Vector; + + /// The states to update, one pointer per input row: row i of every argument vector must be aggregated into + /// state i. Different rows may point to the same state. + auto GetStates() const -> void **; + + private: + explicit UpdateInput(void *args) : args(args) { + } + + void *args; + + void *GetBindDataInternal() const; + void *GetUserDataInternal() const; + }; + + /// What the combine callback works with. Borrowed, valid only for the callback duration. + class CombineInput { + friend detail::HandleFactory; + + public: + /// The bind data set via `BindInput::SetBindData`. + /// @throws InvalidInputException When none was set. + template + auto GetBindData() const -> const T & { + return *static_cast(GetBindDataInternal()); + } + + /// The user data set via `AggregateFunction::SetUserData`. + /// @throws InvalidInputException When none was set. + template + auto GetUserData() const -> T & { + return *static_cast(GetUserDataInternal()); + } + + /// How many source/target state pairs this invocation must combine: the length of `GetSources` and + /// `GetTargets`. + auto GetStateCount() const -> idx_t; + + /// The source states, one pointer per pair. Source i must be combined into target i; the source must not be + /// modified. + auto GetSources() const -> void **; + + /// The target states, one pointer per pair. Source i must be combined into target i. + auto GetTargets() const -> void **; + + private: + explicit CombineInput(void *args) : args(args) { + } + + void *args; + + void *GetBindDataInternal() const; + void *GetUserDataInternal() const; + }; + + /// What the finalize callback works with. Borrowed, valid only for the callback duration. + class FinalizeInput { + friend detail::HandleFactory; + + public: + /// The bind data set via `BindInput::SetBindData`. + /// @throws InvalidInputException When none was set. + template + auto GetBindData() const -> const T & { + return *static_cast(GetBindDataInternal()); + } + + /// The user data set via `AggregateFunction::SetUserData`. + /// @throws InvalidInputException When none was set. + template + auto GetUserData() const -> T & { + return *static_cast(GetUserDataInternal()); + } + + /// How many states this invocation must finalize: the length of `GetStates` and the number of rows to write. + auto GetStateCount() const -> idx_t; + + /// The states to finalize, one pointer per state. State i must be finalized into result row + /// `GetResultOffset() + i`. + auto GetStates() const -> void **; + + /// The result vector to fill, starting at `GetResultOffset`. + auto GetResult() const -> Vector; + + /// The offset in the result vector at which to start writing: state i must be finalized into result row + /// `GetResultOffset() + i`. + auto GetResultOffset() const -> idx_t; + + private: + explicit FinalizeInput(void *args) : args(args) { + } + + void *args; + + void *GetBindDataInternal() const; + void *GetUserDataInternal() const; + }; + + /// What the destroy callback works with. Borrowed, valid only for the callback duration. + class DestroyInput { + friend detail::HandleFactory; + + public: + /// The bind data set via `BindInput::SetBindData`. + /// @throws InvalidInputException When none was set. + template + auto GetBindData() const -> const T & { + return *static_cast(GetBindDataInternal()); + } + + /// The user data set via `AggregateFunction::SetUserData`. + /// @throws InvalidInputException When none was set. + template + auto GetUserData() const -> T & { + return *static_cast(GetUserDataInternal()); + } + + /// How many states this invocation must destroy: the length of `GetStates`. + auto GetStateCount() const -> idx_t; + + /// The states to destroy, one pointer per state. The callback must release any resources the states own. + auto GetStates() const -> void **; + + private: + explicit DestroyInput(void *args) : args(args) { + } + + void *args; + + void *GetBindDataInternal() const; + void *GetUserDataInternal() const; + }; + + /// What the stats callback works with. Borrowed, valid only for the callback duration. + /// + /// The result statistics start out unknown, with every kind of value possible. They describe every result the + /// aggregate produces, including that of a group with no input rows, such as an ungrouped aggregate over an empty + /// table. A callback that leaves them unchanged tells the engine nothing. + class StatsInput { + friend detail::HandleFactory; + + public: + /// The bind data set via `BindInput::SetBindData`. + /// @throws InvalidInputException When none was set. + template + auto GetBindData() const -> const T & { + return *static_cast(GetBindDataInternal()); + } + + /// The user data set via `AggregateFunction::SetUserData`. + /// @throws InvalidInputException When none was set. + template + auto GetUserData() const -> T & { + return *static_cast(GetUserDataInternal()); + } + + /// How many arguments the call has, in all four parts. Valid indices for `GetArgStats` are + /// [0, GetArgCount()). + auto GetArgCount() const -> idx_t; + + /// The sizes of the four parts of the argument list, as the bind callback saw them. + auto GetArgumentCounts() const -> ArgumentCounts; + + /// The statistics of one argument, at the index the bind callback used for it. Read-only. + /// @param index Argument index in [0, GetArgCount()). + auto GetArgStats(idx_t index) const -> Stats; + + /// The statistics of the result, for the callback to narrow. + auto GetResultStats() const -> Stats; + + /// The query's context. Borrowed, valid only for the callback duration. + auto GetContext() -> Context &; + + private: + StatsInput(void *args, void *context) : args(args), context(detail::HandleFactory::Make(context)) { + } + + void *args; + Context context; + + void *GetBindDataInternal() const; + void *GetUserDataInternal() const; + }; +}; + +//---------------------------------------------------------------------------------------------------------------------- +// Bound Expression +//---------------------------------------------------------------------------------------------------------------------- + +/// The type of a bound expression node. Mirrors the C API's `DUCKDB_V2_EXPRESSION_TYPE`: the node types a filter +/// predicate can contain, every other node type reporting `INVALID`. +/// +/// Comparisons, `BETWEEN` and casts are regular scalar function calls once bound: they have the function's children +/// and name, and only their type tells them apart from any other function. A cast has one child, the value being +/// cast, and its target type is the node's return type. +enum class ExpressionType : uint8_t { + /// A node type this API does not model. Its children can still be walked. + INVALID = 0, + /// A cast. One child; `Expression::GetCastMode` tells a `TRY_CAST` apart. + OPERATOR_CAST = 12, + /// Logical `NOT`. One child. + OPERATOR_NOT = 13, + /// `IS NULL`. One child. + OPERATOR_IS_NULL = 14, + /// `IS NOT NULL`. One child. + OPERATOR_IS_NOT_NULL = 15, + /// `=`. Two children. + COMPARE_EQUAL = 25, + /// `<>`. Two children. + COMPARE_NOTEQUAL = 26, + /// `<`. Two children. + COMPARE_LESSTHAN = 27, + /// `>`. Two children. + COMPARE_GREATERTHAN = 28, + /// `<=`. Two children. + COMPARE_LESSTHANOREQUALTO = 29, + /// `>=`. Two children. + COMPARE_GREATERTHANOREQUALTO = 30, + /// `IN`. The first child is the value tested, the remaining children are the candidates. + COMPARE_IN = 35, + /// `NOT IN`. The first child is the value tested, the remaining children are the candidates. + COMPARE_NOT_IN = 36, + /// `IS DISTINCT FROM`. Two children. + COMPARE_DISTINCT_FROM = 37, + /// `BETWEEN`. Three children: the value tested, the lower bound and the upper bound. + COMPARE_BETWEEN = 38, + /// `IS NOT DISTINCT FROM`. Two children. + COMPARE_NOT_DISTINCT_FROM = 40, + /// Logical `AND`. Two or more children. + CONJUNCTION_AND = 50, + /// Logical `OR`. Two or more children. + CONJUNCTION_OR = 51, + /// A constant. No children; read it with `Expression::GetConstantValue`. + VALUE_CONSTANT = 75, + /// A prepared statement parameter whose value is not known yet. No children. + VALUE_PARAMETER = 76, + /// A call to a scalar function other than the ones listed above. The children are its arguments; read the name + /// with `Expression::GetFunctionName`. + BOUND_FUNCTION = 141, + /// A `CASE` expression. The children are each `WHEN` condition followed by its `THEN` result, then the `ELSE` + /// result. + CASE_EXPR = 150, + /// `COALESCE`. One or more children. + OPERATOR_COALESCE = 152, + /// A reference to a column. No children; read it with `Expression::GetColumnIndex`. + BOUND_COLUMN_REF = 228, +}; + +/// A node of a bound expression tree: an expression the engine has resolved every column and function of, handed +/// to callbacks that may want to look inside a predicate (see `TableFunction::FilterPushdownInput`). Borrowed and +/// read-only: valid only for the duration of the callback that handed it out, and the children obtained via +/// `GetChild` share their parent's lifetime. +class Expression final : public detail::Handle { + friend detail::HandleFactory; + +public: + Expression(Expression &&) noexcept = default; + Expression &operator=(Expression &&) noexcept = default; + ~Expression() override = default; + + /// The node's type, which decides what its children mean and which of the accessors below apply. + auto GetType() const -> ExpressionType; + /// The logical type the node evaluates to. For a cast, the target type. + auto GetReturnType() const -> LogicalType; + /// How many child nodes the node has. Works for every type, including `ExpressionType::INVALID`. + auto GetChildCount() const -> idx_t; + /// A child node, ordered as `ExpressionType` describes. + /// @throws InvalidInputException When the index is out of bounds. + auto GetChild(idx_t index) const -> Expression; + /// The value of a `VALUE_CONSTANT` node. + /// @throws InvalidInputException When the node is not a constant. + auto GetConstantValue() const -> Value; + /// The column a `BOUND_COLUMN_REF` node points at. The index counts the columns of the operator the predicate is + /// evaluated against; resolve it through whatever handed out the expression, e.g. + /// `TableFunction::FilterPushdownInput::GetColumnIndex`. + /// @throws InvalidInputException When the node is not a column reference. + auto GetColumnIndex() const -> idx_t; + /// The name of the scalar function a function node calls: `BOUND_FUNCTION`, the comparisons, `COMPARE_BETWEEN` + /// and `OPERATOR_CAST`. A comparison's name is its operator, e.g. `<`; `BETWEEN` and casts carry internal names, + /// so dispatch on the type for those. + /// @throws InvalidInputException When the node is not a function call. + auto GetFunctionName() const -> std::string; + /// The qualified name of the scalar function a function node calls: the name of `GetFunctionName`, qualified with + /// the catalog and schema the function was resolved in where known. + /// @throws InvalidInputException When the node is not a function call. + auto GetFunctionQualifiedName() const -> QualifiedName; + /// Whether an `OPERATOR_CAST` node is a regular `CAST` or a `TRY_CAST`. + /// @throws InvalidInputException When the node is not a cast. + auto GetCastMode() const -> CastMode; + +private: + explicit Expression(void *impl); +}; + +//---------------------------------------------------------------------------------------------------------------------- +// Table Function +//---------------------------------------------------------------------------------------------------------------------- + +/// A user-defined table function, built up with the setters and made live with `Connection::Register` or +/// `Extension::Register`. Create one through a `Factory` of the database it will be registered in, describe it (name, +/// signature, callbacks), then register it with `Connection::Register` or `Extension::Register`. The function object +/// may be destroyed after registration; the registered function lives on in the catalog. +/// +/// A table function produces a table rather than a value: the bind callback declares the columns it returns, and the +/// exec callback is then invoked repeatedly to fill batches of rows until it produces an empty one. Between them, the +/// optional init callbacks set up the state the scan runs on: one global state shared by every thread, and one local +/// state per thread. +/// +/// The callbacks receive their state through the input objects: `SetUserData` plants data readable from every +/// callback, and the bind callback may plant bind data readable from every later callback. A callback reports failure +/// by throwing; the exception surfaces as the query's error. +class TableFunction final : public detail::Handle { + friend detail::HandleFactory; + friend class Connection; + friend class Extension; + +public: + class BindInput; + class InitGlobalInput; + class InitLocalInput; + class ExecInput; + class ProgressInput; + class FilterPushdownInput; + class PartitionDataInput; + class PartitioningInput; + class ClaimBatchInput; + class GetBindInfoInput; + class StatsInput; + class MetricsInput; + class ToStringInput; + + /// Whether, and how, the scan is partitioned by a set of columns. Reported from the partitioning callback. + enum class PartitionInfo : uint8_t { + /// The scan is not known to be partitioned by the requested columns. + NOT_PARTITIONED = 0, + /// Every batch the scan produces carries exactly one distinct value for the requested columns. + SINGLE_VALUE_PARTITIONS = 1, + /// The batches the scan produces overlap only at their boundaries. + OVERLAPPING_PARTITIONS = 2, + /// The batches the scan produces are disjoint ranges. + DISJOINT_PARTITIONS = 3, + }; + + /// Called once per query while the function call is bound; declares the columns the function returns. Required. + using BindCallback = void (*)(BindInput &input); + /// Called once per scan, before the first `ExecCallback`. Optional. + using InitGlobalCallback = void (*)(InitGlobalInput &input); + /// Called once per scanning thread, before the first `ExecCallback` on it. Optional. + using InitLocalCallback = void (*)(InitLocalInput &input); + /// Called repeatedly to produce the next batch of rows; an empty batch ends the scan. Required. + using ExecCallback = void (*)(ExecInput &input); + /// Called on demand during execution to report how far the scan has advanced. Optional. + using ProgressCallback = void (*)(ProgressInput &input); + /// Called while the query is optimized, possibly more than once, with the predicates the query applies to the + /// function's rows; accepts the ones the function will apply itself. Optional. + using FilterPushdownCallback = void (*)(FilterPushdownInput &input); + /// Called after every batch the exec callback produces, on the thread that produced it, to report the batch's + /// ordering position and, when requested, the value it carries for each partitioning column. Optional. + using PartitionDataCallback = void (*)(PartitionDataInput &input); + /// Called while the query is planned, possibly more than once, with a candidate `GROUP BY` column set; reports + /// whether every batch carries a single value for it. Optional; requires a partition data callback. + using PartitioningCallback = void (*)(PartitioningInput &input); + /// Called on a scanning thread to claim its next batch of work - before the exec callback first runs on the thread, + /// and again whenever the exec callback leaves the output chunk empty. The exec callback then produces the rows of + /// the claimed batch only. The callback may run while the other scanning threads wait for it, so it should only + /// claim the work (e.g. reserve a block number) and leave reading it to the exec callback. Optional; unstable API. + using ClaimBatchCallback = void (*)(ClaimBatchInput &input); + /// Called with the bind data of a bound call when the engine needs to know more about the call than its columns: + /// identifiers of its columns (e.g. field ids), and options - key-value facts about what the call reads. A + /// `MultiFileFunction` wrapping the function asks for every file it binds, maps the columns of the files by the + /// identifiers, and exposes the options as the metadata of the reader of the file. May be called more than once + /// for the same bind data: only report what the bind already determined. Optional; unstable API. + using GetBindInfoCallback = void (*)(GetBindInfoInput &input); + /// Called while the query is optimized, once per declared column the query reads, to narrow that column's + /// statistics. Optional; without it the engine knows nothing about the columns. Unstable API. + using StatsCallback = void (*)(StatsInput &input); + /// Called when the engine collects the metrics of the scan, possibly while the scan is still running, to report + /// what the scan did. Optional; unstable API. + using MetricsCallback = void (*)(MetricsInput &input); + /// Called with the bind data of a bound call when the engine renders a query plan that scans the function, e.g. + /// for `EXPLAIN`, possibly more than once; reports the key-value pairs the plan shows for the scan. They replace + /// the `Function` entry the physical plan shows by default. With profiling enabled (including `EXPLAIN ANALYZE`) + /// it is also called while the query executes, once per worker thread and possibly concurrently, so it must not + /// modify shared state without synchronization, and an error it throws there fails the query. Optional; unstable + /// API. + using ToStringCallback = void (*)(ToStringInput &input); + + /// A column a function can produce next to the columns it declares in bind: a query asks for it by name. + enum class VirtualColumn : uint8_t { + /// `file_row_number`, a BIGINT holding the position of the row within the file it was read from, counting + /// from 0. Produced by a function that reads a single file when it is wrapped in a `MultiFileFunction`. + FILE_ROW_NUMBER = 0, + }; + + /// The first column index that stands for a virtual column rather than a declared one. The index the inputs' + /// `GetColumnIndex` reports for a virtual column is this plus its value in `VirtualColumn`. + static constexpr idx_t VIRTUAL_COLUMN_START = static_cast(1) << 63; + + /// Whether a column index reported by `GetColumnIndex` stands for a virtual column. + static auto IsVirtualColumn(idx_t column_index) -> bool { + return column_index >= VIRTUAL_COLUMN_START; + } + + /// The virtual column a column index reported by `GetColumnIndex` stands for. + /// @throws InvalidInputException When the index stands for a declared column. + static auto GetVirtualColumn(idx_t column_index) -> VirtualColumn; + + TableFunction(TableFunction &&) noexcept = default; + TableFunction &operator=(TableFunction &&) noexcept = default; + + ~TableFunction() override; + + /// Creates an empty TableFunction through `factory`. Register it through a `Connection` or an `Extension` of the + /// factory's database. + static auto Create(Factory &factory) -> TableFunction; + + /// Sets the function's name, as SQL will call it. + auto SetName(const std::string &name) & -> TableFunction &; + /// The documentation of this overload, borrowed for in-place mutation. + auto GetDocs() -> FunctionDocs; + + /// Calls `configure` with the documentation of this overload, borrowed for in-place mutation. + template + auto WithDocs(F &&configure) & -> TableFunction & { + auto docs = GetDocs(); + configure(docs); + return *this; + } + + /// The function's signature, borrowed for in-place mutation. A parameter without a default value becomes a + /// required positional argument, one with a default becomes a named argument the caller may omit. Registration + /// rejects a return type: a table function declares the columns it returns from its bind callback. + auto GetSignature() -> FunctionSignature; + + /// Calls `configure` with the function's signature, borrowed for in-place mutation. See `GetSignature`. + template + auto WithSignature(F &&configure) & -> TableFunction & { + auto sig = GetSignature(); + configure(sig); + return *this; + } + + /// Constructs user data of type `T`, carried by the registered function and freed at engine teardown; read it from + /// any callback via the inputs' `GetUserData`. Consumed by registration: set it again before + /// re-registering. + template + auto SetUserData(ARGS &&...args) & -> TableFunction & { + auto ptr = new T(std::forward(args)...); + SetUserDataInternal(ptr, detail::TypedDelete); + return *this; + } + + auto SetBindCallback(BindCallback callback) & -> TableFunction &; + auto SetInitGlobalCallback(InitGlobalCallback callback) & -> TableFunction &; + auto SetInitLocalCallback(InitLocalCallback callback) & -> TableFunction &; + auto SetExecCallback(ExecCallback callback) & -> TableFunction &; + auto SetProgressCallback(ProgressCallback callback) & -> TableFunction &; + auto SetFilterPushdownCallback(FilterPushdownCallback callback) & -> TableFunction &; + auto SetPartitionDataCallback(PartitionDataCallback callback) & -> TableFunction &; + auto SetPartitioningCallback(PartitioningCallback callback) & -> TableFunction &; + /// Makes the function scan one batch at a time: see `ClaimBatchCallback`. Telling the batches apart lets a caller + /// that scans several of them in parallel put their rows back in order - e.g. a `MultiFileFunction` wrapping this + /// function keeps the rows of a file in order also when several threads scan it. Unstable API. + auto SetClaimBatchCallback(ClaimBatchCallback callback) & -> TableFunction &; + /// Lets the function describe what a bound call reads: see `GetBindInfoCallback`. Unstable API. + auto SetGetBindInfoCallback(GetBindInfoCallback callback) & -> TableFunction &; + /// Lets the function narrow the statistics of the columns it produces: see `StatsCallback`. Unstable API. + auto SetStatsCallback(StatsCallback callback) & -> TableFunction &; + + /// Declares whether the function supports projection pushdown. Defaults to false. With it, the engine asks for + /// only the columns a query uses: the exec callback's output chunk holds one vector per requested column, and + /// the init and exec inputs' `GetColumnIndex` says which declared column each vector stands for. Without it the + /// output chunk always holds every declared column, and the engine drops the unused ones itself. + auto SetProjectionPushdown(bool enable) & -> TableFunction &; + + /// Declares that the function can produce a virtual column, which a query asks for by name. It then takes up a + /// vector of the exec callback's output chunk, whose column index (see `GetColumnIndex`) is + /// `VIRTUAL_COLUMN_START` plus the value of the column. Requires projection pushdown. Unstable API. + auto AddVirtualColumn(VirtualColumn column) & -> TableFunction &; + + /// Lets the function report what the scan did: see `MetricsCallback`. Unstable API. + auto SetMetricsCallback(MetricsCallback callback) & -> TableFunction &; + + /// Lets the function describe a bound call in query plans: see `ToStringCallback`. Unstable API. + auto SetToStringCallback(ToStringCallback callback) & -> TableFunction &; + +private: + explicit TableFunction(void *impl); + //! Moves what the callbacks need into the C handle, right before it is registered. + auto PrepareRegistration() -> void; + + auto SetUserDataInternal(void *data, void (*destructor)(void *)) -> void; + + BindCallback bind_callback = nullptr; + InitGlobalCallback init_global_callback = nullptr; + InitLocalCallback init_local_callback = nullptr; + ExecCallback exec_callback = nullptr; + ProgressCallback progress_callback = nullptr; + FilterPushdownCallback filter_pushdown_callback = nullptr; + PartitionDataCallback partition_data_callback = nullptr; + PartitioningCallback partitioning_callback = nullptr; + ClaimBatchCallback claim_batch_callback = nullptr; + GetBindInfoCallback get_bind_info_callback = nullptr; + StatsCallback stats_callback = nullptr; + MetricsCallback metrics_callback = nullptr; + ToStringCallback to_string_callback = nullptr; + detail::UserData user_data; + +public: + /// What the bind callback works with. Borrowed, valid only for the callback duration. + class BindInput final : public FunctionBindInput { + friend detail::HandleFactory; + + public: + /// Declares one of the columns the function returns. Call it once per column, in order: the exec callback's + /// output chunk carries one vector per declared column, in the same order. At least one column is required. + /// @param name The column's name. + /// @param type The column's type. Must be a fully defined concrete type; ANY is rejected. + auto AddResultColumn(const std::string &name, const LogicalType &type) -> void; + + /// The user data set via `TableFunction::SetUserData`. + /// @throws InvalidInputException When none was set. + template + auto GetUserData() const -> T & { + return *static_cast(GetUserDataInternal()); + } + + /// Hints how many rows the scan will produce, for the optimizer. Producing a different number of rows is not + /// an error. + /// @param cardinality The estimated row count. + /// @param is_exact Whether the estimate is exact, which also makes it an upper bound. + auto SetCardinality(idx_t cardinality, bool is_exact) -> void; + + /// Sets the order guarantee of the rows this call produces. Defaults to `OrderPreservation::INSERTION_ORDER`. + /// With `OrderPreservation::NO_ORDER`, a scan that allows more than one thread runs in parallel into query + /// results, INSERT and COPY without a partition data callback, and the rows arrive in no particular order. + /// @param order The order guarantee of the produced rows. + /// @throws InvalidInputException When order is not a declared enum value. + auto SetOrderPreservation(OrderPreservation order) -> void; + + private: + BindInput(void *args, void *result, void *context) : FunctionBindInput(args, context), result(result) { + } + + void *result; + + void *GetUserDataInternal() const; + }; + + /// What the global init callback works with. Borrowed, valid only for the callback duration. + class InitGlobalInput { + friend detail::HandleFactory; + + public: + /// Constructs global state of type `T`, shared by every thread scanning the function and readable from the + /// local init, exec and progress callbacks. Since every thread sees the same object, the function must + /// synchronize its own access to it. + template + void SetGlobalState(ARGS &&...args) { + auto ptr = new T(std::forward(args)...); + SetGlobalStateInternal(ptr, detail::TypedDelete); + } + + /// The bind data set via `BindInput::SetBindData`. + /// @throws InvalidInputException When none was set. + template + auto GetBindData() const -> const T & { + return *static_cast(GetBindDataInternal()); + } + + /// The user data set via `TableFunction::SetUserData`. + /// @throws InvalidInputException When none was set. + template + auto GetUserData() const -> T & { + return *static_cast(GetUserDataInternal()); + } + + /// Caps how many threads may scan the function in parallel. Defaults to 1, a single-threaded scan. The engine + /// creates at most this many local states, and may use fewer. + /// @param max_threads The maximum thread count. Must be at least 1. + auto SetMaxThreads(idx_t max_threads) -> void; + + /// How many columns the scan produces: with projection pushdown the columns the query uses, which is the number + /// of vectors in the exec callback's output chunk; without it, the columns declared in bind. + auto GetColumnCount() const -> idx_t; + /// Which declared column (in `BindInput::AddResultColumn` order) the scan's column at `index` stands for. The + /// identity without projection pushdown. + /// @throws InvalidInputException When the index is out of bounds. + auto GetColumnIndex(idx_t index) const -> idx_t; + + /// The scan's context. Borrowed, valid only for the callback duration. + auto GetContext() -> Context &; + + private: + InitGlobalInput(void *args, void *context) + : args(args), context(detail::HandleFactory::Make(context)) { + } + + void *args; + Context context; + + void SetGlobalStateInternal(void *data, void (*destructor)(void *)); + void *GetBindDataInternal() const; + void *GetUserDataInternal() const; + }; + + /// What the local init callback works with. Borrowed, valid only for the callback duration. + class InitLocalInput { + friend detail::HandleFactory; + + public: + /// Constructs local state of type `T`, owned by this scanning thread and readable from the exec callback via + /// `ExecInput::GetLocalState`. No other thread observes it, so it needs no synchronization. + template + void SetLocalState(ARGS &&...args) { + auto ptr = new T(std::forward(args)...); + SetLocalStateInternal(ptr, detail::TypedDelete); + } + + /// The bind data set via `BindInput::SetBindData`. + /// @throws InvalidInputException When none was set. + template + auto GetBindData() const -> const T & { + return *static_cast(GetBindDataInternal()); + } + + /// The global state set via `InitGlobalInput::SetGlobalState`, typically to claim this thread's share of the + /// work from it. Shared with every other scanning thread; access must be synchronized. + /// @throws InvalidInputException When none was set. + template + auto GetGlobalState() const -> T & { + return *static_cast(GetGlobalStateInternal()); + } + + /// The user data set via `TableFunction::SetUserData`. + /// @throws InvalidInputException When none was set. + template + auto GetUserData() const -> T & { + return *static_cast(GetUserDataInternal()); + } + + /// How many columns the scan produces; see `InitGlobalInput::GetColumnCount`. + auto GetColumnCount() const -> idx_t; + /// Which declared column the scan's column at `index` stands for; see `InitGlobalInput::GetColumnIndex`. + /// @throws InvalidInputException When the index is out of bounds. + auto GetColumnIndex(idx_t index) const -> idx_t; + + /// The scan's context. Borrowed, valid only for the callback duration. + auto GetContext() -> Context &; + + private: + InitLocalInput(void *args, void *context) : args(args), context(detail::HandleFactory::Make(context)) { + } + + void *args; + Context context; + + void SetLocalStateInternal(void *data, void (*destructor)(void *)); + void *GetBindDataInternal() const; + void *GetGlobalStateInternal() const; + void *GetUserDataInternal() const; + }; + + /// What the exec callback works with. Borrowed, valid only for the callback duration. + class ExecInput { + friend detail::HandleFactory; + + public: + /// The bind data set via `BindInput::SetBindData`. + /// @throws InvalidInputException When none was set. + template + auto GetBindData() const -> const T & { + return *static_cast(GetBindDataInternal()); + } + + /// The global state set via `InitGlobalInput::SetGlobalState`. Shared with every other scanning thread; + /// access must be synchronized. + /// @throws InvalidInputException When none was set. + template + auto GetGlobalState() const -> T & { + return *static_cast(GetGlobalStateInternal()); + } + + /// The local state set via `InitLocalInput::SetLocalState`, private to this thread. + /// @throws InvalidInputException When none was set. + template + auto GetLocalState() const -> T & { + return *static_cast(GetLocalStateInternal()); + } + + /// The user data set via `TableFunction::SetUserData`. + /// @throws InvalidInputException When none was set. + template + auto GetUserData() const -> T & { + return *static_cast(GetUserDataInternal()); + } + + /// The chunk to write the next batch of rows into, with one vector per column declared in bind. It starts out + /// empty on every invocation: write the rows, then give the batch its row count with `Vector::SetSize` on the + /// chunk's first vector, which the engine propagates to the others. Leaving it empty ends the scan. + /// @return A borrowed chunk, valid only for the callback duration. + auto GetOutputChunk() const -> DataChunk; + + /// How many vectors the output chunk holds; see `InitGlobalInput::GetColumnCount`. + auto GetColumnCount() const -> idx_t; + /// Which declared column the output chunk's vector at `index` must be filled with; see + /// `InitGlobalInput::GetColumnIndex`. + /// @throws InvalidInputException When the index is out of bounds. + auto GetColumnIndex(idx_t index) const -> idx_t; + + /// The execution context. Borrowed, valid only for the callback duration. + auto GetContext() -> Context &; + + private: + ExecInput(void *args, void *context) : args(args), context(detail::HandleFactory::Make(context)) { + } + + void *args; + Context context; + + void *GetBindDataInternal() const; + void *GetGlobalStateInternal() const; + void *GetLocalStateInternal() const; + void *GetUserDataInternal() const; + }; + + /// What the progress callback works with. Borrowed, valid only for the callback duration. + class ProgressInput { + friend detail::HandleFactory; + + public: + /// The bind data set via `BindInput::SetBindData`. + /// @throws InvalidInputException When none was set. + template + auto GetBindData() const -> const T & { + return *static_cast(GetBindDataInternal()); + } + + /// The global state set via `InitGlobalInput::SetGlobalState`. This callback runs while the scan is running, + /// so the state must be read in a thread-safe way. + /// @throws InvalidInputException When none was set. + template + auto GetGlobalState() const -> T & { + return *static_cast(GetGlobalStateInternal()); + } + + /// The global state set via `InitGlobalInput::SetGlobalState`, or nullptr when the scan has not been + /// initialized yet -- which is the case when a `MultiFileFunction` asks about a file it has not started on. The + /// state must be read in a thread-safe way. + template + auto TryGetGlobalState() const -> T * { + return static_cast(TryGetGlobalStateInternal()); + } + + /// The user data set via `TableFunction::SetUserData`. + /// @throws InvalidInputException When none was set. + template + auto GetUserData() const -> T & { + return *static_cast(GetUserDataInternal()); + } + + /// Reports how far the scan has advanced, as a fraction between 0.0 and 1.0; values outside that range are + /// clamped. A callback that returns without calling this reports no progress. + /// @param progress The fraction of the scan that is complete. + auto SetProgress(double progress) -> void; + + /// The execution context. Borrowed, valid only for the callback duration. + auto GetContext() -> Context &; + + private: + ProgressInput(void *args, void *context) : args(args), context(detail::HandleFactory::Make(context)) { + } + + void *args; + Context context; + + void *GetBindDataInternal() const; + void *GetGlobalStateInternal() const; + void *TryGetGlobalStateInternal() const; + void *GetUserDataInternal() const; + }; + + /// What the filter pushdown callback works with. Borrowed, valid only for the callback duration. + /// + /// The callback runs while the query is optimized, after bind and before any init callback, with the predicates + /// the query applies to the function's rows. Accepting one with `Accept` is a promise: the engine stops + /// applying it, so the scan must produce only rows that satisfy it. Predicates left unaccepted are applied by + /// the engine as usual, so a callback that recognizes nothing can simply return. The optimizer may run the + /// callback more than once for the same query, each time with the predicates not yet accepted, and never with + /// none. + /// + /// A function that also has projection pushdown is offered the predicates that apply to a single column of it + /// once more when a scan starts, just before the global init callback. That is how the callback of a function + /// wrapped in a `MultiFileFunction` sees them, since the optimizer only offers them to the wrapper; the bind data + /// is then the one of the file being scanned. The engine applies these predicates to the rows the function + /// produces itself, so the function may use them to skip what the query can never use (e.g. the parts of a file + /// whose statistics rule them out), and accepting one has no effect. Unstable API. + class FilterPushdownInput { + friend detail::HandleFactory; + + public: + /// The bind data set via `BindInput::SetBindData`, mutable: the same object the init and exec callbacks later + /// receive, so an accepted predicate can be recorded in it for the scan to apply. + /// @throws InvalidInputException When none was set. + template + auto GetBindData() const -> T & { + return *static_cast(GetBindDataInternal()); + } + + /// The user data set via `TableFunction::SetUserData`. + /// @throws InvalidInputException When none was set. + template + auto GetUserData() const -> T & { + return *static_cast(GetUserDataInternal()); + } + + /// How many predicates are offered. They are combined with `AND`. + auto GetFilterCount() const -> idx_t; + /// A predicate: a bound expression evaluating to `BOOLEAN`. Resolve the column references it contains via + /// `GetColumnIndex`. + /// @return A borrowed expression, valid only for the callback duration. + /// @throws InvalidInputException When the index is out of bounds. + auto GetFilter(idx_t index) const -> Expression; + /// Accepts the predicate at `index`: the function will apply it itself. + /// @throws InvalidInputException When the index is out of bounds. + auto Accept(idx_t index) -> void; + /// How many columns the predicates can refer to: the columns the query reads from the function, which is what + /// `Expression::GetColumnIndex` indexes. + auto GetColumnCount() const -> idx_t; + /// Resolves the index a column reference node reports to the declared column (in `BindInput::AddResultColumn` + /// order) it refers to, or to the index of a virtual column (see `IsVirtualColumn`). + /// @throws InvalidInputException When the index is out of bounds. + auto GetColumnIndex(idx_t index) const -> idx_t; + + /// The query's context. Borrowed, valid only for the callback duration. + auto GetContext() -> Context &; + + private: + FilterPushdownInput(void *args, void *context) + : args(args), context(detail::HandleFactory::Make(context)) { + } + + void *args; + Context context; + + void *GetBindDataInternal() const; + void *GetUserDataInternal() const; + }; + + /// What the partition data callback works with. Borrowed, valid only for the callback duration. + /// + /// The callback runs after every batch the exec callback produces, on the thread that produced it. A batch index + /// must be reported on every call with `SetBatchIndex`, whether or not `RequiresBatchIndex` is true. When + /// `RequiresPartitionColumns` is true, `SetPartitionValue` must be called once for every index below + /// `GetPartitionColumnCount`. The engine reads the partition values only when the batch index changes: within one + /// thread the index must not decrease, and the values may only change together with it. + class PartitionDataInput { + friend detail::HandleFactory; + + public: + /// The bind data set via `BindInput::SetBindData`. + /// @throws InvalidInputException When none was set. + template + auto GetBindData() const -> const T & { + return *static_cast(GetBindDataInternal()); + } + + /// The global state set via `InitGlobalInput::SetGlobalState`. Shared with every other scanning thread; + /// access must be synchronized. + /// @throws InvalidInputException When none was set. + template + auto GetGlobalState() const -> T & { + return *static_cast(GetGlobalStateInternal()); + } + + /// The local state set via `InitLocalInput::SetLocalState`, private to this thread. + /// @throws InvalidInputException When none was set. + template + auto GetLocalState() const -> T & { + return *static_cast(GetLocalStateInternal()); + } + + /// The user data set via `TableFunction::SetUserData`. + /// @throws InvalidInputException When none was set. + template + auto GetUserData() const -> T & { + return *static_cast(GetUserDataInternal()); + } + + /// Whether a downstream operator uses the batch index to restore the scan's order. + auto RequiresBatchIndex() const -> bool; + /// Whether a downstream operator needs the batch's value for each partitioning column. + auto RequiresPartitionColumns() const -> bool; + /// How many partitioning columns are requested; zero unless `RequiresPartitionColumns` is true. + auto GetPartitionColumnCount() const -> idx_t; + /// Which declared column (in `BindInput::AddResultColumn` order) the partitioning column at `index` stands for. + /// @throws InvalidInputException When the index is out of bounds. + auto GetPartitionColumnIndex(idx_t index) const -> idx_t; + + /// Reports the batch's ordering position. Required on every call. Must not decrease across calls on the same + /// thread, and must change whenever the reported partition values change. + /// @throws InvalidInputException When the value is out of range. + auto SetBatchIndex(idx_t batch_index) -> void; + /// Reports the single value every row of the batch carries for the partitioning column at `index`. The value + /// is copied and must be of the declared column's type. + /// @throws InvalidInputException When the index is out of bounds or the type does not match. + auto SetPartitionValue(idx_t index, const Value &value) -> void; + + /// The execution context. Borrowed, valid only for the callback duration. + auto GetContext() -> Context &; + + private: + PartitionDataInput(void *args, void *context) + : args(args), context(detail::HandleFactory::Make(context)) { + } + + void *args; + Context context; + + void *GetBindDataInternal() const; + void *GetGlobalStateInternal() const; + void *GetLocalStateInternal() const; + void *GetUserDataInternal() const; + }; + + /// What the partitioning callback works with. Borrowed, valid only for the callback duration. + /// + /// The callback runs on the planning thread, only while the optimizer considers a partitioned aggregate over the + /// scan, and may run more than once for one query. It must answer deterministically for a given column set. Only + /// `PartitionInfo::SINGLE_VALUE_PARTITIONS` unlocks the optimization; a callback that returns without calling + /// `SetPartitionInfo` reports `PartitionInfo::NOT_PARTITIONED`. + class PartitioningInput { + friend detail::HandleFactory; + + public: + /// The bind data set via `BindInput::SetBindData`. + /// @throws InvalidInputException When none was set. + template + auto GetBindData() const -> const T & { + return *static_cast(GetBindDataInternal()); + } + + /// The user data set via `TableFunction::SetUserData`. + /// @throws InvalidInputException When none was set. + template + auto GetUserData() const -> T & { + return *static_cast(GetUserDataInternal()); + } + + /// How many columns the candidate `GROUP BY` set holds. + auto GetPartitionColumnCount() const -> idx_t; + /// Which declared column (in `BindInput::AddResultColumn` order) the candidate column at `index` stands for. + /// @throws InvalidInputException When the index is out of bounds. + auto GetPartitionColumnIndex(idx_t index) const -> idx_t; + + /// Reports whether, and how, the scan is partitioned by the candidate column set. + /// @throws InvalidInputException When the value is not one of the enum's declared values. + auto SetPartitionInfo(PartitionInfo partition_info) -> void; + + /// The query's context. Borrowed, valid only for the callback duration. + auto GetContext() -> Context &; + + private: + PartitioningInput(void *args, void *context) + : args(args), context(detail::HandleFactory::Make(context)) { + } + + void *args; + Context context; + + void *GetBindDataInternal() const; + void *GetUserDataInternal() const; + }; + + /// What the claim batch callback works with. Borrowed, valid only for the callback duration. Unstable API. + /// + /// The callback claims the next batch of work for the thread's local state - typically from the global state, + /// which is shared with the other scanning threads - and reports whether it claimed one with `SetClaimed`. A + /// callback that returns without claiming a batch ends the scan for the thread. + class ClaimBatchInput { + friend detail::HandleFactory; + + public: + /// The bind data set via `BindInput::SetBindData`. + /// @throws InvalidInputException When none was set. + template + auto GetBindData() const -> const T & { + return *static_cast(GetBindDataInternal()); + } + + /// The global state set via `InitGlobalInput::SetGlobalState`. Shared with every other scanning thread; + /// access must be synchronized. + /// @throws InvalidInputException When none was set. + template + auto GetGlobalState() const -> T & { + return *static_cast(GetGlobalStateInternal()); + } + + /// The local state set via `InitLocalInput::SetLocalState`, of the thread claiming a batch. + /// @throws InvalidInputException When none was set. + template + auto GetLocalState() const -> T & { + return *static_cast(GetLocalStateInternal()); + } + + /// The user data set via `TableFunction::SetUserData`. + /// @throws InvalidInputException When none was set. + template + auto GetUserData() const -> T & { + return *static_cast(GetUserDataInternal()); + } + + /// Reports whether a batch was claimed. + auto SetClaimed(bool claimed) -> void; + + /// The execution context. Borrowed, valid only for the callback duration. + auto GetContext() -> Context &; + + private: + ClaimBatchInput(void *args, void *context) + : args(args), context(detail::HandleFactory::Make(context)) { + } + + void *args; + Context context; + + void *GetBindDataInternal() const; + void *GetGlobalStateInternal() const; + void *GetLocalStateInternal() const; + void *GetUserDataInternal() const; + }; + + /// What the get bind info callback works with. Borrowed, valid only for the callback duration. Unstable API. + class GetBindInfoInput { + friend detail::HandleFactory; + + public: + /// The bind data set via `BindInput::SetBindData` for the bound call being described. + /// @throws InvalidInputException When none was set. + template + auto GetBindData() const -> const T & { + return *static_cast(GetBindDataInternal()); + } + + /// The user data set via `TableFunction::SetUserData`. + /// @throws InvalidInputException When none was set. + template + auto GetUserData() const -> T & { + return *static_cast(GetUserDataInternal()); + } + + /// Attaches an identifier to a result column of the bound call: an INTEGER field id, or a VARCHAR name, by + /// which a `MultiFileFunction` maps the columns of every file rather than by name. + /// @param column_index The column, in `BindInput::AddResultColumn` order. + /// @throws InvalidInputException When the column was not declared, or the identifier is not an INTEGER or + /// VARCHAR. + auto SetColumnIdentifier(idx_t column_index, const Value &identifier) -> void; + + /// Attaches an identifier to a field nested inside a result column, addressed by a path of child indexes: a + /// STRUCT field by its index, the elements of a LIST or ARRAY by 0, the keys of a MAP by 0 and its values by + /// 1, and a UNION member by its index. See `SetColumnIdentifier`. + /// @throws InvalidInputException When the column was not declared, or the path does not address a nested + /// field of it. + auto SetColumnIdentifier(idx_t column_index, const std::vector &child_path, const Value &identifier) + -> void; + + /// Sets an option describing the bound call: a key-value fact about what the call reads. A `MultiFileFunction` + /// exposes the options as the metadata of the reader of the file. Setting a key again replaces its value. + auto SetOption(const std::string &key, const Value &value) -> void; + + /// The context of the query the bound call is part of. Borrowed, valid only for the callback duration. + auto GetContext() -> Context &; + + private: + GetBindInfoInput(void *args, void *context) + : args(args), context(detail::HandleFactory::Make(context)) { + } + + void *args; + Context context; + + void *GetBindDataInternal() const; + void *GetUserDataInternal() const; + }; + + /// What the stats callback works with. Borrowed, valid only for the callback duration. + /// + /// The column statistics start out unknown, with every kind of value possible, and describe every value the scan + /// produces for the column. A callback that leaves them unchanged tells the engine nothing. + class StatsInput { + friend detail::HandleFactory; + + public: + /// The bind data set via `BindInput::SetBindData`. + /// @throws InvalidInputException When none was set. + template + auto GetBindData() const -> const T & { + return *static_cast(GetBindDataInternal()); + } + + /// The user data set via `TableFunction::SetUserData`. + /// @throws InvalidInputException When none was set. + template + auto GetUserData() const -> T & { + return *static_cast(GetUserDataInternal()); + } + + /// Which declared column (in `BindInput::AddResultColumn` order) the statistics describe. + auto GetColumnIndex() const -> idx_t; + + /// The statistics of the column, for the callback to narrow. + auto GetResultStats() const -> Stats; + + /// The query's context. Borrowed, valid only for the callback duration. + auto GetContext() -> Context &; + + private: + StatsInput(void *args, void *context) : args(args), context(detail::HandleFactory::Make(context)) { + } + + void *args; + Context context; + + void *GetBindDataInternal() const; + void *GetUserDataInternal() const; + }; + + /// What the metrics callback works with. Borrowed, valid only for the callback duration. Unstable API. + /// + /// The callback runs when the engine collects the metrics of the scan, which can be while the scan is still + /// running, and possibly more than once: it adds up what it is told. + class MetricsInput { + friend detail::HandleFactory; + + public: + /// The bind data set via `BindInput::SetBindData`. + /// @throws InvalidInputException When none was set. + template + auto GetBindData() const -> const T & { + return *static_cast(GetBindDataInternal()); + } + + /// The user data set via `TableFunction::SetUserData`. + /// @throws InvalidInputException When none was set. + template + auto GetUserData() const -> T & { + return *static_cast(GetUserDataInternal()); + } + + /// The global state set via `InitGlobalInput::SetGlobalState`, or nullptr when the scan has not been + /// initialized or set none. The scan can be running, so the state must be read in a thread-safe way. + template + auto GetGlobalState() const -> T * { + return static_cast(GetGlobalStateInternal()); + } + + /// Reports an operator metric of the scan by its profiler name, e.g. "operator.row_groups_scanned" or + /// "operator.total_row_groups_to_scan". See `duckdb_v2_table_function_metrics_set` for the accepted names. + /// @param name The name of the metric. + /// @param value The value since the metrics were last collected ("operator.total_row_groups_to_scan": in all). + /// @throws InvalidInputException When the name is not a metric a table function can report. + auto SetMetric(std::string_view name, uint64_t value) -> void; + + /// The query's context. Borrowed, valid only for the callback duration. + auto GetContext() -> Context &; + + private: + MetricsInput(void *args, void *context) : args(args), context(detail::HandleFactory::Make(context)) { + } + + void *args; + Context context; + + void *GetBindDataInternal() const; + void *GetGlobalStateInternal() const; + void *GetUserDataInternal() const; + }; + + /// What the to string callback works with. Borrowed, valid only for the callback duration. Unstable API. + class ToStringInput { + friend detail::HandleFactory; + + public: + /// The bind data set via `BindInput::SetBindData` for the bound call being described. + /// @throws InvalidInputException When none was set. + template + auto GetBindData() const -> const T & { + return *static_cast(GetBindDataInternal()); + } + + /// The user data set via `TableFunction::SetUserData`. + /// @throws InvalidInputException When none was set. + template + auto GetUserData() const -> T & { + return *static_cast(GetUserDataInternal()); + } + + /// Reports a key-value pair the plan shows for the scan. The pairs are shown in the order they were first + /// reported; setting a key again replaces its value. + /// @throws InvalidInputException When the key is empty. + auto Set(std::string_view key, std::string_view value) -> void; + + private: + explicit ToStringInput(void *args) : args(args) { + } + + void *args; + + void *GetBindDataInternal() const; + void *GetUserDataInternal() const; + }; +}; + +//---------------------------------------------------------------------------------------------------------------------- +// Multi-File Function +//---------------------------------------------------------------------------------------------------------------------- + +/// A table function that reads many files, built on top of a registered `TableFunction` that reads a single one. +/// Unstable API. +/// +/// The single-file function takes the file to read as its only positional parameter, of type ANY, and is bound and +/// scanned once for every file that is read. It receives the file as a VARCHAR path, or as a file struct that also +/// carries the options to open the file with: what a file system reported about it while globbing, or the options a +/// caller passed along with it. Open the file with `GetFilePath` and `FileOpenOptions::SetValues` to make use of +/// them. A single-file function that takes a VARCHAR parameter instead only receives the path. The multi-file function +/// adds everything that involves several files: globbing, lists of files, hive partitioning, the `filename` column, +/// `union_by_name` and the like. Every named parameter of the single-file function is also a named parameter of the +/// multi-file function, forwarded as given. +/// +/// The single-file function can describe the file it reads in more detail than its columns with a get bind info +/// callback (`TableFunction::SetGetBindInfoCallback`): the field ids of its columns, which the files of the scan are +/// mapped onto one another by, and options, which become the metadata of the reader of the file. With a claim batch +/// callback, the rows of a file keep their order also when several threads scan it. +class MultiFileFunction final : public detail::Handle { + friend detail::HandleFactory; + friend class Connection; + friend class Extension; + +public: + MultiFileFunction(MultiFileFunction &&) noexcept = default; + MultiFileFunction &operator=(MultiFileFunction &&) noexcept = default; + + ~MultiFileFunction() override; + + /// Creates an empty MultiFileFunction through `factory`. Register it through a `Connection` or an `Extension` of + /// the factory's database. + static auto Create(Factory &factory) -> MultiFileFunction; + + /// Sets the function's name, as SQL will call it. + auto SetName(const std::string &name) & -> MultiFileFunction &; + + /// Sets the name of the registered table function that reads a single file. + auto SetSingleFileFunction(const std::string &name) & -> MultiFileFunction &; + + /// Sets how the files are referred to in messages, e.g. "Avro". Defaults to the name of the function. + auto SetReaderType(const std::string &reader_type) & -> MultiFileFunction &; + + /// Sets the extension of the files the function reads, without a leading dot, e.g. "avro". A path naming a + /// directory then reads the files with that extension inside it. + auto SetFileExtension(const std::string &extension) & -> MultiFileFunction &; + +private: + explicit MultiFileFunction(void *impl); + //! Moves what the callbacks need into the C handle, right before it is registered. + auto PrepareRegistration() -> void; +}; + +//---------------------------------------------------------------------------------------------------------------------- +// Custom Type +//---------------------------------------------------------------------------------------------------------------------- + +/// A user-defined type, built up with the setters and made live with `Connection::Register` or `Extension::Register`. +/// Create one through a `Factory` of the database it will be registered in, give it a name and a base type, then +/// register it with `Connection::Register` or `Extension::Register`. The type object may be destroyed after +/// registration; the registered type lives on in the catalog. +/// +/// A custom type borrows its base type's internal representation, so the execution engine needs no special handling +/// for it, while staying logically distinct from the base type so it can carry its own casts. Values of it are +/// produced and read with the base type's vector accessors; to hand one back out under the custom name, alias the +/// base type with `LogicalType::WithAlias`. +class CustomType final : public detail::Handle { + friend detail::HandleFactory; + friend class Connection; + friend class Extension; + +public: + CustomType(CustomType &&) noexcept = default; + CustomType &operator=(CustomType &&) noexcept = default; + + ~CustomType() override; + + /// Creates an empty CustomType through `factory`. Register it through a `Connection` or an `Extension` of the + /// factory's database. + static auto Create(Factory &factory) -> CustomType; + + /// Sets the type's name, as SQL will refer to it, and as every logical type instance of it carries as its alias. + auto SetName(const std::string &name) & -> CustomType &; + + /// Sets the type whose representation this type borrows. Must be a fully defined concrete type. + auto SetBaseType(const LogicalType &type) & -> CustomType &; + +private: + explicit CustomType(void *impl); + //! Moves what the callbacks need into the C handle, right before it is registered. + auto PrepareRegistration() -> void; +}; + +//---------------------------------------------------------------------------------------------------------------------- +// Copy Function +//---------------------------------------------------------------------------------------------------------------------- + +/// A user-defined file format for `COPY`, built up with the setters and made live with `Connection::Register` or +/// `Extension::Register`. Create one through a `Factory` of the database it will be registered in, describe it (name, +/// callbacks), then register it with `Connection::Register` or `Extension::Register`. The function object may be +/// destroyed after registration; the registered function lives on in the catalog and is reached from SQL with `COPY ... +/// TO 'path' (FORMAT name)` and `COPY table FROM 'path' (FORMAT name)`. +/// +/// The two directions are configured separately and a function may implement either or both. The `COPY ... TO` side +/// gathers the rows being written into batches and drives its callbacks in this order: bind (once, during planning), +/// batch size (once, during planning, unless the statement sets `BATCH_SIZE`), init (once per output file), batch +/// (once per batch, possibly on several threads at once), flush (once per prepared batch, never concurrently for the +/// same file) and finalize (once per output file). The `COPY ... FROM` side reads like a table function whose columns +/// are fixed by the target table: bind (once, during planning), init global (once per statement), init local (once +/// per thread), exec (repeatedly, until it produces an empty batch), plus an optional progress hook. +/// +/// The callbacks receive their state through the input objects: `SetUserData` plants data readable from every +/// callback of either side, and each side's bind callback may plant bind data readable from that side's later +/// callbacks. A callback reports failure by throwing; the exception surfaces as the query's error. +class CopyFunction final : public detail::Handle { + friend detail::HandleFactory; + friend class Connection; + friend class Extension; + +public: + class CopyToBindInput; + class CopyToBatchSizeInput; + class CopyToInitInput; + class CopyToBatchInput; + class CopyToFlushInput; + class CopyToFinalizeInput; + class CopyToStatisticsInput; + class CopyFromBindInput; + class CopyFromInitGlobalInput; + class CopyFromInitLocalInput; + class CopyFromExecInput; + class CopyFromProgressInput; + + /// Called once per `COPY ... TO` statement while it is bound. Optional. + using CopyToBindCallback = void (*)(CopyToBindInput &input); + /// Called after bind, for a `COPY ... TO` statement that sets no `BATCH_SIZE` itself, to report how many rows a + /// batch should carry; must call `SetTarget`. Optional: without it, a batch is cut for every chunk of rows sunk, + /// i.e. a vector at a time. + using CopyToBatchSizeCallback = void (*)(CopyToBatchSizeInput &input); + /// Called once per output file before its first batch is prepared. Optional. + using CopyToInitCallback = void (*)(CopyToInitInput &input); + /// Called to prepare a batch of rows for writing; may run on several threads at once. Required for the side. + using CopyToBatchCallback = void (*)(CopyToBatchInput &input); + /// Called to write a prepared batch to the output; never concurrently for the same file. Required for the side. + using CopyToFlushCallback = void (*)(CopyToFlushInput &input); + /// Called once per output file after its last batch has been flushed. Optional. + using CopyToFinalizeCallback = void (*)(CopyToFinalizeInput &input); + /// Called once per output file after its finalize callback, to report the statistics of the written file when the + /// statement asks for them (`RETURN_STATS`). Optional: without it, `RETURN_STATS` is rejected. Unstable API. + using CopyToStatisticsCallback = void (*)(CopyToStatisticsInput &input); + + /// Called once per `COPY ... FROM` statement while it is bound. Required for the side. + using CopyFromBindCallback = void (*)(CopyFromBindInput &input); + /// Called once per statement at the start of execution. Optional. + using CopyFromInitGlobalCallback = void (*)(CopyFromInitGlobalInput &input); + /// Called once per thread reading the file. Optional. + using CopyFromInitLocalCallback = void (*)(CopyFromInitLocalInput &input); + /// Called to fill the next batch of rows; leaving the chunk empty ends the read. Required for the side. + using CopyFromExecCallback = void (*)(CopyFromExecInput &input); + /// Called on demand during execution to report progress. Optional. + using CopyFromProgressCallback = void (*)(CopyFromProgressInput &input); + + CopyFunction(CopyFunction &&) noexcept = default; + CopyFunction &operator=(CopyFunction &&) noexcept = default; + + ~CopyFunction() override; + + /// Creates an empty CopyFunction through `factory`. Register it through a `Connection` or an `Extension` of the + /// factory's database. + static auto Create(Factory &factory) -> CopyFunction; + + /// Sets the function's name: the format SQL selects it with, as in `COPY ... TO 'path' (FORMAT name)`. + auto SetName(const std::string &name) & -> CopyFunction &; + + /// Sets the extension of the files the function writes, without the leading dot, e.g. `parquet`. DuckDB uses it + /// when it names files itself, as for `PARTITION_BY`; without it such names end in a bare dot. + /// @throws InvalidInputException When the extension starts with a dot. + auto SetFileExtension(const std::string &extension) & -> CopyFunction &; + + /// Constructs user data of type `T`, carried by the registered function and freed at engine teardown; read it from + /// any callback via the inputs' `GetUserData`. Consumed by registration: set it again before + /// re-registering. + template + auto SetUserData(ARGS &&...args) & -> CopyFunction & { + auto ptr = new T(std::forward(args)...); + SetUserDataInternal(ptr, detail::TypedDelete); + return *this; + } + + auto SetCopyToBindCallback(CopyToBindCallback callback) & -> CopyFunction &; + auto SetCopyToBatchSizeCallback(CopyToBatchSizeCallback callback) & -> CopyFunction &; + auto SetCopyToInitCallback(CopyToInitCallback callback) & -> CopyFunction &; + auto SetCopyToBatchCallback(CopyToBatchCallback callback) & -> CopyFunction &; + auto SetCopyToFlushCallback(CopyToFlushCallback callback) & -> CopyFunction &; + auto SetCopyToFinalizeCallback(CopyToFinalizeCallback callback) & -> CopyFunction &; + auto SetCopyToStatisticsCallback(CopyToStatisticsCallback callback) & -> CopyFunction &; + + auto SetCopyFromBindCallback(CopyFromBindCallback callback) & -> CopyFunction &; + auto SetCopyFromInitGlobalCallback(CopyFromInitGlobalCallback callback) & -> CopyFunction &; + auto SetCopyFromInitLocalCallback(CopyFromInitLocalCallback callback) & -> CopyFunction &; + auto SetCopyFromExecCallback(CopyFromExecCallback callback) & -> CopyFunction &; + auto SetCopyFromProgressCallback(CopyFromProgressCallback callback) & -> CopyFunction &; + +private: + explicit CopyFunction(void *impl); + //! Moves what the callbacks need into the C handle, right before it is registered. + auto PrepareRegistration() -> void; + + auto SetUserDataInternal(void *data, void (*destructor)(void *)) -> void; + + CopyToBindCallback copy_to_bind_callback = nullptr; + CopyToBatchSizeCallback copy_to_batch_size_callback = nullptr; + CopyToInitCallback copy_to_init_callback = nullptr; + CopyToBatchCallback copy_to_batch_callback = nullptr; + CopyToFlushCallback copy_to_flush_callback = nullptr; + CopyToFinalizeCallback copy_to_finalize_callback = nullptr; + CopyToStatisticsCallback copy_to_statistics_callback = nullptr; + CopyFromBindCallback copy_from_bind_callback = nullptr; + CopyFromInitGlobalCallback copy_from_init_global_callback = nullptr; + CopyFromInitLocalCallback copy_from_init_local_callback = nullptr; + CopyFromExecCallback copy_from_exec_callback = nullptr; + CopyFromProgressCallback copy_from_progress_callback = nullptr; + detail::UserData user_data; + +public: + /// What the `COPY ... TO` bind callback works with. Borrowed, valid only for the callback duration. + class CopyToBindInput { + friend detail::HandleFactory; + + public: + /// Constructs bind data of type `T`, owned by the bound statement and readable from every later `COPY ... TO` + /// callback via `GetBindData`. The engine compares bind data when it compares statements: by `operator==` + /// when `T` has one, by identity otherwise. + template + void SetBindData(ARGS &&...args) { + auto ptr = new T(std::forward(args)...); + SetBindDataInternal(ptr, detail::SelectEquals(), detail::TypedDelete); + } + + /// The user data set via `CopyFunction::SetUserData`. + /// @throws InvalidInputException When none was set. + template + auto GetUserData() const -> T & { + return *static_cast(GetUserDataInternal()); + } + + /// The path the statement writes to, as written. The path of each file actually written is only known to the + /// init callback. + auto GetFilePath() const -> std::string; + + /// How many columns are being written: the columns of every batch's rows. Valid indices for `GetColumnName` + /// and `GetColumnType` are [0, GetColumnCount()). + auto GetColumnCount() const -> idx_t; + + /// One column's name. + /// @param index Column index in [0, GetColumnCount()). + /// @throws InvalidInputException When the index is out of range. + auto GetColumnName(idx_t index) const -> std::string; + + /// One column's type. + /// @param index Column index in [0, GetColumnCount()). + /// @throws InvalidInputException When the index is out of range. + auto GetColumnType(idx_t index) const -> LogicalType; + + /// How many options the statement passed to the function, ordered by name. The engine's own options (e.g. + /// `USE_TMP_FILE`) are not included. Valid indices for the option accessors are [0, GetOptionCount()). + auto GetOptionCount() const -> idx_t; + + /// One option's name, a SQL identifier matched case-insensitively. + /// @param index Option index in [0, GetOptionCount()). + /// @throws InvalidInputException When the index is out of range. + auto GetOptionName(idx_t index) const -> std::string; + + /// One option's value: the value itself for `DELIM ','`, the BOOLEAN true for a bare option such as `HEADER`, + /// and a tuple (an unnamed STRUCT with one field per element, in order) for a parenthesized list. + /// @param index Option index in [0, GetOptionCount()). + /// @throws InvalidInputException When the index is out of range. + auto GetOptionValue(idx_t index) const -> Value; + + /// The binding context. Borrowed, valid only for the callback duration. + auto GetContext() -> Context &; + + private: + CopyToBindInput(void *args, void *context) + : args(args), context(detail::HandleFactory::Make(context)) { + } + + void *args; + Context context; + + void SetBindDataInternal(void *data, bool (*equals)(void *a, void *b), void (*destructor)(void *)); + void *GetUserDataInternal() const; + }; + + /// What the `COPY ... TO` batch size callback works with. Borrowed, valid only for the callback duration. + class CopyToBatchSizeInput { + friend detail::HandleFactory; + + public: + /// The bind data set via `CopyToBindInput::SetBindData`. + /// @throws InvalidInputException When none was set. + template + auto GetBindData() const -> const T & { + return *static_cast(GetBindDataInternal()); + } + + /// The user data set via `CopyFunction::SetUserData`. + /// @throws InvalidInputException When none was set. + template + auto GetUserData() const -> T & { + return *static_cast(GetUserDataInternal()); + } + + /// Reports how many rows a batch should carry, as the target the engine cuts batches at. Not calling this + /// leaves the engine's default in effect. A batch may still be smaller (the last one of a file, or when + /// `BATCH_SIZE_BYTES` cuts it first). + /// @param rows The number of rows a batch should carry; must be greater than 0. + auto SetTarget(idx_t rows) -> void; + + /// The binding context. Borrowed, valid only for the callback duration. + auto GetContext() -> Context &; + + private: + CopyToBatchSizeInput(void *args, void *context) + : args(args), context(detail::HandleFactory::Make(context)) { + } + + void *args; + Context context; + + void *GetBindDataInternal() const; + void *GetUserDataInternal() const; + }; + + /// What the `COPY ... TO` init callback works with. Borrowed, valid only for the callback duration. + class CopyToInitInput { + friend detail::HandleFactory; + + public: + /// Constructs init data of type `T`, owned by the file being written and readable from the batch, flush and + /// finalize callbacks of that file via `GetInitData`. Batches may be prepared on several threads at once, so + /// the batch callback must synchronize its own access to it. + template + void SetInitData(ARGS &&...args) { + auto ptr = new T(std::forward(args)...); + SetInitDataInternal(ptr, detail::TypedDelete); + } + + /// The bind data set via `CopyToBindInput::SetBindData`. + /// @throws InvalidInputException When none was set. + template + auto GetBindData() const -> const T & { + return *static_cast(GetBindDataInternal()); + } + + /// The user data set via `CopyFunction::SetUserData`. + /// @throws InvalidInputException When none was set. + template + auto GetUserData() const -> T & { + return *static_cast(GetUserDataInternal()); + } + + /// The path of the file being written, after the engine's own rewrites (e.g. a temporary name while the file + /// is being written, or a per-partition path). + auto GetFilePath() const -> std::string; + + /// The query context. Borrowed, valid only for the callback duration. + auto GetContext() -> Context &; + + private: + CopyToInitInput(void *args, void *context) + : args(args), context(detail::HandleFactory::Make(context)) { + } + + void *args; + Context context; + + void SetInitDataInternal(void *data, void (*destructor)(void *)); + void *GetBindDataInternal() const; + void *GetUserDataInternal() const; + }; + + /// What the `COPY ... TO` batch callback works with. Borrowed, valid only for the callback duration. + class CopyToBatchInput { + friend detail::HandleFactory; + + public: + /// Constructs batch data of type `T`: the prepared form of the batch, handed to the flush callback via + /// `CopyToFlushInput::GetBatchData` and freed once the batch has been flushed. + template + void SetBatchData(ARGS &&...args) { + auto ptr = new T(std::forward(args)...); + SetBatchDataInternal(ptr, detail::TypedDelete); + } + + /// The bind data set via `CopyToBindInput::SetBindData`. + /// @throws InvalidInputException When none was set. + template + auto GetBindData() const -> const T & { + return *static_cast(GetBindDataInternal()); + } + + /// The init data set via `CopyToInitInput::SetInitData` for the file this batch belongs to. + /// @throws InvalidInputException When none was set. + template + auto GetInitData() const -> T & { + return *static_cast(GetInitDataInternal()); + } + + /// The user data set via `CopyFunction::SetUserData`. + /// @throws InvalidInputException When none was set. + template + auto GetUserData() const -> T & { + return *static_cast(GetUserDataInternal()); + } + + /// Takes ownership of the rows of the batch: one column per column reported by + /// `CopyToBindInput::GetColumnCount`, in the same order. The batch can only be taken once; a batch that is + /// never taken is released when the callback returns. It may be kept beyond the callback, e.g. moved into the + /// batch data via `SetBatchData`. + /// @throws InvalidInputException When the batch was already taken. + auto TakeBatch() -> ColumnDataCollection; + + /// The query context. Borrowed, valid only for the callback duration. + auto GetContext() -> Context &; + + private: + CopyToBatchInput(void *args, void *context) + : args(args), context(detail::HandleFactory::Make(context)) { + } + + void *args; + Context context; + + void SetBatchDataInternal(void *data, void (*destructor)(void *)); + void *GetBindDataInternal() const; + void *GetInitDataInternal() const; + void *GetUserDataInternal() const; + }; + + /// What the `COPY ... TO` flush callback works with. Borrowed, valid only for the callback duration. + class CopyToFlushInput { + friend detail::HandleFactory; + + public: + /// The bind data set via `CopyToBindInput::SetBindData`. + /// @throws InvalidInputException When none was set. + template + auto GetBindData() const -> const T & { + return *static_cast(GetBindDataInternal()); + } + + /// The init data set via `CopyToInitInput::SetInitData` for the file this batch belongs to. + /// @throws InvalidInputException When none was set. + template + auto GetInitData() const -> T & { + return *static_cast(GetInitDataInternal()); + } + + /// The batch data set via `CopyToBatchInput::SetBatchData` for the batch being flushed. + /// @throws InvalidInputException When none was set. + template + auto GetBatchData() const -> T & { + return *static_cast(GetBatchDataInternal()); + } + + /// The user data set via `CopyFunction::SetUserData`. + /// @throws InvalidInputException When none was set. + template + auto GetUserData() const -> T & { + return *static_cast(GetUserDataInternal()); + } + + /// The query context. Borrowed, valid only for the callback duration. + auto GetContext() -> Context &; + + private: + CopyToFlushInput(void *args, void *context) + : args(args), context(detail::HandleFactory::Make(context)) { + } + + void *args; + Context context; + + void *GetBindDataInternal() const; + void *GetInitDataInternal() const; + void *GetBatchDataInternal() const; + void *GetUserDataInternal() const; + }; + + /// What the `COPY ... TO` finalize callback works with. Borrowed, valid only for the callback duration. + class CopyToFinalizeInput { + friend detail::HandleFactory; + + public: + /// The bind data set via `CopyToBindInput::SetBindData`. + /// @throws InvalidInputException When none was set. + template + auto GetBindData() const -> const T & { + return *static_cast(GetBindDataInternal()); + } + + /// The init data set via `CopyToInitInput::SetInitData` for the file being finalized. + /// @throws InvalidInputException When none was set. + template + auto GetInitData() const -> T & { + return *static_cast(GetInitDataInternal()); + } + + /// The user data set via `CopyFunction::SetUserData`. + /// @throws InvalidInputException When none was set. + template + auto GetUserData() const -> T & { + return *static_cast(GetUserDataInternal()); + } + + /// The query context. Borrowed, valid only for the callback duration. + auto GetContext() -> Context &; + + private: + CopyToFinalizeInput(void *args, void *context) + : args(args), context(detail::HandleFactory::Make(context)) { + } + + void *args; + Context context; + + void *GetBindDataInternal() const; + void *GetInitDataInternal() const; + void *GetUserDataInternal() const; + }; + + /// What the `COPY ... TO` statistics callback works with. Borrowed, valid only for the callback duration. Unstable + /// API. + class CopyToStatisticsInput { + friend detail::HandleFactory; + + public: + /// The bind data set via `CopyToBindInput::SetBindData`. + /// @throws InvalidInputException When none was set. + template + auto GetBindData() const -> const T & { + return *static_cast(GetBindDataInternal()); + } + + /// The init data set via `CopyToInitInput::SetInitData` for the file being reported. + /// @throws InvalidInputException When none was set. + template + auto GetInitData() const -> T & { + return *static_cast(GetInitDataInternal()); + } + + /// The user data set via `CopyFunction::SetUserData`. + /// @throws InvalidInputException When none was set. + template + auto GetUserData() const -> T & { + return *static_cast(GetUserDataInternal()); + } + + /// Reports how many rows were written to the file. Reported as 0 when not set. + auto SetRowCount(idx_t row_count) -> void; + + /// Reports the size of the file in bytes. Reported as 0 when not set. + auto SetFileSize(idx_t file_size_bytes) -> void; + + /// The query context. Borrowed, valid only for the callback duration. + auto GetContext() -> Context &; + + private: + CopyToStatisticsInput(void *args, void *context) + : args(args), context(detail::HandleFactory::Make(context)) { + } + + void *args; + Context context; + + void *GetBindDataInternal() const; + void *GetInitDataInternal() const; + void *GetUserDataInternal() const; + }; + + /// What the `COPY ... FROM` bind callback works with. Borrowed, valid only for the callback duration. + class CopyFromBindInput { + friend detail::HandleFactory; + + public: + /// Constructs bind data of type `T`, owned by the bound statement and readable from every later + /// `COPY ... FROM` callback via `GetBindData`. The engine compares bind data when it compares statements: + /// by `operator==` when `T` has one, by identity otherwise. + template + void SetBindData(ARGS &&...args) { + auto ptr = new T(std::forward(args)...); + SetBindDataInternal(ptr, detail::SelectEquals(), detail::TypedDelete); + } + + /// The user data set via `CopyFunction::SetUserData`. + /// @throws InvalidInputException When none was set. + template + auto GetUserData() const -> T & { + return *static_cast(GetUserDataInternal()); + } + + /// The path the statement reads from, as written. The engine expands no globs and checks nothing; both are + /// left to the function. + auto GetFilePath() const -> std::string; + + /// How many columns the target table expects: the columns every batch the exec callback produces must carry, + /// in this order. Valid indices for `GetColumnName` and `GetColumnType` are [0, GetColumnCount()). + auto GetColumnCount() const -> idx_t; + + /// One column's name. + /// @param index Column index in [0, GetColumnCount()). + /// @throws InvalidInputException When the index is out of range. + auto GetColumnName(idx_t index) const -> std::string; + + /// One column's type. + /// @param index Column index in [0, GetColumnCount()). + /// @throws InvalidInputException When the index is out of range. + auto GetColumnType(idx_t index) const -> LogicalType; + + /// How many options the statement passed to the function, ordered by name; every option other than `FORMAT`. + /// Valid indices for the option accessors are [0, GetOptionCount()). + auto GetOptionCount() const -> idx_t; + + /// One option's name, a SQL identifier matched case-insensitively. + /// @param index Option index in [0, GetOptionCount()). + /// @throws InvalidInputException When the index is out of range. + auto GetOptionName(idx_t index) const -> std::string; + + /// One option's value: the value itself for `DELIM ','`, the BOOLEAN true for a bare option such as `HEADER`, + /// and a tuple (an unnamed STRUCT with one field per element, in order) for a parenthesized list. + /// @param index Option index in [0, GetOptionCount()). + /// @throws InvalidInputException When the index is out of range. + auto GetOptionValue(idx_t index) const -> Value; + + /// Hints how many rows the read will produce, for the optimizer. Producing a different number of rows is not + /// an error. + /// @param cardinality The estimated row count. + /// @param is_exact Whether the estimate is exact, which also makes it an upper bound. + auto SetCardinality(idx_t cardinality, bool is_exact) -> void; + + /// The binding context. Borrowed, valid only for the callback duration. + auto GetContext() -> Context &; + + private: + CopyFromBindInput(void *args, void *context) + : args(args), context(detail::HandleFactory::Make(context)) { + } + + void *args; + Context context; + + void SetBindDataInternal(void *data, bool (*equals)(void *a, void *b), void (*destructor)(void *)); + void *GetUserDataInternal() const; + }; + + /// What the `COPY ... FROM` global init callback works with. Borrowed, valid only for the callback duration. + class CopyFromInitGlobalInput { + friend detail::HandleFactory; + + public: + /// Constructs global state of type `T`, shared by every thread reading the file and readable from the local + /// init, exec and progress callbacks. Since every thread sees the same object, the function must synchronize + /// its own access to it. + template + void SetGlobalState(ARGS &&...args) { + auto ptr = new T(std::forward(args)...); + SetGlobalStateInternal(ptr, detail::TypedDelete); + } + + /// The bind data set via `CopyFromBindInput::SetBindData`. + /// @throws InvalidInputException When none was set. + template + auto GetBindData() const -> const T & { + return *static_cast(GetBindDataInternal()); + } + + /// The user data set via `CopyFunction::SetUserData`. + /// @throws InvalidInputException When none was set. + template + auto GetUserData() const -> T & { + return *static_cast(GetUserDataInternal()); + } + + /// Caps how many threads may read the file in parallel. Defaults to 1, a single-threaded read. The engine + /// creates at most this many local states, and may use fewer. + /// @param max_threads The maximum thread count. Must be at least 1. + auto SetMaxThreads(idx_t max_threads) -> void; + + /// The query context. Borrowed, valid only for the callback duration. + auto GetContext() -> Context &; + + private: + CopyFromInitGlobalInput(void *args, void *context) + : args(args), context(detail::HandleFactory::Make(context)) { + } + + void *args; + Context context; + + void SetGlobalStateInternal(void *data, void (*destructor)(void *)); + void *GetBindDataInternal() const; + void *GetUserDataInternal() const; + }; + + /// What the `COPY ... FROM` local init callback works with. Borrowed, valid only for the callback duration. + class CopyFromInitLocalInput { + friend detail::HandleFactory; + + public: + /// Constructs local state of type `T`, owned by this reading thread and readable from the exec callback via + /// `CopyFromExecInput::GetLocalState`. No other thread observes it, so it needs no synchronization. + template + void SetLocalState(ARGS &&...args) { + auto ptr = new T(std::forward(args)...); + SetLocalStateInternal(ptr, detail::TypedDelete); + } + + /// The bind data set via `CopyFromBindInput::SetBindData`. + /// @throws InvalidInputException When none was set. + template + auto GetBindData() const -> const T & { + return *static_cast(GetBindDataInternal()); + } + + /// The global state set via `CopyFromInitGlobalInput::SetGlobalState`, typically to claim this thread's share + /// of the work from it. Shared with every other reading thread; access must be synchronized. + /// @throws InvalidInputException When none was set. + template + auto GetGlobalState() const -> T & { + return *static_cast(GetGlobalStateInternal()); + } + + /// The user data set via `CopyFunction::SetUserData`. + /// @throws InvalidInputException When none was set. + template + auto GetUserData() const -> T & { + return *static_cast(GetUserDataInternal()); + } + + /// The query context. Borrowed, valid only for the callback duration. + auto GetContext() -> Context &; + + private: + CopyFromInitLocalInput(void *args, void *context) + : args(args), context(detail::HandleFactory::Make(context)) { + } + + void *args; + Context context; + + void SetLocalStateInternal(void *data, void (*destructor)(void *)); + void *GetBindDataInternal() const; + void *GetGlobalStateInternal() const; + void *GetUserDataInternal() const; + }; + + /// What the `COPY ... FROM` exec callback works with. Borrowed, valid only for the callback duration. + class CopyFromExecInput { + friend detail::HandleFactory; + + public: + /// The bind data set via `CopyFromBindInput::SetBindData`. + /// @throws InvalidInputException When none was set. + template + auto GetBindData() const -> const T & { + return *static_cast(GetBindDataInternal()); + } + + /// The global state set via `CopyFromInitGlobalInput::SetGlobalState`. Shared with every other reading thread; + /// access must be synchronized. + /// @throws InvalidInputException When none was set. + template + auto GetGlobalState() const -> T & { + return *static_cast(GetGlobalStateInternal()); + } + + /// The local state set via `CopyFromInitLocalInput::SetLocalState`, private to this thread. + /// @throws InvalidInputException When none was set. + template + auto GetLocalState() const -> T & { + return *static_cast(GetLocalStateInternal()); + } + + /// The user data set via `CopyFunction::SetUserData`. + /// @throws InvalidInputException When none was set. + template + auto GetUserData() const -> T & { + return *static_cast(GetUserDataInternal()); + } + + /// The chunk to write the next batch of rows into, with one vector per column reported by + /// `CopyFromBindInput::GetColumnCount`. It starts out empty on every invocation: write the rows, then give the + /// batch its row count with `Vector::SetSize` on the chunk's first vector, which the engine propagates to the + /// others. Leaving it empty ends the read. + /// @return A borrowed chunk, valid only for the callback duration. + auto GetOutputChunk() const -> DataChunk; + + /// The execution context. Borrowed, valid only for the callback duration. + auto GetContext() -> Context &; + + private: + CopyFromExecInput(void *args, void *context) + : args(args), context(detail::HandleFactory::Make(context)) { + } + + void *args; + Context context; + + void *GetBindDataInternal() const; + void *GetGlobalStateInternal() const; + void *GetLocalStateInternal() const; + void *GetUserDataInternal() const; + }; + + /// What the `COPY ... FROM` progress callback works with. Borrowed, valid only for the callback duration. + class CopyFromProgressInput { + friend detail::HandleFactory; + + public: + /// The bind data set via `CopyFromBindInput::SetBindData`. + /// @throws InvalidInputException When none was set. + template + auto GetBindData() const -> const T & { + return *static_cast(GetBindDataInternal()); + } + + /// The global state set via `CopyFromInitGlobalInput::SetGlobalState`. This callback runs while the read is + /// running, so the state must be read in a thread-safe way. + /// @throws InvalidInputException When none was set. + template + auto GetGlobalState() const -> T & { + return *static_cast(GetGlobalStateInternal()); + } + + /// The user data set via `CopyFunction::SetUserData`. + /// @throws InvalidInputException When none was set. + template + auto GetUserData() const -> T & { + return *static_cast(GetUserDataInternal()); + } + + /// Reports how far the read has advanced, as a fraction between 0.0 and 1.0; values outside that range are + /// clamped. A callback that returns without calling this reports no progress. + /// @param progress The fraction of the read that is complete. + auto SetProgress(double progress) -> void; + + /// The execution context. Borrowed, valid only for the callback duration. + auto GetContext() -> Context &; + + private: + CopyFromProgressInput(void *args, void *context) + : args(args), context(detail::HandleFactory::Make(context)) { + } + + void *args; + Context context; + + void *GetBindDataInternal() const; + void *GetGlobalStateInternal() const; + void *GetUserDataInternal() const; + }; +}; + +//---------------------------------------------------------------------------------------------------------------------- +// Cast Function +//---------------------------------------------------------------------------------------------------------------------- + +/// The mode a cast runs in, which decides what a conversion failure means. +enum class CastMode : uint8_t { + /// A regular cast. Throwing from the exec callback aborts the query. + NORMAL = 0, + /// A "try" cast (SQL TRY_CAST). The rows the callback could not convert should be left NULL in the output; an + /// exception thrown anyway is swallowed and those rows stay NULL. + TRY = 1, +}; + +/// A user-defined cast between two types, built up with the setters and made live with `Connection::Register` or +/// `Extension::Register`. Create one through a `Factory` of the database it will be registered in, describe it (source +/// type, target type, exec callback), then register it with `Connection::Register` or `Extension::Register`. The +/// function object may be destroyed after registration; the registered cast lives on. +/// +/// A cast is keyed by its (source, target) type pair rather than by a name, and is reached from SQL through CAST and +/// TRY_CAST -- and, when it declares a non-negative implicit cast cost, through the binder converting argument types +/// on its own. The exec callback converts a whole batch at a time; whether a per-row failure aborts the query or +/// becomes a NULL follows from `ExecInput::GetMode`. +class CastFunction final : public detail::Handle { + friend detail::HandleFactory; + friend class Connection; + friend class Extension; + +public: + class ExecInput; + + /// Called for every batch of values; must fill the output vector. Required. + using ExecCallback = void (*)(ExecInput &input); + + CastFunction(CastFunction &&) noexcept = default; + CastFunction &operator=(CastFunction &&) noexcept = default; + + ~CastFunction() override; + + /// Creates an empty CastFunction through `factory`. Register it through a `Connection` or an `Extension` of the + /// factory's database. + static auto Create(Factory &factory) -> CastFunction; + + /// Sets the type the cast converts from. Must be a fully defined concrete type. + auto SetSourceType(const LogicalType &type) & -> CastFunction &; + + /// Sets the type the cast converts to. Must be a fully defined concrete type. + auto SetTargetType(const LogicalType &type) & -> CastFunction &; + + /// Sets what it costs to apply this cast implicitly. The binder uses the cost to choose between candidate + /// implicit casts: a lower non-negative cost makes this cast more likely to be picked. Built-in widening casts + /// sit in the [0, 20] range. A negative cost -- the default -- keeps the cast out of implicit conversion + /// entirely, so it is reached only through an explicit CAST or TRY_CAST. + /// @param cost The cost, or a negative value to disable implicit casting. + auto SetImplicitCastCost(int64_t cost) & -> CastFunction &; + + /// Constructs user data of type `T`, carried by the registered cast and freed at engine teardown; read it from the + /// exec callback via `ExecInput::GetUserData`. Consumed by registration: set it again before + /// re-registering. + template + auto SetUserData(ARGS &&...args) & -> CastFunction & { + auto ptr = new T(std::forward(args)...); + SetUserDataInternal(ptr, detail::TypedDelete); + return *this; + } + + auto SetExecCallback(ExecCallback callback) & -> CastFunction &; + +private: + explicit CastFunction(void *impl); + //! Moves what the callbacks need into the C handle, right before it is registered. + auto PrepareRegistration() -> void; + + auto SetUserDataInternal(void *data, void (*destructor)(void *)) -> void; + + ExecCallback exec_callback = nullptr; + detail::UserData user_data; + +public: + /// What the exec callback works with. Borrowed, valid only for the callback duration. + class ExecInput { + friend detail::HandleFactory; + + public: + /// The user data set via `CastFunction::SetUserData`. + /// @throws InvalidInputException When none was set. + template + auto GetUserData() const -> T & { + return *static_cast(GetUserDataInternal()); + } + + /// How many rows this execution must convert: the callback writes exactly this many entries to the output + /// vector. May be less than a full vector; a constant input is converted as a single row and the engine + /// expands the result. + auto GetRowCount() const -> idx_t; + + /// The input vector holding the values to convert. + auto GetInput() const -> Vector; + + /// The output vector to fill. + auto GetOutput() const -> Vector; + + /// The mode this cast runs in. In `CastMode::TRY` a failed row should be left NULL rather than reported by + /// throwing. + auto GetMode() const -> CastMode; + + /// The execution context. Borrowed, valid only for the callback duration. + auto GetContext() -> Context &; + + private: + ExecInput(void *args, void *context) : args(args), context(detail::HandleFactory::Make(context)) { + } + + void *args; + Context context; + + void *GetUserDataInternal() const; + }; +}; + +//---------------------------------------------------------------------------------------------------------------------- +// Pragma Function +//---------------------------------------------------------------------------------------------------------------------- + +/// A user-defined pragma, called with the `PRAGMA` statement. Create one through a `Factory` of the database it will be +/// registered in, describe it (name, signature, callback), then register it with `Connection::Register` or +/// `Extension::Register`. The function object may be destroyed after registration; the registered pragma lives on in +/// the catalog. +/// +/// A pragma takes constant arguments and is one of two kinds, decided by the callback it is given: a query pragma +/// returns SQL that runs in place of the `PRAGMA` statement, and an exec pragma runs for its side effects and produces +/// no rows. Set exactly one of the two callbacks. A pragma without parameters is called as `PRAGMA name`, one with +/// parameters as `PRAGMA name(...)`. A callback reports failure by throwing; the exception surfaces as the statement's +/// error. +class PragmaFunction final : public detail::Handle { + friend detail::HandleFactory; + friend class Connection; + friend class Extension; + +public: + class QueryInput; + class ExecInput; + + /// Called before the `PRAGMA` statement is bound; returns the SQL to run in its place, which may hold several + /// statements. + using QueryCallback = std::string (*)(QueryInput &input); + /// Called when the `PRAGMA` statement executes. + using ExecCallback = void (*)(ExecInput &input); + + PragmaFunction(PragmaFunction &&) noexcept = default; + PragmaFunction &operator=(PragmaFunction &&) noexcept = default; + + ~PragmaFunction() override; + + /// Creates an empty PragmaFunction through `factory`. Register it through a `Connection` or an `Extension` of the + /// factory's database. + static auto Create(Factory &factory) -> PragmaFunction; + + /// Sets the pragma's name, as the `PRAGMA` statement calls it. + auto SetName(const std::string &name) & -> PragmaFunction &; + /// The documentation of the pragma, borrowed for in-place mutation. + auto GetDocs() -> FunctionDocs; + + /// Calls `configure` with the documentation of the pragma, borrowed for in-place mutation. + template + auto WithDocs(F &&configure) & -> PragmaFunction & { + auto docs = GetDocs(); + configure(docs); + return *this; + } + + /// The pragma's signature, borrowed for in-place mutation. A pragma produces no value, so registration rejects a + /// signature with a return type. + auto GetSignature() -> FunctionSignature; + + /// Calls `configure` with the pragma's signature, borrowed for in-place mutation. + template + auto WithSignature(F &&configure) & -> PragmaFunction & { + auto sig = GetSignature(); + configure(sig); + return *this; + } + + /// Constructs user data of type `T`, carried by the registered pragma and freed at engine teardown; read it from + /// the callback via the input's `GetUserData`. Consumed by registration: set it again before re-registering. + template + auto SetUserData(ARGS &&...args) & -> PragmaFunction & { + auto ptr = new T(std::forward(args)...); + SetUserDataInternal(ptr, detail::TypedDelete); + return *this; + } + + /// Makes this a query pragma. Registration fails when an exec callback is set as well. + auto SetQueryCallback(QueryCallback callback) & -> PragmaFunction &; + /// Makes this an exec pragma. Registration fails when a query callback is set as well. + auto SetExecCallback(ExecCallback callback) & -> PragmaFunction &; + +private: + explicit PragmaFunction(void *impl); + //! Moves what the callbacks need into the C handle, right before it is registered. + auto PrepareRegistration() -> void; + + auto SetUserDataInternal(void *data, void (*destructor)(void *)) -> void; + + QueryCallback query_callback = nullptr; + ExecCallback exec_callback = nullptr; + detail::UserData user_data; + +public: + /// What the query callback works with: the arguments of the `PRAGMA` statement. Borrowed, valid only for the + /// callback duration. + class QueryInput final : public FunctionBindInput { + friend detail::HandleFactory; + + public: + /// The user data set via `PragmaFunction::SetUserData`. + /// @throws InvalidInputException When none was set. + template + auto GetUserData() const -> T & { + return *static_cast(GetUserDataInternal()); + } + + private: + QueryInput(void *args, void *context) : FunctionBindInput(args, context) { + } + + /// Pragmas have no bind data + using FunctionBindInput::SetBindData; + + void *GetUserDataInternal() const; + }; + + /// What the exec callback works with: the arguments of the `PRAGMA` statement. Borrowed, valid only for the + /// callback duration. + class ExecInput final : public FunctionBindInput { + friend detail::HandleFactory; + + public: + /// The user data set via `PragmaFunction::SetUserData`. + /// @throws InvalidInputException When none was set. + template + auto GetUserData() const -> T & { + return *static_cast(GetUserDataInternal()); + } + + private: + ExecInput(void *args, void *context) : FunctionBindInput(args, context) { + } + + /// Pragmas have no bind data + using FunctionBindInput::SetBindData; + + void *GetUserDataInternal() const; + }; +}; + +//---------------------------------------------------------------------------------------------------------------------- +// Macro Function +//---------------------------------------------------------------------------------------------------------------------- + +/// A function defined in SQL: a call is replaced with the body, an expression for a scalar macro and a query for a +/// table macro, which refers to the parameters by name. Create one through a `Factory` of the database it will be +/// registered in, describe it (name, signature, body), then register it with `Extension::Register`; outside an +/// extension, define a macro with SQL `CREATE MACRO` instead. The function object may be destroyed after +/// registration; the registered macro lives on in the catalog. +/// +/// A macro's parameters can always be passed by position or by name, so the signature may only hold standard +/// parameters, optionally with a default value. A parameter of type ANY is untyped. The result follows from the body, +/// so the signature cannot set a return type. +class MacroFunction final : public detail::Handle { + friend detail::HandleFactory; + friend class Extension; + +public: + MacroFunction(MacroFunction &&) noexcept = default; + MacroFunction &operator=(MacroFunction &&) noexcept = default; + + ~MacroFunction() override; + + /// Creates an empty scalar macro through `factory`: its body is an expression, and it is called like a scalar + /// function. Register it through an `Extension` of the factory's database. + static auto CreateScalar(Factory &factory) -> MacroFunction; + /// Creates an empty table macro through `factory`: its body is a SELECT query, and it is called like a table + /// function. Register it through an `Extension` of the factory's database. + static auto CreateTable(Factory &factory) -> MacroFunction; + + /// Sets the macro's name, as SQL calls it. + auto SetName(const std::string &name) & -> MacroFunction &; + /// Sets the body, as SQL text: an expression for a scalar macro, a SELECT query for a table macro. Parsed at + /// registration; names in it are resolved when the macro is called. + auto SetBody(std::string_view body) & -> MacroFunction &; + /// The documentation of the macro, borrowed for in-place mutation. + auto GetDocs() -> FunctionDocs; + + /// Calls `configure` with the documentation of the macro, borrowed for in-place mutation. + template + auto WithDocs(F &&configure) & -> MacroFunction & { + auto docs = GetDocs(); + configure(docs); + return *this; + } + + /// The macro's signature, borrowed for in-place mutation. + auto GetSignature() -> FunctionSignature; + + /// Calls `configure` with the macro's signature, borrowed for in-place mutation. + template + auto WithSignature(F &&configure) & -> MacroFunction & { + auto sig = GetSignature(); + configure(sig); + return *this; + } + +private: + explicit MacroFunction(void *impl); +}; + +//---------------------------------------------------------------------------------------------------------------------- +// Log Sink +//---------------------------------------------------------------------------------------------------------------------- + +/// The scope a log entry was written in, which decides which of its ids are present. +enum class LogScope : uint8_t { + /// Written for the database as a whole, carrying no connection, transaction or query id. + DATABASE = 10, + /// Written by a connection, carrying its connection id and, inside one, the transaction and query ids. + CONNECTION = 20, + /// Written by a thread executing a query, carrying the thread id next to the connection's ids. + THREAD = 30, +}; + +/// Code of your own that receives DuckDB's log entries. Create one through a `Factory` of the database it will be +/// registered in, give it a name and a write callback, then register it with `Instance::Register` or +/// `Extension::Register`, which makes it available to the logging configuration under its name; once the +/// configuration directs entries to it (currently with `SET logging_sink = ''`), the write callback receives +/// them. A log sink only receives entries: they cannot be read back through `duckdb_logs`. +/// +/// Which entries a sink receives, and when and on which thread its callbacks run, are up to DuckDB: the callbacks must +/// return quickly, must be safe to run concurrently and on any thread, and must not log or change the logging +/// configuration. An exception a callback throws drops the entry; it never fails the operation that logged. +class LogSink final : public detail::Handle { + friend detail::HandleFactory; + friend class Instance; + friend class Extension; + +public: + class Entry; + class FlushInput; + + /// Called for every entry to store. Required. + using WriteCallback = void (*)(Entry &entry); + /// Called when DuckDB flushes its log, so entries the sink holds on to can be written out. When is up to DuckDB. + /// Optional. + using FlushCallback = void (*)(FlushInput &input); + + LogSink(LogSink &&) noexcept = default; + LogSink &operator=(LogSink &&) noexcept = default; + + ~LogSink() override; + + /// Creates an empty LogSink through `factory`. Register it through an `Instance` or an `Extension` of the + /// factory's database. + static auto Create(Factory &factory) -> LogSink; + + /// Sets the name the logging configuration refers to the sink by, matched case-insensitively. + auto SetName(const std::string &name) & -> LogSink &; + + /// Constructs user data of type `T`, carried by the registered sink and freed at database teardown; read it + /// from the callbacks via `GetUserData`. Consumed by registration. + template + auto SetUserData(ARGS &&...args) & -> LogSink & { + auto ptr = new T(std::forward(args)...); + SetUserDataInternal(ptr, detail::TypedDelete); + return *this; + } + + auto SetWriteCallback(WriteCallback callback) & -> LogSink &; + auto SetFlushCallback(FlushCallback callback) & -> LogSink &; + +private: + explicit LogSink(void *impl); + //! Moves what the callbacks need into the C handle, right before it is registered. + auto PrepareRegistration() -> void; + + auto SetUserDataInternal(void *data, void (*destructor)(void *)) -> void; + + WriteCallback write_callback = nullptr; + FlushCallback flush_callback = nullptr; + detail::UserData user_data; + +public: + /// One log entry, borrowed for the duration of the write callback. + class Entry { + friend detail::HandleFactory; + + public: + /// The user data set via `LogSink::SetUserData`. + /// @throws InvalidInputException When none was set. + template + auto GetUserData() const -> T & { + return *static_cast(GetUserDataInternal()); + } + + /// When the entry was written. + auto GetTimestamp() const -> timestamp_tz_t; + /// The severity of the entry. + auto GetLevel() const -> LogLevel; + /// The log type the entry was written under, e.g. `QueryLog`. Valid only for the callback duration. + auto GetLogType() const -> std::string_view; + /// The message. Valid only for the callback duration. + auto GetLogMessage() const -> std::string_view; + /// The scope the entry was written in, which decides which of the ids below are present. + auto GetScope() const -> LogScope; + /// The ids `duckdb_logs` reports for the entry, each absent when the entry's scope has none. The thread id + /// identifies the thread that logged, which need not be the thread the write callback runs on. + auto GetConnectionId() const -> std::optional; + auto GetTransactionId() const -> std::optional; + auto GetQueryId() const -> std::optional; + auto GetThreadId() const -> std::optional; + + private: + Entry(void *info, void *user_data, int64_t timestamp, LogLevel level, LogScope scope, std::string_view type, + std::string_view message) + : info(info), user_data(user_data), timestamp(timestamp), level(level), scope(scope), type(type), + message(message) { + } + + void *info; + void *user_data; + int64_t timestamp; + LogLevel level; + LogScope scope; + std::string_view type; + std::string_view message; + + void *GetUserDataInternal() const; + }; + + /// What the flush callback works with. Borrowed, valid only for the callback duration. + class FlushInput { + friend detail::HandleFactory; + + public: + /// The user data set via `LogSink::SetUserData`. + /// @throws InvalidInputException When none was set. + template + auto GetUserData() const -> T & { + return *static_cast(GetUserDataInternal()); + } + + private: + explicit FlushInput(void *user_data) : user_data(user_data) { + } + + void *user_data; + + void *GetUserDataInternal() const; + }; +}; + +//---------------------------------------------------------------------------------------------------------------------- +// File System +//---------------------------------------------------------------------------------------------------------------------- + +/// How `FileSystem::OpenFile` opens a file. Not a bitmask -- apply these one at a time with +/// `FileOpenOptions::SetFlag`, or pass several as a braced list to `FileSystem::OpenFile`. +enum class FileFlags : uint8_t { + /// Not a flag. The zero value, so an uninitialized variable does not name a behaviour; applying it is an error. + INVALID = 0, + /// Open the file with "read" capabilities. + READ = 1, + /// Open the file with "write" capabilities. + WRITE = 2, + /// Create the file if it does not exist, and open it as it is if it does. + /// The FILE_ prefix matches the engine's flag names and keeps CREATE clear of the `` macro. + FILE_CREATE = 3, + /// Create the file if it does not exist, and truncate it to empty if it does. To fail instead of truncating, + /// combine `FILE_CREATE` with `EXCLUSIVE_CREATE`. + FILE_CREATE_NEW = 4, + /// Open the file in "append" mode. + APPEND = 5, + /// Fail if the file already exists. A modifier on `FILE_CREATE`, and meaningless without it. + EXCLUSIVE_CREATE = 6, + /// The file will be read and written at explicit offsets from several threads at once. Pass it whenever `ReadAt` + /// or `WriteAt` are used concurrently, so that a file system which would otherwise assume sequential access does + /// not. + PARALLEL_ACCESS = 7, + /// Read the file through DuckDB's external file cache, which keeps the bytes that were read in memory for later + /// reads - also by later queries. Whether a local file is cached is decided by the `cache_local_files` setting. + /// Only for reading. Unstable API. + EXTERNAL_FILE_CACHE = 8, +}; + +/// An open file, obtained from `FileSystem::OpenFile`. Closes on destruction. +/// Only usable while the `FileSystem` it came from is still valid. +class FileHandle final : public detail::Handle { + friend detail::HandleFactory; + +public: + FileHandle(FileHandle &&) noexcept = default; + FileHandle &operator=(FileHandle &&) noexcept = default; + + ~FileHandle() override; + + /// Flushes buffered writes to persistent storage, which is what makes them durable across a crash. Closing or + /// destroying the handle flushes as well. + void Sync(); + + /// Closes the file, releasing its operating-system resources. The handle stays valid but can no longer be used + /// to read, write or seek. + void Close(); + + /// Moves the read/write position to an absolute byte offset from the start of the file. Seeking past the end is + /// allowed; reading from there yields nothing. + void Seek(idx_t position); + + /// The current read/write position, as a byte offset from the start of the file. + auto Tell() const -> idx_t; + + /// The total size of the file in bytes. + auto Size() const -> idx_t; + + /// Reads up to `size` bytes from the current position, advancing it by however many were read. + /// @return How many bytes were read. Fewer than asked for is normal at the end of the file, and zero means + /// there is nothing left; neither is an error. + auto Read(void *buffer, idx_t size) -> idx_t; + + /// Writes up to `size` bytes at the current position, advancing it by however many were written. + /// @return How many bytes were written. + auto Write(const void *buffer, idx_t size) -> idx_t; + + /// Reads exactly `size` bytes from `location`, leaving the file's position alone. Unlike `Read`, a short read is + /// an error rather than a result, so there is no count to return. Safe to call from several threads at once when + /// the file was opened with `FileFlags::PARALLEL_ACCESS`. + /// @throws Exception When the file ends before `size` bytes have been read. + void ReadAt(void *buffer, idx_t size, idx_t location); + + /// Writes exactly `size` bytes at `location`, leaving the file's position alone and extending the file when the + /// offset is past its end. Safe to call from several threads at once when the file was opened with + /// `FileFlags::PARALLEL_ACCESS` and the threads write disjoint ranges. + void WriteAt(const void *buffer, idx_t size, idx_t location); + +private: + explicit FileHandle(void *impl); +}; + +/// How a file is opened: the flags, plus any values the file system handling the path cares about. +/// Created from the `FileSystem` it will be used with, and reusable across any number of opens. +class FileOpenOptions final : public detail::Handle { + friend detail::HandleFactory; + +public: + FileOpenOptions(FileOpenOptions &&) noexcept = default; + FileOpenOptions &operator=(FileOpenOptions &&) noexcept = default; + + ~FileOpenOptions() override; + + /// Creates an empty set of options for `fs`. Flags must be set before they can open anything. + static auto Create(const FileSystem &fs) -> FileOpenOptions; + + /// Applies one flag. Additive, and applying the same flag twice is harmless; at least one flag is required + /// before the options can open anything. There is no way to take a flag back -- build a fresh set instead. + /// @throws InvalidInputException When the value is `FileFlags::INVALID` or not a flag at all. + auto SetFlag(FileFlags flag) & -> FileOpenOptions &; + + /// Attaches a named value, a hint for whichever file system ends up handling the path. What a name means is that + /// file system's business, and one it does not recognize is ignored. Setting the same name again replaces it. + auto SetValue(std::string_view name, const Value &value) & -> FileOpenOptions &; + + /// Attaches the options a file is specified with, as table functions that read files take it: a STRUCT holding + /// the path of the file in its `filename` field, and an option to open the file with in every other field - e.g. + /// `{'filename': 'f.parquet', 'file_size': 42}`. A field set to NULL is an option that was not specified. A + /// VARCHAR path carries no options, and attaches nothing. See `GetFilePath`. + /// @param file The file, a VARCHAR path or a file struct. + /// @throws InvalidInputException When the file is neither, or a file struct has no VARCHAR `filename` field. + auto SetValues(const Value &file) & -> FileOpenOptions &; + +private: + explicit FileOpenOptions(void *impl); +}; + +/// The path of a file, as table functions that read files take it: a VARCHAR path, or a STRUCT holding the path in +/// its `filename` field and the options to open the file with in its other fields. See `FileOpenOptions::SetValues`. +/// @param file The file, a VARCHAR path or a file struct. +/// @throws InvalidInputException When the file is neither, or a file struct has no VARCHAR `filename` field. +auto GetFilePath(const Value &file) -> std::string; + +/// The file system DuckDB itself reads and writes through, so files open the way the engine would open them -- +/// including through virtual and remote file systems registered by other extensions. +/// Borrowed from a `Context` or `Connection`, and valid only for as long as that is. +class FileSystem final : public detail::Handle { + friend detail::HandleFactory; + +public: + FileSystem(FileSystem &&) noexcept = default; + FileSystem &operator=(FileSystem &&) noexcept = default; + + ~FileSystem() override; + + /// Opens a file with nothing but flags, which is what most opens need. + /// @param path The path to open, routed the way the engine would route it. + /// @param flags How to open it, e.g. `{FileFlags::WRITE, FileFlags::FILE_CREATE}`; at least one is required. + /// @throws Exception When the file cannot be opened. + auto OpenFile(const std::string &path, std::initializer_list flags) const -> FileHandle; + + /// Opens a file with a prepared set of options, for when the file system needs values as well as flags. + /// @throws Exception When the file cannot be opened, or the options carry no flags. + auto OpenFile(const std::string &path, const FileOpenOptions &options) const -> FileHandle; + + /// Creates an empty set of options for this file system, the same as `FileOpenOptions::Create(*this)`. + auto CreateOpenOptions() const -> FileOpenOptions; + + /// Whether a file exists at `path`, routed the way `OpenFile` routes it. A directory is not a file. + auto Exists(const std::string &path) const -> bool; + /// Whether `path` names a remote file, e.g. under `s3://` or `https://`. Decided from the path alone, so it + /// answers even when the extension providing the remote file system is not loaded. + auto IsRemote(const std::string &path) const -> bool; + /// `path` expanded as `OpenFile` expands it: a leading `~` becomes the configured home directory. + auto Expand(const std::string &path) const -> std::string; + + /// The paths of the files matching a glob pattern, e.g. `data/*.csv`, in the order the file system lists them. + /// A pattern without glob characters matches the file it names, if there is one. + auto Glob(const std::string &pattern) const -> std::vector; + /// Moves, or renames, a file. Whether an existing file at `target` is replaced, and whether the move is atomic, is + /// up to the file system; moving between two file systems is not supported. + /// @throws Exception When the file cannot be moved. + auto Move(const std::string &source, const std::string &target) const -> void; + /// Removes the file at `path`, if there is one. + /// @return Whether a file was removed. + /// @throws Exception When the file exists but cannot be removed. + auto Remove(const std::string &path) const -> bool; + +private: + explicit FileSystem(void *impl); +}; + +//---------------------------------------------------------------------------------------------------------------------- +// Qualified Name +//---------------------------------------------------------------------------------------------------------------------- + +/// The ordered path of identifiers that names a database object. +/// The path is the whole representation: partial qualification is expressed by having fewer parts (`{"t"}`, +/// `{"s", "t"}`, `{"c", "s", "t"}`), never by empty placeholders, and the last part is always the object itself. +/// Whether a two-part name means catalog.object or schema.object is decided by resolution, not by the name. +/// +/// Owned, so a name obtained from somewhere transient -- a replacement scan callback, say -- can be kept for as long +/// as you like. +class QualifiedName final : public detail::Handle { + friend detail::HandleFactory; + +public: + QualifiedName(QualifiedName &&) noexcept = default; + QualifiedName &operator=(QualifiedName &&) noexcept = default; + + ~QualifiedName() override; + + /// Parses SQL text into a qualified name: dots separate parts, and a double-quoted part may contain dots and + /// doubled interior quotes. + /// @throws Exception When the text does not parse, or yields no parts or more than three. + static auto Parse(std::string_view text) -> QualifiedName; + + /// Builds a name from its parts, outermost first, so the last one is the object name. + /// @param parts Between one and three non-empty parts. + /// @throws InvalidInputException When there are no parts, more than three, or any is empty. + static auto Create(const std::vector &parts) -> QualifiedName; + + /// How many parts the name has; always at least one. + auto GetPartCount() const -> idx_t; + + /// One part, outermost first. The view is valid until this name is destroyed. + /// @param index Part index in [0, GetPartCount()). + /// @throws Exception When the index is out of range. + auto GetPart(idx_t index) const -> std::string_view; + + /// The object name: the last part. The view is valid until this name is destroyed. + auto GetName() const -> std::string_view; + + /// The name as SQL text, quoting each part only where the identifier requires it, so it parses back to an equal + /// name. + auto Render() const -> std::string; + + /// Whether two names have the same parts, compared case-insensitively the way the engine compares identifiers. + auto Equals(const QualifiedName &other) const -> bool; + + /// A hash consistent with `Equals`. Not stable across processes or versions: for in-process lookup only. + auto Hash() const -> uint64_t; + +private: + explicit QualifiedName(void *impl); +}; + +inline bool operator==(const QualifiedName &lhs, const QualifiedName &rhs) { + return lhs.Equals(rhs); +} +inline bool operator!=(const QualifiedName &lhs, const QualifiedName &rhs) { + return !lhs.Equals(rhs); +} + +//---------------------------------------------------------------------------------------------------------------------- +// Table Description +//---------------------------------------------------------------------------------------------------------------------- + +/// An owned snapshot of one base table, taken by `Connection::DescribeTable`: where the name resolved, the table's +/// columns in declared order (generated columns included), and per-column catalog facts. Later DDL does not update it. +class TableDescription final : public detail::Handle { + friend detail::HandleFactory; + +public: + TableDescription(TableDescription &&) noexcept = default; + TableDescription &operator=(TableDescription &&) noexcept = default; + + ~TableDescription() override; + + /// The fully resolved name: the catalog, schema and table the lookup landed on, with the casing the table was + /// created with. + auto GetQualifiedName() const -> QualifiedName; + + /// How many columns the table has, generated columns included. + auto GetColumnCount() const -> idx_t; + + /// An owned description of one column, independent of this table description. + /// @param index Column index in [0, GetColumnCount()). + /// @throws Exception When the index is out of range. + auto GetColumn(idx_t index) const -> ColumnDescription; + + /// Whether the catalog the table lives in was attached read-only. + auto IsReadOnly() const -> bool; + +private: + explicit TableDescription(void *impl); +}; + +/// An owned snapshot of one column of a described table, from `TableDescription::GetColumn`: its name, type and +/// catalog facts. Independent of the table description it came from. +class ColumnDescription final : public detail::Handle { + friend detail::HandleFactory; + +public: + ColumnDescription(ColumnDescription &&) noexcept = default; + ColumnDescription &operator=(ColumnDescription &&) noexcept = default; + + ~ColumnDescription() override; + + /// The column name, with the casing it was declared with. + /// @return A view borrowed from this description, valid until it is destroyed. + auto GetName() const -> std::string_view; + + /// An owned copy of the column type. + auto GetType() const -> LogicalType; + + /// Whether the column declares a default expression. Generated columns report false. + auto HasDefault() const -> bool; + + /// Whether the column is generated: computed by the engine and not writable. + auto HasGenerated() const -> bool; + +private: + explicit ColumnDescription(void *impl); +}; + +//---------------------------------------------------------------------------------------------------------------------- +// Query Metrics +//---------------------------------------------------------------------------------------------------------------------- + +/// An owned snapshot of the metrics of a query, taken by `Connection::GetQueryMetrics`: a tree whose root describes +/// the query as a whole and whose other nodes describe its operators. Later queries do not update it. Which metrics +/// are present, their names and the shape of the tree may change between versions. Unstable API. +class QueryMetrics final : public detail::Handle { + friend detail::HandleFactory; + +public: + QueryMetrics(QueryMetrics &&) noexcept = default; + QueryMetrics &operator=(QueryMetrics &&) noexcept = default; + + ~QueryMetrics() override; + + /// The node describing the query as a whole. + /// @return A borrowed node, valid for as long as this snapshot is. + auto GetRoot() const -> QueryMetricsNode; + +private: + explicit QueryMetrics(void *impl); +}; + +/// One node of a `QueryMetrics` snapshot, carrying a set of named, numeric metrics. Borrowed, valid for as long as the +/// snapshot is. Unstable API. +class QueryMetricsNode final : public detail::Handle { + friend detail::HandleFactory; + +public: + QueryMetricsNode(QueryMetricsNode &&) noexcept = default; + QueryMetricsNode &operator=(QueryMetricsNode &&) noexcept = default; + + ~QueryMetricsNode() override; + + /// `QUERY` for the root node, the name of the operator, e.g. `TABLE_SCAN`, for the others. + /// @return A view borrowed from the snapshot. + auto GetName() const -> std::string_view; + + /// How many children the node has. + auto GetChildCount() const -> idx_t; + + /// One child of the node. + /// @param index Child index in [0, GetChildCount()). + /// @throws Exception When the index is out of range. + auto GetChild(idx_t index) const -> QueryMetricsNode; + + /// How many metrics the node carries. + auto GetMetricCount() const -> idx_t; + + /// The name of one metric, e.g. `query.total_time`. The order of the metrics is unspecified. + /// @param index Metric index in [0, GetMetricCount()). + /// @return A view borrowed from the snapshot. + /// @throws Exception When the index is out of range. + auto GetMetricName(idx_t index) const -> std::string_view; + + /// The value of one metric, a number such as a UBIGINT count or a DOUBLE duration. + /// @param index Metric index in [0, GetMetricCount()). + /// @throws Exception When the index is out of range. + auto GetMetricValue(idx_t index) const -> Value; + + /// Looks a metric up by its exact name. + /// @return Its value, or nothing when the node does not carry it. + auto GetMetric(std::string_view name) const -> std::optional; + +private: + explicit QueryMetricsNode(void *impl); +}; + +//---------------------------------------------------------------------------------------------------------------------- +// Replacement Scan +//---------------------------------------------------------------------------------------------------------------------- + +/// A user-defined replacement scan, built up with the setters and made live with `Connection::Register` or +/// `Extension::Register`. Create one through a `Factory` of the database it will be registered on, set its callback and +/// user data, then register it with `Connection::Register` or `Extension::Register`. The scan object may be destroyed +/// after registration; the registered scan lives on until its scope ends. +/// +/// The binder consults replacement scans when a table name cannot be resolved in the catalog; this is what makes +/// `SELECT * FROM 'file.parquet'` work. The callback inspects the unresolved name and either claims it, by naming a +/// table function to call, a `ColumnDataCollection` to read or a query to run instead, or declines it by claiming +/// nothing, which lets the next registered scan try. When no scan claims the name, the usual "table does not exist" +/// error is raised. A callback reports failure by throwing; the exception surfaces as the query's error. +/// +/// Scope follows the registration. A scan registered through a `Connection` is visible only to that connection, +/// is released when it closes, and is consulted before every instance-wide scan, including the built-in file scans. A +/// scan registered through an `Instance` or an `Extension` is visible to every connection to that instance +/// and lives until it closes; registering one is not thread-safe against queries binding on other connections, so do it +/// during extension load or before issuing queries. A registered scan cannot be unregistered. +class ReplacementScan final : public detail::Handle { + friend detail::HandleFactory; + friend class Connection; + friend class Extension; + friend class Instance; + +public: + class Input; + + /// Called once per table reference the catalog could not resolve; claims it or declines it. Required. + using Callback = void (*)(Input &input); + + ReplacementScan(ReplacementScan &&) noexcept = default; + ReplacementScan &operator=(ReplacementScan &&) noexcept = default; + + ~ReplacementScan() override; + + /// Creates an empty ReplacementScan through `factory`. Register it through a `Connection` or an `Extension` of the + /// factory's database. + static auto Create(Factory &factory) -> ReplacementScan; + + auto SetCallback(Callback callback) & -> ReplacementScan &; + + /// Constructs user data of type `T`, carried by the registered scan and freed when its scope ends; read it from + /// the callback via `Input::GetUserData`. Consumed by registration. + template + auto SetUserData(ARGS &&...args) & -> ReplacementScan & { + auto ptr = new T(std::forward(args)...); + SetUserDataInternal(ptr, detail::TypedDelete); + return *this; + } + +private: + explicit ReplacementScan(void *impl); + //! Moves what the callbacks need into the C handle, right before it is registered. + auto PrepareRegistration() -> void; + + auto SetUserDataInternal(void *data, void (*destructor)(void *)) -> void; + + Callback callback = nullptr; + detail::UserData user_data; + +public: + /// What the callback works with. Borrowed, valid only for the callback duration, as are the name views it hands + /// out. + class Input { + friend detail::HandleFactory; + + public: + /// The user data set via `ReplacementScan::SetUserData`. + /// @throws InvalidInputException When none was set. + template + auto GetUserData() const -> T & { + return *static_cast(GetUserDataInternal()); + } + + /// The name the catalog could not resolve, as written in the query. An unqualified reference has a single + /// part; for a file-backed one that part is the path. Owned, so it can outlive the callback. + auto GetName() const -> QualifiedName; + + /// Claims the reference by naming a table function to call instead; its arguments are then supplied with + /// `AddArgument` and `AddNamedArgument`. Parts are matched case-insensitively, and a qualified name targets a + /// function in a particular schema or catalog. The name is not resolved here: an unknown function fails + /// later, when the replacement is bound. The three claim forms, `SetFunctionName`, `SetCollection` and + /// `SetSubquery`, are mutually exclusive. + /// @throws InvalidInputException When a different claim form was already used. + auto SetFunctionName(const QualifiedName &name) -> void; + + /// `SetFunctionName` for the common case of an unqualified function. + auto SetFunctionName(std::string_view name) -> void; + + /// Appends a positional argument to the claimed table function. Positional arguments are passed in the order + /// they are added, before any named ones. + /// @throws InvalidInputException Unless `SetFunctionName` was called first. + auto AddArgument(const Value &value) -> void; + + /// Appends a named argument to the claimed table function, the equivalent of `name := value`. + /// @throws InvalidInputException Unless `SetFunctionName` was called first. + auto AddNamedArgument(std::string_view name, const Value &value) -> void; + + /// Claims the reference by naming a collection to read instead. The collection is borrowed: it must stay + /// alive, and must not be cleared, reset or destroyed, for as long as any result reading it is live. A + /// `PreparedStatement` over a claimed name extends that further: it captures the borrow in its plan and, + /// since a collection claim reads no database, reuses that plan without consulting the callback again + /// (`PreparedStatement::ReusesPlan` reports true). Destroy such statements before releasing the collection. + /// The three claim forms, `SetFunctionName`, `SetCollection` and `SetSubquery`, are mutually exclusive. + /// @param collection The collection to read. + /// @param column_names Names for its columns, in order; empty names them col1..colN. + /// @throws InvalidInputException When the names do not match the collection's columns, or a different claim + /// form was already used. + auto SetCollection(const ColumnDataCollection &collection, const std::vector &column_names = {}) + -> void; + + /// Claims the reference by naming a query to run instead. The text is parsed here and must contain exactly + /// one SELECT statement. The three claim forms, `SetFunctionName`, `SetCollection` and `SetSubquery`, are + /// mutually exclusive. + /// @throws Exception When the text does not parse, or is not a single SELECT. + /// @throws InvalidInputException When a different claim form was already used. + auto SetSubquery(std::string_view sql) -> void; + + /// Sets the alias the claimed replacement is bound under. Optional: an alias written in the query takes + /// precedence, and without either the reference's own table name is used. + auto SetAlias(std::string_view alias) -> void; + + /// The binding context. Borrowed, valid only for the callback duration. + auto GetContext() -> Context &; + + private: + Input(void *args, void *context) : args(args), context(detail::HandleFactory::Make(context)) { + } + + void *args; + Context context; + + void *GetUserDataInternal() const; + }; +}; + +//---------------------------------------------------------------------------------------------------------------------- +// Scalar Executor +//---------------------------------------------------------------------------------------------------------------------- + +namespace detail { + +/// @internal +/// Names `Vector` once per element of a type pack, to declare one owned child vector per tuple element. +template +using VectorPerField = Vector; + +/// @internal +/// Reads one argument row as a `T`. The primary template covers the primitive types; the specializations add the +/// composed forms: `std::reference_wrapper` reads in place, `std::optional` absorbs NULLs, and +/// `std::tuple` reads a STRUCT/TUPLE vector's fields through its child vectors, recursively. +/// `IsValid` reports whether a row can produce a value: false when a non-optional part of it is NULL. +template +struct VectorReader { + VectorView view; + + explicit VectorReader(const Vector &vec) : view(vec.GetView()) { + } + bool AllValid() const { + return view.AllValid(); + } + bool IsValid(idx_t row) const { + return view.IsValid(row); + } + T Get(idx_t row) const { + return view.Data()[view.SelAt(row)]; + } +}; + +template +struct VectorReader> { + VectorView view; + + explicit VectorReader(const Vector &vec) : view(vec.GetView()) { + } + bool AllValid() const { + return view.AllValid(); + } + bool IsValid(idx_t row) const { + return view.IsValid(row); + } + std::reference_wrapper Get(idx_t row) const { + return std::cref(view.Data()[view.SelAt(row)]); + } +}; + +template +struct VectorReader> { + VectorReader inner; + + explicit VectorReader(const Vector &vec) : inner(vec) { + } + bool AllValid() const { + return inner.AllValid(); + } + // A NULL is a value here (nullopt), so the row always participates. + bool IsValid(idx_t) const { + return true; + } + std::optional Get(idx_t row) const { + if (!inner.IsValid(row)) { + return std::nullopt; + } + return inner.Get(row); + } +}; + +template +struct VectorReader> { + VectorView view; + std::tuple...> children; + + explicit VectorReader(const Vector &vec) + : view(vec.GetView()), children(MakeChildren(vec, std::index_sequence_for {})) { + } + bool AllValid() const { + return AllValidImpl(std::index_sequence_for {}); + } + bool IsValid(idx_t row) const { + // The row's struct entry must be non-NULL, and so must every non-optional field of it. The children index + // by entry: their rows align with this vector's elements, so the selection applies once, here. + return view.IsValid(row) && IsValidImpl(view.SelAt(row), std::index_sequence_for {}); + } + std::tuple Get(idx_t row) const { + return GetImpl(view.SelAt(row), std::index_sequence_for {}); + } + +private: + template + static std::tuple...> MakeChildren(const Vector &vec, std::index_sequence) { + return std::tuple...> {VectorReader(vec.GetChild(Is))...}; + } + template + bool AllValidImpl(std::index_sequence) const { + return view.AllValid() && (... && std::get(children).AllValid()); + } + template + bool IsValidImpl(idx_t entry, std::index_sequence) const { + return (... && std::get(children).IsValid(entry)); + } + template + std::tuple GetImpl(idx_t entry, std::index_sequence) const { + return std::tuple {std::get(children).Get(entry)...}; + } +}; + +/// @internal +/// Writes one result row as a `T` into a FLAT vector, mirroring `VectorReader`'s type forms: primitives write the +/// element, `std::optional` turns nullopt into a NULL row, and `std::tuple` writes a STRUCT/TUPLE vector's +/// fields through its child vectors, recursively. NULLs go through the validity mask directly (fetched on first use, so +/// the all-valid path allocates no mask): the result's size is set by the engine only after the callback, so the +/// size-checked `Vector::SetNull` is not usable here. `ResetValidity` readies the masks before a loop that may write +/// NULLs; nulling a tuple row nulls its fields too, keeping the engine's nested-NULL invariant. +template +struct VectorWriter { + Vector &vec; + T *data; + ValidityMask mask {nullptr}; + + explicit VectorWriter(Vector &vec) : vec(vec), data(vec.GetDataMutable()) { + } + void ResetValidity(idx_t count) { + Mask().SetAllValid(count); + } + void Set(idx_t row, const T &value) { + data[row] = value; + } + void SetNull(idx_t row) { + Mask().SetInvalid(row); + } + +private: + ValidityMask &Mask() { + if (!mask.words) { + mask = vec.GetValidityMutable(); + } + return mask; + } +}; + +template +struct VectorWriter> { + VectorWriter inner; + + explicit VectorWriter(Vector &vec) : inner(vec) { + } + void ResetValidity(idx_t count) { + inner.ResetValidity(count); + } + void Set(idx_t row, const std::optional &value) { + if (value) { + inner.Set(row, *value); + } else { + inner.SetNull(row); + } + } + void SetNull(idx_t row) { + inner.SetNull(row); + } +}; + +template +struct VectorWriter> { + Vector &vec; + std::tuple...> child_vectors; + std::tuple...> children; + ValidityMask mask {nullptr}; + + explicit VectorWriter(Vector &vec) + : vec(vec), child_vectors(MakeChildVectors(vec, std::index_sequence_for {})), + children(MakeChildWriters(child_vectors, std::index_sequence_for {})) { + } + void ResetValidity(idx_t count) { + Mask().SetAllValid(count); + ResetValidityImpl(count, std::index_sequence_for {}); + } + void Set(idx_t row, const std::tuple &value) { + SetImpl(row, value, std::index_sequence_for {}); + } + void SetNull(idx_t row) { + // A NULL struct entry requires NULL fields, so the row nulls recursively. + Mask().SetInvalid(row); + SetNullImpl(row, std::index_sequence_for {}); + } + +private: + template + static std::tuple...> MakeChildVectors(Vector &vec, std::index_sequence) { + return std::tuple...> {vec.GetChild(Is)...}; + } + template + static std::tuple...> MakeChildWriters(std::tuple...> &vectors, + std::index_sequence) { + return std::tuple...> {VectorWriter(std::get(vectors))...}; + } + template + void ResetValidityImpl(idx_t count, std::index_sequence) { + (std::get(children).ResetValidity(count), ...); + } + template + void SetImpl(idx_t row, const std::tuple &value, std::index_sequence) { + (std::get(children).Set(row, std::get(value)), ...); + } + template + void SetNullImpl(idx_t row, std::index_sequence) { + (std::get(children).SetNull(row), ...); + } + ValidityMask &Mask() { + if (!mask.words) { + mask = vec.GetValidityMutable(); + } + return mask; + } +}; + +} // namespace detail + +/// Row-at-a-time execution helper for exec callbacks: give it the value types and a callable and it handles the +/// vector plumbing -- argument layout (selection vectors, constants), NULL propagation, and writing the result. For a +/// function this covers, the whole exec callback is one call: +/// +/// void AddExec(ScalarFunction::ExecInput &input) { +/// ScalarExecutor::Execute(input, [](int64_t a, int64_t b) { return a + b; }); +/// } +/// +/// The type list is the result type followed by one type per argument; a nullary function passes just the result +/// type. Each type is composed from these forms: +/// +/// - A primitive type (`VectorView::Data`'s element types) passes or returns the value itself. +/// - `std::reference_wrapper` (arguments only) passes a reference into the vector instead of a copy. +/// - `std::optional` makes NULL part of the value: an argument arrives as nullopt when its row is NULL instead of +/// nulling the row, and a result of nullopt makes the row NULL. Meaningful for arguments only when the function +/// uses special NULL handling; under the default the engine assumes NULL in, NULL out. +/// - `std::tuple` maps a STRUCT/TUPLE vector to its fields, read from and written to the child vectors; the +/// forms nest, so a field can itself be optional, a reference, or a tuple. +/// +/// Rows follow SQL's default NULL handling: a row where any non-optional part of any argument is NULL yields NULL, +/// and the callable is not invoked for it. Functions over strings or other unrepresented types drive the vectors +/// directly instead. +class ScalarExecutor { +public: + /// Fills the exec callback's result vector by invoking `fun` once per participating row. + /// @tparam RESULT The result type; `fun` must return it (or something convertible). + /// @tparam ARGS One type per argument, in signature order; `fun` is invoked with one value of each. + /// @param input The exec callback's input. + /// @param fun The callable computing one row: `RESULT(ARGS...)`. + /// @throws InvalidInputException When the call carries a different number of arguments than `ARGS` lists. + template + static void Execute(ScalarFunction::ExecInput &input, FUN fun) { + if (input.GetArgCount() != sizeof...(ARGS)) { + throw InvalidInputException("ScalarExecutor::Execute: the call carries " + + std::to_string(input.GetArgCount()) + " arguments but the type list names " + + std::to_string(sizeof...(ARGS))); + } + auto result = input.GetResult(); + ExecuteImpl(input, result, input.GetRowCount(), fun, std::index_sequence_for {}); + } + + /// The vector-level form, for vectors that come from somewhere other than an exec callback (e.g. a `DataChunk`): + /// one vector parameter per type in `ARGS`, so passing the wrong number of vectors is a compile error. + /// @tparam RESULT The result type; `fun` must return it (or something convertible). + /// @tparam ARGS One type per argument vector, in order; `fun` is invoked with one value of each. + /// @param args One vector per argument, each covering at least `count` rows. + /// @param result The FLAT vector to fill; must have room for `count` rows. + /// @param count How many rows to produce. + /// @param fun The callable computing one row: `RESULT(ARGS...)`. + template + static void Execute(detail::VectorPerArg... args, Vector &result, idx_t count, FUN fun) { + std::tuple...> readers {detail::VectorReader(args)...}; + detail::VectorWriter writer(result); + Run(readers, writer, count, fun, std::index_sequence_for {}); + } + +private: + template + static void ExecuteImpl(ScalarFunction::ExecInput &input, Vector &result, idx_t count, FUN &fun, + std::index_sequence seq) { + std::tuple...> readers {detail::VectorReader(input.GetArg(Is))...}; + detail::VectorWriter writer(result); + Run(readers, writer, count, fun, seq); + } + + template + static void Run(const std::tuple...> &readers, detail::VectorWriter &writer, + idx_t count, FUN &fun, std::index_sequence) { + if ((... && std::get(readers).AllValid())) { + for (idx_t i = 0; i < count; i++) { + writer.Set(i, fun(std::get(readers).Get(i)...)); + } + return; + } + + // Some argument row is NULL: propagate row by row through the result's mask. + writer.ResetValidity(count); + for (idx_t i = 0; i < count; i++) { + if ((... && std::get(readers).IsValid(i))) { + writer.Set(i, fun(std::get(readers).Get(i)...)); + } else { + writer.SetNull(i); + } + } + } +}; + +inline auto Factory::CreateType() -> TypeBuilder { + return TypeBuilder(*this); +} + +inline auto Connection::Execute(const SqlStatement &statement, const std::vector ¶meters) -> QueryResult { + return Execute(statement, parameters.data(), parameters.size()); +} + +inline auto PreparedStatement::Execute(const std::vector ¶meters) -> QueryResult { + return Execute(parameters.data(), parameters.size()); +} + +inline auto Connection::Execute(const SqlStatement &statement, const std::vector ¶meters, ArrowFormat format) + -> ArrowResult { + return Execute(statement, parameters.data(), parameters.size(), format); +} + +inline auto Connection::Execute(const SqlStatement &statement, const std::vector ¶meters, + ArrowFormat format) -> ArrowResult { + return ExecuteArrowNamed(statement, parameters.data(), parameters.size(), format); +} + +inline auto Connection::Execute(const std::string &sql, ArrowFormat format) -> ArrowResult { + auto statements = ParseSQL(sql); + auto statement = statements.Next(); + if (!statement || statements.Next()) { + throw InvalidInputException("Execute expects exactly one statement; use ParseSQL for multi-statement input"); + } + return Execute(statement, format); +} + +inline auto PreparedStatement::Execute(const std::vector ¶meters, ArrowFormat format) -> ArrowResult { + return Execute(parameters.data(), parameters.size(), format); +} + +inline auto PreparedStatement::Execute(const std::vector ¶meters, ArrowFormat format) -> ArrowResult { + return ExecuteArrowNamed(parameters.data(), parameters.size(), format); +} + +} // namespace cxx +} // namespace duckdb + +#ifdef DUCKDB_CPP_RESTORE_DELETE_MACRO +#pragma pop_macro("DELETE") +#undef DUCKDB_CPP_RESTORE_DELETE_MACRO +#endif +#ifdef DUCKDB_CPP_RESTORE_IGNORE_MACRO +#pragma pop_macro("IGNORE") +#undef DUCKDB_CPP_RESTORE_IGNORE_MACRO +#endif diff --git a/src/duckdb/tools/cpp/duckdb_cpp_extension.hpp b/src/duckdb/tools/cpp/duckdb_cpp_extension.hpp new file mode 100644 index 000000000..dddbaa3ac --- /dev/null +++ b/src/duckdb/tools/cpp/duckdb_cpp_extension.hpp @@ -0,0 +1,48 @@ +//===----------------------------------------------------------------------===// +// +// DuckDB +// +// duckdb_cpp_extension.hpp +// +// The entrypoint of an extension written against the C++ API. Include this +// instead of duckdb_extension_v2.h, in the file holding the entrypoint; every +// other file just includes duckdb_cpp.hpp. +// +// This is separate from duckdb_cpp.hpp because the entrypoint needs +// duckdb_extension_v2.h, and that header is not free to include: it rewrites +// every duckdb_v2_* name to an indirection through a vtable global, refuses to +// coexist with duckdb_extension.h, and forces a choice between the loadable and +// link-time flavors. duckdb_cpp.hpp names no C type at all, and a plain client +// application linking libduckdb should not have to answer any of that. +// +//===----------------------------------------------------------------------===// + +#pragma once + +#include "duckdb_cpp.hpp" + +// Match the flavor duckdb_cpp.cpp was compiled in: the loadable build routes every call through the extension vtable, +// anything else binds DuckDB's symbols at link time. +#if !defined(DUCKDB_CPP_API_LOADABLE) && !defined(DUCKDB_BUILD_STATIC_EXTENSION) +#define DUCKDB_BUILD_STATIC_EXTENSION +#endif +#include "duckdb_extension_v2.h" + +// The entrypoint macro below defines the vtable global that the C++ API archive references, so an extension must use it +// exactly once. Including this header more than once is harmless; expanding the macro twice is a duplicate symbol. + +//! Defines the entrypoint of a C++ API extension. Requires DUCKDB_EXTENSION_NAME to be set, which the build helpers do. +//! Write the body as +//! +//! DUCKDB_CPP_EXTENSION_ENTRYPOINT(duckdb::cxx::Extension &extension, duckdb::cxx::Context &context) { +//! ... +//! } +//! +//! Throwing from the body fails the load and reports the exception; returning normally completes it. +#define DUCKDB_CPP_EXTENSION_ENTRYPOINT \ + static void duckdb_cpp_extension_entry(duckdb::cxx::Extension &, duckdb::cxx::Context &); \ + DUCKDB_EXTENSION_ENTRYPOINT(duckdb_v2_extension_handle extension, duckdb_v2_context_handle context, \ + duckdb_v2_error_info_handle *err) { \ + duckdb::cxx::detail::RunExtensionEntry(duckdb_cpp_extension_entry, extension, context, err); \ + } \ + static void duckdb_cpp_extension_entry diff --git a/src/jni/arrow.cpp b/src/jni/arrow.cpp index ce74570b3..01cf9498c 100644 --- a/src/jni/arrow.cpp +++ b/src/jni/arrow.cpp @@ -1,184 +1,453 @@ #include "arrow.hpp" -#include "duckdb/common/arrow/arrow_appender.hpp" -#include "duckdb/common/arrow/arrow_converter.hpp" -#include "duckdb/function/table/arrow/arrow_duck_schema.hpp" - -using namespace duckdb; - -JavaResultArrowStream::JavaResultArrowStream(duckdb::unique_ptr res_p, - duckdb::unique_ptr> stream_p, idx_t batch_size_p) - : res(std::move(res_p)), res_stream(std::move(stream_p)), batch_size(batch_size_p) { - if (res) { - types = res->GetTypes(); - names = IdentifiersToStrings(res->GetNames()); - properties = res->client_properties; - } else { - types = res_stream->GetTypes(); - names = IdentifiersToStrings(res_stream->GetNames()); - properties = res_stream->GetClientProperties(); - } - if (properties.client_context) { - extension_types = ArrowTypeExtensionData::GetExtensionTypes(*properties.client_context, types); +#include "util.hpp" + +#include +#include +#include +#include +#include + +/** + * State of an Arrow stream that exports the rows of a result. The rows of the result are bound to a statement + * (SELECT * FROM the rows) that runs on a connection of its own with the Arrow result format, so that the connection + * of the result stays usable while the stream is open. The rows are moved out of the Java-owned holder, a result + * that is streamed is read into memory first. + */ +class JavaResultArrowStream : public ArrowStreamState { +public: + JavaResultArrowStream(ConnectionHolder &conn_holder, ResultHolder &source, idx_t batch_size) { + auto &factory = conn_holder.connection->GetFactory(); + names = source.names; + if (source.materialized) { + collection = std::move(source.materialized->collection); + source.materialized.reset(); + } else { + collection.emplace(factory.CreateColumnDataCollection(source.types)); + auto append_state = collection->CreateAppendState(); + if (source.first_chunk) { + collection->Append(append_state, *source.first_chunk); + source.first_chunk.reset(); + } + while (true) { + auto chunk = source.stream->FetchChunk(); + if (!chunk) { + break; + } + collection->Append(append_state, chunk); + } + // the connection of the result is free + source.stream.reset(); + } + + helper = std::make_unique(conn_holder.db->instance.Connect()); + copy_session_settings(*conn_holder.connection, *helper); + auto iterator = helper->ParseSQL(std::string("SELECT * FROM ") + ROWS_TABLE_NAME); + statement.emplace(iterator.Next()); + statement->AddCollection(ROWS_TABLE_NAME, *collection, names); + auto result = helper->Execute(*statement, cxx::ArrowFormat(batch_size)); + inner.release = nullptr; + result.ToArrowStream(inner); } -} -void JavaResultArrowStream::Close() { - std::lock_guard guard(lock); - closed = true; - chunk = nullptr; - res = nullptr; - res_stream = nullptr; -} + ~JavaResultArrowStream() override { + Close(); + } -ArrowArrayStream *JavaResultArrowStream::Export(duckdb::shared_ptr state) { - auto exported = new Exported(); - exported->state = std::move(state); - auto &stream = exported->stream; - stream.private_data = exported; - stream.get_schema = GetSchema; - stream.get_next = GetNext; - stream.get_last_error = GetLastError; - stream.release = Release; - return &stream; -} + void Close() override { + std::lock_guard guard(lock); + closed = true; + // the result of the stream goes first, as it uses the statement, the rows and the connection + if (inner.release) { + inner.release(&inner); + inner.release = nullptr; + } + statement.reset(); + helper.reset(); + collection.reset(); + } -JavaResultArrowStream &JavaResultArrowStream::GetState(ArrowArrayStream *stream) { - return *reinterpret_cast(stream->private_data)->state; -} + //! Creates a stream that shares the state, the stream is deleted when it is released + static ArrowArrayStream *Export(std::shared_ptr state) { + auto exported = new Exported(); + exported->state = std::move(state); + auto &stream = exported->stream; + stream.private_data = exported; + stream.get_schema = GetSchema; + stream.get_next = GetNext; + stream.get_last_error = GetLastError; + stream.release = Release; + return &stream; + } + +private: + static constexpr const char *ROWS_TABLE_NAME = "__jdbc_result_rows"; -int JavaResultArrowStream::GetSchema(ArrowArrayStream *stream, ArrowSchema *out) { - if (!stream->release) { - return -1; + struct Exported { + ArrowArrayStream stream; + std::shared_ptr state; + }; + + static JavaResultArrowStream &GetState(ArrowArrayStream *stream) { + return *reinterpret_cast(stream->private_data)->state; } - auto &self = GetState(stream); - std::lock_guard guard(self.lock); - out->release = nullptr; - try { - ArrowConverter::ToArrowSchema(out, self.types, self.names, self.properties); - } catch (std::exception &e) { - self.last_error = ErrorData(e); - return -1; + + //! Calls the function of the stream of the result, the error of the call is kept + template + int Forward(FUNCTION call) { + std::lock_guard guard(lock); + if (closed || !inner.release) { + last_error = "Connection Error: Connection was closed"; + return EIO; + } + auto res = call(); + if (res != 0) { + auto error = inner.get_last_error(&inner); + last_error = error ? error : "unable to read the result"; + } + return res; + } + + static int GetSchema(ArrowArrayStream *stream, ArrowSchema *out) { + if (!stream->release) { + return -1; + } + auto &self = GetState(stream); + out->release = nullptr; + return self.Forward([&]() { return self.inner.get_schema(&self.inner, out); }); + } + + static int GetNext(ArrowArrayStream *stream, ArrowArray *out) { + if (!stream->release) { + return -1; + } + auto &self = GetState(stream); + out->release = nullptr; + return self.Forward([&]() { return self.inner.get_next(&self.inner, out); }); } - return 0; + + static const char *GetLastError(ArrowArrayStream *stream) { + if (!stream->release) { + return nullptr; + } + auto &self = GetState(stream); + std::lock_guard guard(self.lock); + return self.last_error.empty() ? nullptr : self.last_error.c_str(); + } + + static void Release(ArrowArrayStream *stream) { + if (!stream->release) { + return; + } + auto exported = reinterpret_cast(stream->private_data); + stream->release = nullptr; + delete exported; + } + + std::mutex lock; + std::vector names; + std::optional collection; + std::unique_ptr helper; + std::optional statement; + //! The stream of the result of the statement + ArrowArrayStream inner {}; + bool closed = false; + std::string last_error; +}; + +ArrowArrayStream *create_result_arrow_stream(ConnectionHolder &conn_holder, ResultHolder &result, idx_t batch_size) { + auto state = std::make_shared(conn_holder, result, batch_size); + conn_holder.track_arrow_stream(state); + return JavaResultArrowStream::Export(std::move(state)); } -int JavaResultArrowStream::GetNext(ArrowArrayStream *stream, ArrowArray *out) { - if (!stream->release) { - return -1; +namespace { + +//! The name of the table function that scans a registered Arrow stream +const char *const ARROW_SCAN_FUNCTION = "__jdbc_arrow_stream_scan"; + +/** + * State of an Arrow stream registered with a connection. The stream is moved out of the Java-owned struct on + * registration, it is released when it is consumed by a scan or when the connection is closed. + */ +class JavaRegisteredArrowStream : public ArrowStreamState { +public: + explicit JavaRegisteredArrowStream(ArrowArrayStream *source) { + stream = *source; + source->release = nullptr; } - auto &self = GetState(stream); - std::lock_guard guard(self.lock); - out->release = nullptr; - if (self.closed) { - self.last_error = ErrorData(ConnectionException("Connection was closed")); - return -1; + + ~JavaRegisteredArrowStream() override { + Close(); } - try { - ArrowAppender appender(self.types, self.batch_size, self.properties, self.extension_types); - idx_t count = 0; - while (count < self.batch_size) { - if (!self.chunk || self.chunk_offset >= self.chunk->size()) { - if (!self.FetchChunk()) { - return -1; - } - if (!self.chunk) { - break; - } - continue; - } - auto &chunk = *self.chunk; - auto to_append = MinValue(self.batch_size - count, chunk.size() - self.chunk_offset); - appender.Append(chunk, self.chunk_offset, self.chunk_offset + to_append, chunk.size()); - self.chunk_offset += to_append; - count += to_append; + + void Close() override; + + void GetSchema(ArrowSchema &schema) { + std::lock_guard guard(lock); + if (!stream.release) { + throw JdbcException("Invalid Input Error: This stream has been released"); } - if (count > 0) { - *out = appender.Finalize(); + schema.release = nullptr; + if (stream.get_schema(&stream, &schema) != 0) { + auto error = stream.get_last_error(&stream); + throw JdbcException(std::string("Invalid Input Error: ") + (error ? error : "unable to read the schema")); } - } catch (std::exception &e) { - self.last_error = ErrorData(e); - return -1; } - return 0; + + //! A stream can only be consumed by a single scan + void Take(ArrowArrayStream &out); + + int64_t id = 0; + +private: + std::mutex lock; + ArrowArrayStream stream; +}; + +//! The registered streams by the ids that the views pass to the scan function +struct ArrowStreamRegistry { + std::mutex lock; + int64_t next_id = 1; + //! The streams are owned until they are consumed by a scan or closed with their connection + std::unordered_map> streams; + + void Add(const std::shared_ptr &state) { + std::lock_guard guard(lock); + state->id = next_id++; + streams[state->id] = state; + } + + std::shared_ptr Get(int64_t id) { + std::lock_guard guard(lock); + auto it = streams.find(id); + return it == streams.end() ? nullptr : it->second; + } + + void Remove(int64_t id) { + // the state can be destroyed here, it is destroyed after the lock is released + std::shared_ptr removed; + { + std::lock_guard guard(lock); + auto it = streams.find(id); + if (it != streams.end()) { + removed = std::move(it->second); + streams.erase(it); + } + } + } +}; + +ArrowStreamRegistry &arrow_stream_registry() { + static ArrowStreamRegistry registry; + return registry; } -const char *JavaResultArrowStream::GetLastError(ArrowArrayStream *stream) { - if (!stream->release) { - return "stream was released"; +void JavaRegisteredArrowStream::Close() { + { + std::lock_guard guard(lock); + if (stream.release) { + stream.release(&stream); + stream.release = nullptr; + } } - auto &self = GetState(stream); - std::lock_guard guard(self.lock); - return self.last_error.HasError() ? self.last_error.Message().c_str() : nullptr; + arrow_stream_registry().Remove(id); } -void JavaResultArrowStream::Release(ArrowArrayStream *stream) { - if (!stream || !stream->release) { - return; +void JavaRegisteredArrowStream::Take(ArrowArrayStream &out) { + { + std::lock_guard guard(lock); + if (!stream.release) { + throw JdbcException("Invalid Input Error: This stream has been released"); + } + out = stream; + stream.release = nullptr; } - stream->release = nullptr; - delete reinterpret_cast(stream->private_data); + arrow_stream_registry().Remove(id); } -bool JavaResultArrowStream::FetchChunk() { - chunk_offset = 0; - if (finished) { - chunk = nullptr; - return true; +//! Releases an Arrow stream that was taken from a registered stream +struct TakenArrowStream { + ArrowArrayStream stream {}; + + TakenArrowStream() = default; + TakenArrowStream(const TakenArrowStream &) = delete; + TakenArrowStream &operator=(const TakenArrowStream &) = delete; + + ~TakenArrowStream() { + if (stream.release) { + stream.release(&stream); + } } - if (res) { - chunk = res->Fetch(); - if (res->HasError()) { - last_error = res->GetErrorObject(); - return false; +}; + +struct ArrowScanBindData { + explicit ArrowScanBindData(std::shared_ptr state_p) : state(std::move(state_p)) { + } + + std::shared_ptr state; +}; + +struct ArrowScanGlobalState { + ArrowScanGlobalState(const std::shared_ptr &state, cxx::Context &context) { + // only the stream of the first scan can be read + state->Take(taken.stream); + ArrowSchema schema {}; + if (taken.stream.get_schema(&taken.stream, &schema) != 0) { + auto error = taken.stream.get_last_error(&taken.stream); + throw JdbcException(std::string("Invalid Input Error: ") + (error ? error : "unable to read the schema")); } - } else { - chunk = res_stream->Fetch(); - if (res_stream->HasError()) { - last_error = res_stream->GetErrorObject(); - return false; + try { + // the arrays are split into chunks that fit into the output chunk + std::vector types; + types.push_back(context.GetFactory().CreateType(cxx::LogicalTypeId::BOOLEAN)); + auto capacity = context.GetFactory().CreateDataChunk(types).GetCapacity(); + importer.emplace(context, schema, capacity); + } catch (...) { + if (schema.release) { + schema.release(&schema); + } + throw; + } + if (schema.release) { + schema.release(&schema); } } - if (!chunk) { - finished = true; + + //! The next chunk of the stream, the chunk is empty at the end of the stream + cxx::DataChunk NextChunk() { + while (true) { + auto chunk = importer->NextChunk(); + if (chunk) { + return chunk; + } + if (finished) { + return chunk; + } + ArrowArray array {}; + array.release = nullptr; + if (taken.stream.get_next(&taken.stream, &array) != 0) { + auto error = taken.stream.get_last_error(&taken.stream); + throw JdbcException(std::string("Invalid Input Error: ") + + (error ? error : "unable to read the stream")); + } + if (!array.release) { + // the end of the stream + finished = true; + importer->Flush(); + continue; + } + importer->Append(array, true); + } + } + + TakenArrowStream taken; + std::optional importer; + bool finished = false; +}; + +void arrow_scan_bind(cxx::TableFunction::BindInput &input) { + auto id = input.GetConstantArgument(0).Get(); + auto state = arrow_stream_registry().Get(id); + if (!state) { + throw JdbcException("Invalid Input Error: This stream has been released"); + } + ArrowSchema schema {}; + state->GetSchema(schema); + try { + cxx::ArrowImporter importer(input.GetContext(), schema); + auto resolved = importer.GetSchema(); + if (resolved.GetFieldCount() == 0) { + throw JdbcException("Invalid Input Error: Provided table/dataframe must have at least one column"); + } + for (idx_t i = 0; i < resolved.GetFieldCount(); i++) { + input.AddResultColumn(std::string(resolved.GetFieldName(i)), resolved.GetFieldType(i)); + } + } catch (...) { + if (schema.release) { + schema.release(&schema); + } + throw; + } + if (schema.release) { + schema.release(&schema); } - return true; + input.SetBindData(std::move(state)); } -JavaRegisteredArrowStream::JavaRegisteredArrowStream(ArrowArrayStream *source) : stream(*source) { - source->release = nullptr; +void arrow_scan_init_global(cxx::TableFunction::InitGlobalInput &input) { + auto &bind_data = input.GetBindData(); + input.SetGlobalState(bind_data.state, input.GetContext()); } -JavaRegisteredArrowStream::~JavaRegisteredArrowStream() { - Close(); +void arrow_scan_exec(cxx::TableFunction::ExecInput &input) { + auto &global = input.GetGlobalState(); + auto chunk = global.NextChunk(); + if (!chunk) { + // an empty output chunk is the end of the scan + return; + } + auto output = input.GetOutputChunk(); + for (idx_t i = 0; i < chunk.GetVectorCount(); i++) { + auto target = output.GetVector(i); + target.Reference(chunk.GetVector(i)); + } } -void JavaRegisteredArrowStream::Close() { - std::lock_guard guard(lock); - if (stream.release) { - stream.release(&stream); - stream.release = nullptr; +} // namespace + +//! The message of the error without the name of its type, as in "Invalid Input Error: message" +static std::string error_message_without_type(const std::string &message) { + auto pos = message.find(" Error: "); + if (pos == std::string::npos || pos > 40) { + return message; } + return message.substr(pos + 8); } -void JavaRegisteredArrowStream::GetSchema(ArrowSchema &schema) { - std::lock_guard guard(lock); - if (!stream.release) { - throw InvalidInputException("This stream has been released"); +void register_arrow_stream(ConnectionHolder &conn_holder, ArrowArrayStream *stream, const std::string &name) { + auto state = std::make_shared(stream); + conn_holder.track_arrow_stream(state); + arrow_stream_registry().Add(state); + auto id = state->id; + + std::string quoted_name = "\""; + for (char c : name) { + if (c == '"') { + quoted_name += "\"\""; + } else { + quoted_name += c; + } } - if (stream.get_schema(&stream, &schema) != 0) { - auto error = stream.get_last_error(&stream); - throw InvalidInputException(error ? error : "Unknown error getting Arrow stream schema"); + quoted_name += "\""; + try { + std::lock_guard guard(*conn_holder.lock); + conn_holder.connection + ->Execute("CREATE OR REPLACE TEMPORARY VIEW " + quoted_name + " AS SELECT * FROM " + ARROW_SCAN_FUNCTION + + "(" + std::to_string(id) + ")") + .Drain(); + } catch (const std::exception &e) { + state->Close(); + throw JdbcException(std::string("Failed to create view '") + name + + "': " + error_message_without_type(e.what())); + } + // the stream of the view that is replaced is released + auto replaced = conn_holder.replace_registered_stream(name, state); + if (replaced) { + replaced->Close(); } } -duckdb::unique_ptr JavaRegisteredArrowStream::Take() { - std::lock_guard guard(lock); - if (!stream.release) { - throw InvalidInputException("This stream has been released"); - } - auto res = make_uniq(); - res->arrow_array_stream = stream; - stream.release = nullptr; - return res; +void register_arrow_scan_function(cxx::Instance &instance) { + auto conn = instance.Connect(); + auto &factory = conn.GetFactory(); + auto function = cxx::TableFunction::Create(factory); + function.SetName(ARROW_SCAN_FUNCTION); + function.WithSignature([&factory](cxx::FunctionSignature &signature) { + signature.AddParameter("stream_id", factory.CreateType(cxx::LogicalTypeId::BIGINT)); + }); + function.SetBindCallback(arrow_scan_bind); + function.SetInitGlobalCallback(arrow_scan_init_global); + function.SetExecCallback(arrow_scan_exec); + conn.Register(function); } diff --git a/src/jni/arrow.hpp b/src/jni/arrow.hpp index 4bc1699a3..bbd5d08cb 100644 --- a/src/jni/arrow.hpp +++ b/src/jni/arrow.hpp @@ -1,75 +1,26 @@ #pragma once -#include "duckdb.hpp" -#include "duckdb/common/arrow/arrow_wrapper.hpp" -#include "duckdb/main/query_result_stream.hpp" #include "holders.hpp" -#include - -namespace duckdb { -class ArrowTypeExtensionData; -} - -//! Exports the chunks of a JDBC result as an Arrow stream of record batches of at most batch_size rows. -//! The result is moved out of the ResultHolder into this state, that is shared between the exported stream -//! and the connection. Connection closes the state (releasing the result) if it is closed before the stream. -class JavaResultArrowStream : public ArrowStreamState { -public: - JavaResultArrowStream(duckdb::unique_ptr res_p, - duckdb::unique_ptr> stream_p, duckdb::idx_t batch_size_p); - - void Close() override; - - //! Creates a stream that shares the state, the stream is deleted when it is released - static ArrowArrayStream *Export(duckdb::shared_ptr state); - -private: - struct Exported { - ArrowArrayStream stream; - duckdb::shared_ptr state; - }; - - static JavaResultArrowStream &GetState(ArrowArrayStream *stream); - static int GetSchema(ArrowArrayStream *stream, ArrowSchema *out); - static int GetNext(ArrowArrayStream *stream, ArrowArray *out); - static const char *GetLastError(ArrowArrayStream *stream); - static void Release(ArrowArrayStream *stream); - - //! Loads the next chunk, chunk is null at the end of the result - bool FetchChunk(); - - std::mutex lock; - duckdb::unique_ptr res; - duckdb::unique_ptr> res_stream; - duckdb::idx_t batch_size; - duckdb::vector types; - duckdb::vector names; - duckdb::ClientProperties properties; - duckdb::unordered_map> extension_types; - duckdb::unique_ptr chunk; - duckdb::idx_t chunk_offset = 0; - bool finished = false; - bool closed = false; - duckdb::ErrorData last_error; -}; - -//! Arrow stream registered with a connection. The stream is moved out of the Java-owned struct on registration, -//! it is released when it is consumed by a scan, when the view is dropped or when the connection is closed. -class JavaRegisteredArrowStream : public ArrowStreamState { -public: - explicit JavaRegisteredArrowStream(ArrowArrayStream *source); - - ~JavaRegisteredArrowStream() override; - - void Close() override; - - void GetSchema(ArrowSchema &schema); - - //! A stream can only be consumed by a single scan - duckdb::unique_ptr Take(); - -private: - std::mutex lock; - ArrowArrayStream stream; -}; +#include + +/** + * Exports the chunks of a JDBC result as an Arrow stream of record batches of at most batch_size rows. The data of + * the result is moved out of the ResultHolder into the state of the stream, that is shared between the exported stream + * and the connection. Connection closes the state (releasing the result) if it is closed before the stream. + * The returned stream is owned by its consumer, it is deleted when released. + */ +ArrowArrayStream *create_result_arrow_stream(ConnectionHolder &conn_holder, ResultHolder &result, idx_t batch_size); + +/** + * Registers the Arrow stream as a view with the specified name. The stream is moved out of the Java-owned struct on + * registration, it is released when it is consumed by a scan, when the view is dropped or when the connection is + * closed. + */ +void register_arrow_stream(ConnectionHolder &conn_holder, ArrowArrayStream *stream, const std::string &name); + +/** + * Registers the table function that is used by the views of the registered Arrow streams, called when the instance + * is created. + */ +void register_arrow_scan_function(cxx::Instance &instance); diff --git a/src/jni/bindings_appender.cpp b/src/jni/bindings_appender.cpp index 671f829d5..bd82e3a3c 100644 --- a/src/jni/bindings_appender.cpp +++ b/src/jni/bindings_appender.cpp @@ -2,38 +2,66 @@ #include "holders.hpp" #include "util.hpp" +#include +#include +#include +#include +#include + /* - * The C API v2 does not have an appender, the appender of the C API v1 is used. The connection, data chunks and - * logical types are passed between Java and JNI as C API v2 handles, they are converted to and from C API v1 handles - * here. In both APIs these handles point to the same engine objects, except logical types that are copied. + * The C API v2 does not have an appender, the appender of the stable C++ API is used. The connection, data chunks and + * logical types are passed between Java and JNI as C API v2 handles. */ -extern "C" { -#include "duckdb.h" -} -static duckdb_data_chunk v2_chunk_to_v1_chunk(duckdb_v2_data_chunk_handle chunk) { - duckdb::DataChunk *engine_chunk = duckdb::capiv2::Convert(chunk); - return reinterpret_cast(engine_chunk); +namespace { + +struct AppenderHolder { + //! The appender does not outlive the connection that it is created on + std::shared_ptr connection; + std::optional appender; + std::string error; + //! The qualified name of the table, to look up the default values of its columns + std::string catalog; + std::string schema; + std::string table; + //! The SQL texts of the default values of the columns, the lookup is done when the first default is appended + std::vector> defaults; + bool defaults_loaded = false; +}; + +std::string quote_identifier(const std::string &name) { + std::string res = "\""; + for (char c : name) { + if (c == '"') { + res += "\"\""; + } else { + res += c; + } + } + res += "\""; + return res; } -static duckdb_v2_logical_type_handle v1_logical_type_to_v2_logical_type(duckdb_logical_type logical_type) { - if (logical_type == nullptr) { - return nullptr; +std::string quote_literal(const std::string &value) { + std::string res = "'"; + for (char c : value) { + if (c == '\'') { + res += "''"; + } else { + res += c; + } } - auto engine_type = reinterpret_cast(logical_type); - auto res = duckdb::capiv2::Convert(engine_type->Copy()); - duckdb_destroy_logical_type(&logical_type); + res += "'"; return res; } -static duckdb_appender appender_buf_to_appender(JNIEnv *env, jobject appender_buf) { - +AppenderHolder *appender_buf_to_appender(JNIEnv *env, jobject appender_buf) { if (appender_buf == nullptr) { env->ThrowNew(J_SQLException, "Invalid appender buffer"); return nullptr; } - duckdb_appender appender = reinterpret_cast(env->GetDirectBufferAddress(appender_buf)); + auto appender = reinterpret_cast(env->GetDirectBufferAddress(appender_buf)); if (appender == nullptr) { env->ThrowNew(J_SQLException, "Invalid appender"); return nullptr; @@ -42,6 +70,46 @@ static duckdb_appender appender_buf_to_appender(JNIEnv *env, jobject appender_bu return appender; } +//! Wraps the chunk that is owned by the Java side, it is not destroyed with the wrapper +cxx::DataChunk borrow_chunk(duckdb_v2_data_chunk_handle chunk) { + return cxx::detail::HandleFactory::Make(static_cast(chunk), false); +} + +void load_defaults(AppenderHolder &app) { + if (app.defaults_loaded) { + return; + } + auto &conn = *app.connection; + // the default values of all columns of the table, in the order of the columns + std::string sql = "SELECT column_default FROM duckdb_columns() WHERE table_name = " + quote_literal(app.table); + if (!app.schema.empty()) { + sql += " AND schema_name = " + quote_literal(app.schema); + } + if (!app.catalog.empty()) { + sql += " AND database_name = " + quote_literal(app.catalog); + } + sql += " ORDER BY column_index"; + auto result = conn.Execute(sql); + while (true) { + auto chunk = result.FetchChunk(); + if (!chunk) { + break; + } + auto vec = chunk.GetVector(0); + for (idx_t i = 0; i < chunk.GetRowCount(); i++) { + auto value = vec.GetValue(i); + if (value.IsNull()) { + app.defaults.emplace_back(std::nullopt); + } else { + app.defaults.emplace_back(value.ToText()); + } + } + } + app.defaults_loaded = true; +} + +} // namespace + /* * Class: org_duckdb_DuckDBBindings * Method: duckdb_appender_create_ext @@ -53,45 +121,61 @@ JNIEXPORT jint JNICALL Java_org_duckdb_DuckDBBindings_duckdb_1appender_1create_1 jbyteArray schema, jbyteArray table, jobjectArray out_appender) { - duckdb::Connection *engine_conn = conn_ref_buf_to_engine_conn(env, connection); + ConnectionHolder *conn_holder = get_connection_ref(env, connection); if (env->ExceptionCheck()) { return -1; } - auto conn = reinterpret_cast(engine_conn); std::string catalog_str = jbyteArray_to_string(env, catalog); if (env->ExceptionCheck()) { return -1; } - const char *catalog_ptr = nullptr != catalog ? catalog_str.c_str() : nullptr; - std::string schema_str = jbyteArray_to_string(env, schema); if (env->ExceptionCheck()) { return -1; } - const char *schema_ptr = nullptr != schema ? schema_str.c_str() : nullptr; - std::string table_str = jbyteArray_to_string(env, table); if (env->ExceptionCheck()) { return -1; } - const char *table_ptr = nullptr != table ? table_str.c_str() : nullptr; + if (nullptr == table) { + return CAPI_STATE_ERROR; + } check_out_param(env, out_appender); if (env->ExceptionCheck()) { return -1; } - duckdb_appender appender = nullptr; + auto holder = std::make_unique(); + holder->connection = conn_holder->connection; + if (nullptr != catalog) { + holder->catalog = catalog_str; + } + if (nullptr != schema) { + holder->schema = schema_str; + } + holder->table = table_str; - duckdb_state state = duckdb_appender_create_ext(conn, catalog_ptr, schema_ptr, table_ptr, &appender); + std::string qualified_name; + if (nullptr != catalog) { + qualified_name += quote_identifier(catalog_str) + "."; + } + if (nullptr != schema) { + qualified_name += quote_identifier(schema_str) + "."; + } + qualified_name += quote_identifier(table_str); - if (state == DuckDBSuccess) { - jobject appender_ref_buf = env->NewDirectByteBuffer(appender, 0); - set_out_param(env, out_appender, appender_ref_buf); + try { + holder->appender.emplace(*holder->connection, qualified_name); + } catch (const std::exception &) { + return CAPI_STATE_ERROR; } - return static_cast(state); + jobject appender_ref_buf = env->NewDirectByteBuffer(holder.release(), 0); + set_out_param(env, out_appender, appender_ref_buf); + + return CAPI_STATE_SUCCESS; } /* @@ -102,19 +186,16 @@ JNIEXPORT jint JNICALL Java_org_duckdb_DuckDBBindings_duckdb_1appender_1create_1 JNIEXPORT jbyteArray JNICALL Java_org_duckdb_DuckDBBindings_duckdb_1appender_1error(JNIEnv *env, jclass, jobject appender) { - duckdb_appender app = appender_buf_to_appender(env, appender); + auto app = appender_buf_to_appender(env, appender); if (env->ExceptionCheck()) { return nullptr; } - const char *error_msg = duckdb_appender_error(app); - if (error_msg == nullptr) { + if (app->error.empty()) { return nullptr; } - idx_t len = static_cast(std::strlen(error_msg)); - - return make_jbyteArray(env, error_msg, len); + return make_jbyteArray(env, app->error.c_str(), static_cast(app->error.size())); } /* @@ -124,14 +205,18 @@ JNIEXPORT jbyteArray JNICALL Java_org_duckdb_DuckDBBindings_duckdb_1appender_1er */ JNIEXPORT jint JNICALL Java_org_duckdb_DuckDBBindings_duckdb_1appender_1flush(JNIEnv *env, jclass, jobject appender) { - duckdb_appender app = appender_buf_to_appender(env, appender); + auto app = appender_buf_to_appender(env, appender); if (env->ExceptionCheck()) { return -1; } - duckdb_state state = duckdb_appender_flush(app); - - return static_cast(state); + try { + app->appender->Flush(); + } catch (const std::exception &e) { + app->error = e.what(); + return CAPI_STATE_ERROR; + } + return CAPI_STATE_SUCCESS; } /* @@ -141,14 +226,18 @@ JNIEXPORT jint JNICALL Java_org_duckdb_DuckDBBindings_duckdb_1appender_1flush(JN */ JNIEXPORT jint JNICALL Java_org_duckdb_DuckDBBindings_duckdb_1appender_1close(JNIEnv *env, jclass, jobject appender) { - duckdb_appender app = appender_buf_to_appender(env, appender); + auto app = appender_buf_to_appender(env, appender); if (env->ExceptionCheck()) { return -1; } - duckdb_state state = duckdb_appender_close(app); - - return static_cast(state); + try { + app->appender->Flush(); + } catch (const std::exception &e) { + app->error = e.what(); + return CAPI_STATE_ERROR; + } + return CAPI_STATE_SUCCESS; } /* @@ -158,14 +247,14 @@ JNIEXPORT jint JNICALL Java_org_duckdb_DuckDBBindings_duckdb_1appender_1close(JN */ JNIEXPORT jint JNICALL Java_org_duckdb_DuckDBBindings_duckdb_1appender_1destroy(JNIEnv *env, jclass, jobject appender) { - duckdb_appender app = appender_buf_to_appender(env, appender); + auto app = appender_buf_to_appender(env, appender); if (env->ExceptionCheck()) { return -1; } - duckdb_state state = duckdb_appender_destroy(&app); + delete app; - return static_cast(state); + return CAPI_STATE_SUCCESS; } /* @@ -176,14 +265,12 @@ JNIEXPORT jint JNICALL Java_org_duckdb_DuckDBBindings_duckdb_1appender_1destroy( JNIEXPORT jlong JNICALL Java_org_duckdb_DuckDBBindings_duckdb_1appender_1column_1count(JNIEnv *env, jclass, jobject appender) { - duckdb_appender app = appender_buf_to_appender(env, appender); + auto app = appender_buf_to_appender(env, appender); if (env->ExceptionCheck()) { return -1; } - idx_t count = duckdb_appender_column_count(app); - - return static_cast(count); + return static_cast(app->appender->ColumnTypes().size()); } /* @@ -195,7 +282,7 @@ JNIEXPORT jobject JNICALL Java_org_duckdb_DuckDBBindings_duckdb_1appender_1colum jobject appender, jlong col_idx) { - duckdb_appender app = appender_buf_to_appender(env, appender); + auto app = appender_buf_to_appender(env, appender); if (env->ExceptionCheck()) { return nullptr; } @@ -205,9 +292,17 @@ JNIEXPORT jobject JNICALL Java_org_duckdb_DuckDBBindings_duckdb_1appender_1colum return nullptr; } - duckdb_logical_type logical_type = duckdb_appender_column_type(app, idx); + auto &types = app->appender->ColumnTypes(); + if (idx >= types.size()) { + return make_logical_type_buf(env, nullptr); + } - return make_logical_type_buf(env, v1_logical_type_to_v2_logical_type(logical_type)); + // the type is passed to Java as an owned handle + duckdb_v2_logical_type_handle copy = nullptr; + if (duckdb_v2_logical_type_copy(types[idx].handle(), ©, nullptr) != DUCKDB_V2_ERROR_NONE) { + return make_logical_type_buf(env, nullptr); + } + return make_logical_type_buf(env, copy); } /* @@ -218,19 +313,24 @@ JNIEXPORT jobject JNICALL Java_org_duckdb_DuckDBBindings_duckdb_1appender_1colum JNIEXPORT jint JNICALL Java_org_duckdb_DuckDBBindings_duckdb_1append_1data_1chunk(JNIEnv *env, jclass, jobject appender, jobject chunk) { - duckdb_appender app = appender_buf_to_appender(env, appender); + auto app = appender_buf_to_appender(env, appender); if (env->ExceptionCheck()) { return -1; } - duckdb_data_chunk dc = v2_chunk_to_v1_chunk(chunk_buf_to_chunk(env, chunk)); + auto raw_chunk = chunk_buf_to_chunk(env, chunk); if (env->ExceptionCheck()) { return -1; } + auto dc = borrow_chunk(raw_chunk); - duckdb_state state = duckdb_append_data_chunk(app, dc); - - return static_cast(state); + try { + app->appender->AppendChunk(dc); + } catch (const std::exception &e) { + app->error = e.what(); + return CAPI_STATE_ERROR; + } + return CAPI_STATE_SUCCESS; } /* @@ -243,11 +343,11 @@ JNIEXPORT jint JNICALL Java_org_duckdb_DuckDBBindings_duckdb_1append_1default_1t jobject chunk, jlong col, jlong row) { - duckdb_appender app = appender_buf_to_appender(env, appender); + auto app = appender_buf_to_appender(env, appender); if (env->ExceptionCheck()) { return -1; } - duckdb_data_chunk dc = v2_chunk_to_v1_chunk(chunk_buf_to_chunk(env, chunk)); + auto raw_chunk = chunk_buf_to_chunk(env, chunk); if (env->ExceptionCheck()) { return -1; } @@ -260,7 +360,31 @@ JNIEXPORT jint JNICALL Java_org_duckdb_DuckDBBindings_duckdb_1append_1default_1t return -1; } - duckdb_state state = duckdb_append_default_to_chunk(app, dc, col_idx, row_idx); - - return static_cast(state); + try { + load_defaults(*app); + auto dc = borrow_chunk(raw_chunk); + auto vec = dc.GetVector(col_idx); + // the size of the vector is set by the caller when the chunk is complete + if (vec.GetSize() <= row_idx) { + vec.SetSize(row_idx + 1); + } + if (col_idx < app->defaults.size() && app->defaults[col_idx]) { + // the default value is an expression, that is evaluated every time as it can be volatile + auto result = app->connection->Execute("SELECT " + *app->defaults[col_idx]); + auto value_chunk = result.FetchChunk(); + if (!value_chunk || value_chunk.GetRowCount() == 0) { + throw JdbcException("Invalid Input Error: Unable to evaluate the default value"); + } + auto value = value_chunk.GetVector(0).GetValue(0); + result.Drain(); + vec.SetValue(row_idx, value); + } else { + // a column without a default value gets the NULL default + vec.SetNull(row_idx); + } + } catch (const std::exception &e) { + app->error = e.what(); + return CAPI_STATE_ERROR; + } + return CAPI_STATE_SUCCESS; } diff --git a/src/jni/bindings_result.cpp b/src/jni/bindings_result.cpp index 58e82fac3..8b47f1ff0 100644 --- a/src/jni/bindings_result.cpp +++ b/src/jni/bindings_result.cpp @@ -49,6 +49,12 @@ JNIEXPORT jobject JNICALL Java_org_duckdb_DuckDBBindings_duckdb_1fetch_1chunk(JN return nullptr; } + if (res->has_first_chunk) { + // the chunk that was read when the result was created, an empty handle marks the end of the result + res->has_first_chunk = false; + return make_data_chunk_buf(env, res->first_chunk.release()); + } + duckdb_v2_data_chunk_handle chunk = nullptr; v2_error err; if (duckdb_v2_result_fetch_chunk(res->result.get(), &chunk, err.out()) != DUCKDB_V2_ERROR_NONE) { diff --git a/src/jni/config.cpp b/src/jni/config.cpp index 396d3d11d..ae1de04b0 100644 --- a/src/jni/config.cpp +++ b/src/jni/config.cpp @@ -1,62 +1,102 @@ #include "config.hpp" -#include "duckdb/common/virtual_file_system.hpp" +#include "arrow.hpp" #include "refs.hpp" #include "util.hpp" +#include +#include +#include +#include +#include #include #include +#include +#include +#include + +static const char *const JDBC_STREAM_RESULTS_OPTION = "jdbc_stream_results"; + +//! The options that need a running instance, they cannot be given at startup +static bool is_runtime_option(const std::string &name) { + static const std::unordered_set runtime_options = { + "allowed_directories", "allowed_paths", "disabled_filesystems", "enable_logging", "logging_level", + "logging_mode", "logging_storage", "enabled_log_types", "disabled_log_types"}; + std::string lower = name; + std::transform(lower.begin(), lower.end(), lower.begin(), [](unsigned char c) { return std::tolower(c); }); + return runtime_options.count(lower) > 0; +} + +static std::string quote_list_entry(const std::string &entry) { + std::string res = "'"; + for (char c : entry) { + if (c == '\'') { + res += "''"; + } else { + res += c; + } + } + res += "'"; + return res; +} + +static std::string format_double(double value) { + char buf[64]; + std::snprintf(buf, sizeof(buf), "%.17g", value); + return std::string(buf); +} -static duckdb::Value jobj_to_value(JNIEnv *env, const std::string &key, jobject jval) { +//! The text of a Java configuration value in the form that is accepted by SET, the empty optional is for nulls +static bool jobj_to_text(JNIEnv *env, jobject jval, std::string &res) { // On the right in comments are all types that are currently present // in DuckDB config. if (nullptr == jval) { - return duckdb::Value(); + return false; } else if (env->IsInstanceOf(jval, J_Bool)) { // BOOLEAN jboolean val = env->CallBooleanMethod(jval, J_Bool_booleanValue); check_java_exception_and_rethrow(env); - return duckdb::Value::BOOLEAN(val); + res = val ? "true" : "false"; - } else if (env->IsInstanceOf(jval, J_Byte)) { // UBIGINT + } else if (env->IsInstanceOf(jval, J_Byte)) { jbyte val = env->CallByteMethod(jval, J_Byte_byteValue); check_java_exception_and_rethrow(env); - return duckdb::Value::TINYINT(val); + res = std::to_string(static_cast(val)); - } else if (env->IsInstanceOf(jval, J_Short)) { // UBIGINT + } else if (env->IsInstanceOf(jval, J_Short)) { jshort val = env->CallShortMethod(jval, J_Short_shortValue); check_java_exception_and_rethrow(env); - return duckdb::Value::SMALLINT(val); + res = std::to_string(static_cast(val)); - } else if (env->IsInstanceOf(jval, J_Int)) { // UBIGINT + } else if (env->IsInstanceOf(jval, J_Int)) { jint val = env->CallIntMethod(jval, J_Int_intValue); check_java_exception_and_rethrow(env); - return duckdb::Value::INTEGER(val); + res = std::to_string(static_cast(val)); - } else if (env->IsInstanceOf(jval, J_Long)) { // UBIGINT + } else if (env->IsInstanceOf(jval, J_Long)) { jlong val = env->CallLongMethod(jval, J_Long_longValue); check_java_exception_and_rethrow(env); - return duckdb::Value::BIGINT(val); + res = std::to_string(static_cast(val)); - } else if (env->IsInstanceOf(jval, J_Float)) { // FLOAT + } else if (env->IsInstanceOf(jval, J_Float)) { jfloat val = env->CallFloatMethod(jval, J_Float_floatValue); check_java_exception_and_rethrow(env); - return duckdb::Value::FLOAT(val); + res = format_double(static_cast(val)); - } else if (env->IsInstanceOf(jval, J_Double)) { // DOUBLE + } else if (env->IsInstanceOf(jval, J_Double)) { jdouble val = env->CallDoubleMethod(jval, J_Double_doubleValue); check_java_exception_and_rethrow(env); - return duckdb::Value::DOUBLE(val); + res = format_double(static_cast(val)); - } else if (env->IsInstanceOf(jval, J_String)) { // VARCHAR - std::string val = jstring_to_string(env, reinterpret_cast(jval)); - return duckdb::Value(val); + } else if (env->IsInstanceOf(jval, J_String)) { + res = jstring_to_string(env, reinterpret_cast(jval)); } else if (env->IsInstanceOf(jval, J_List)) { // VARCHAR[] jobject iterator = env->CallObjectMethod(jval, J_List_iterator); check_java_exception_and_rethrow(env); - duckdb::vector vec; + res = "["; + bool first = true; while (env->CallBooleanMethod(iterator, J_Iterator_hasNext)) { check_java_exception_and_rethrow(env); jobject list_entry = env->CallObjectMethod(iterator, J_Iterator_next); @@ -64,65 +104,58 @@ static duckdb::Value jobj_to_value(JNIEnv *env, const std::string &key, jobject // all list entries are coalesced to string jstring jstr = reinterpret_cast(env->CallObjectMethod(list_entry, J_Object_toString)); check_java_exception_and_rethrow(env); - std::string sval = jstring_to_string(env, jstr); - duckdb::Value val(std::move(sval)); - vec.push_back(std::move(val)); + if (!first) { + res += ", "; + } + first = false; + res += quote_list_entry(jstring_to_string(env, jstr)); } check_java_exception_and_rethrow(env); - return duckdb::Value::LIST(duckdb::LogicalType::VARCHAR, std::move(vec)); + res += "]"; } else { // coalesce to string the entry with an unknown type jstring jstr = reinterpret_cast(env->CallObjectMethod(jval, J_Object_toString)); check_java_exception_and_rethrow(env); - std::string str = jstring_to_string(env, jstr); - return duckdb::Value(str); + res = jstring_to_string(env, jstr); } + return true; } -static bool is_allowed_paths_option(const std::string &key) { - return duckdb::StringUtil::CIEquals(key, "allowed_directories") || - duckdb::StringUtil::CIEquals(key, "allowed_paths"); +//! The database instances that are opened with the instance cache enabled, they are identified by the database path +static std::string instance_cache_key(const std::string &database) { + std::error_code ec; + auto path = std::filesystem::absolute(std::filesystem::path(database), ec); + if (ec) { + return database; + } + return path.lexically_normal().string(); } -// DuckDB refuses to set 'allowed_directories' and 'allowed_paths' through -// SetOptionByName before the database is started. Set them directly on the -// DBConfig instead, its options are copied to the database on startup. -// The check of 'enable_external_access' is skipped intentionally, at startup -// these options are commonly used together with 'enable_external_access=false' -// and the order in which properties are applied is not defined. -static void set_allowed_paths_option(duckdb::DBConfig &config, const std::string &key, const duckdb::Value &value) { - if (value.IsNull()) { - throw duckdb::InvalidInputException("%s setting cannot be NULL", key); - } - auto list_value = value.DefaultCastAs(duckdb::LogicalType::LIST(duckdb::LogicalType::VARCHAR)); - duckdb::vector paths; - for (auto &val : duckdb::ListValue::GetChildren(list_value)) { - paths.push_back(val.GetValue()); - } - if (duckdb::StringUtil::CIEquals(key, "allowed_directories")) { - config.SetAllowedDirectories(paths); - } else { - config.SetAllowedPaths(paths); - } - // keep the option in 'user_options' like SetOptionByName does for a user config, - // it is used by the instance cache to compare configs - config.options.user_options[duckdb::Identifier(key)] = value; +static void register_stream_results_option(cxx::Instance &instance) { + auto conn = instance.Connect(); + auto &factory = conn.GetFactory(); + auto option = cxx::CustomOption::Create(factory); + option.SetName(JDBC_STREAM_RESULTS_OPTION) + .SetType(factory.CreateType(cxx::LogicalTypeId::BOOLEAN)) + .SetDefaultValue(cxx::Value::Create(factory, false)) + .SetDescription("Whether to stream results. Only one ResultSet on a connection can be open at once when true") + .SetDefaultScope(cxx::SettingScope::SESSION) + .SetSupportsScope(cxx::SettingScope::GLOBAL, true) + .SetSupportsScope(cxx::SettingScope::SESSION, true); + conn.Register(option); } -std::unique_ptr create_db_config(JNIEnv *env, jboolean read_only, jobject java_config) { - auto config = std::unique_ptr(new duckdb::DBConfig()); - // Required for setting like 'allowed_directories' that use - // file separator when checking the property value. - config->file_system = duckdb::make_uniq(); - config->SetOptionByName("duckdb_api", "java"); - config->AddExtensionOption( - "jdbc_stream_results", - "Whether to stream results. Only one ResultSet on a connection can be open at once when true", - duckdb::LogicalType::BOOLEAN); +std::shared_ptr open_instance(JNIEnv *env, const std::string &database, jboolean read_only, + jobject java_config, bool cache_instance) { + cxx::StartupOptions startup; + std::vector> runtime_options; + std::vector> compat_options; + startup.Set("duckdb_api", "java"); if (read_only) { - config->options.access_mode = duckdb::AccessMode::READ_ONLY; + startup.Set("access_mode", "READ_ONLY"); } + jobject entry_set = env->CallObjectMethod(java_config, J_Map_entrySet); check_java_exception_and_rethrow(env); jobject iterator = env->CallObjectMethod(entry_set, J_Set_iterator); @@ -143,22 +176,69 @@ std::unique_ptr create_db_config(JNIEnv *env, jboolean read_on std::string key_str = jstring_to_string(env, key_jstr); env->DeleteLocalRef(key_jstr); - duckdb::Value dvalue = jobj_to_value(env, key_str, value); + std::string value_str; + bool has_value = jobj_to_text(env, value, value_str); env->DeleteLocalRef(value); + if (!has_value) { + continue; + } - try { - if (is_allowed_paths_option(key_str)) { - set_allowed_paths_option(*config, key_str, dvalue); - continue; - } - config->SetOptionByName(duckdb::Identifier(key_str), dvalue); - } catch (const std::exception &e) { - duckdb::ErrorData error(e); - throw duckdb::CatalogException("Failed to set configuration option \"%s\", error: %s", key_str, - error.RawMessage()); + if (key_str == JDBC_STREAM_RESULTS_OPTION || is_runtime_option(key_str)) { + runtime_options.emplace_back(key_str, value_str); + } else { + startup.Set(key_str, value_str); + compat_options.emplace_back(key_str, value_str); } } check_java_exception_and_rethrow(env); - return config; + // settings that cannot be given at startup are written when the instance is created + auto init = [&runtime_options](cxx::Instance &instance) { + register_stream_results_option(instance); + register_arrow_scan_function(instance); + for (auto &option : runtime_options) { + try { + instance.GetConfig().SetOption(option.first, option.second, cxx::SettingScope::GLOBAL); + } catch (const std::exception &e) { + throw JdbcException("Catalog Error: Failed to set configuration option \"" + option.first + + "\", error: " + e.what()); + } + } + }; + + bool should_cache = cache_instance && database != ":memory:" && !database.empty(); + std::shared_ptr holder; + if (should_cache) { + try { + holder = std::make_shared(cxx::Instance::OpenShared(database, startup, init)); + } catch (const cxx::Exception &e) { + throw JdbcException(std::string("Connection Error: ") + e.what()); + } + holder->key = instance_cache_key(database); + } else { + auto environment = std::make_unique(); + auto &env_ref = *environment; + const std::string memory_prefix = ":memory:"; + if (database.size() > memory_prefix.size() && database.compare(0, memory_prefix.size(), memory_prefix) == 0) { + // a named in-memory database + cxx::Instance instance(env_ref, startup); + instance.Attach(memory_prefix, database.substr(memory_prefix.size()), {}, true); + holder = std::make_shared(std::move(environment), std::move(instance)); + } else { + holder = + std::make_shared(std::move(environment), cxx::Instance(env_ref, database, startup)); + } + init(holder->instance); + } + holder->read_only = read_only; + std::sort(compat_options.begin(), compat_options.end()); + holder->options = std::move(compat_options); + return holder; +} + +jlong instance_address(const InstanceHolder &holder) { + if (!holder.key.empty()) { + return static_cast(std::hash()(holder.key) | 1); + } + return reinterpret_cast(&holder); } diff --git a/src/jni/config.hpp b/src/jni/config.hpp index 8218226fe..1d4469625 100644 --- a/src/jni/config.hpp +++ b/src/jni/config.hpp @@ -1,8 +1,20 @@ #pragma once -#include "duckdb.hpp" +#include "holders.hpp" #include #include +#include -std::unique_ptr create_db_config(JNIEnv *env, jboolean read_only, jobject java_config); +/** + * Opens a database instance, the instance is shared with the other connections to the same database file if + * the instance cache is enabled and the database is not an in-memory one. The configuration is read from the Java + * properties. + */ +std::shared_ptr open_instance(JNIEnv *env, const std::string &database, jboolean read_only, + jobject java_config, bool cache_instance); + +/** + * An identifier of the database instance, the same for all connections to the same cached instance. + */ +jlong instance_address(const InstanceHolder &holder); diff --git a/src/jni/cxx_handles.hpp b/src/jni/cxx_handles.hpp new file mode 100644 index 000000000..22e2172cd --- /dev/null +++ b/src/jni/cxx_handles.hpp @@ -0,0 +1,34 @@ +#pragma once + +#include "capi_v2.hpp" +#include "duckdb_cpp.hpp" + +/** + * The stable C++ API wrappers own C API v2 handles. Their handle() accessors are internal to the API and are not + * available outside of it by default, the traits that map a wrapper to its handle type are specialized here for + * the wrappers whose handles are passed to the C API v2 by the driver (the bindings use the C API v2 directly). + */ +namespace duckdb { +namespace cxx { +namespace detail { + +template <> +struct HandleTraits { + using handle = duckdb_v2_connection_handle; +}; +template <> +struct HandleTraits { + using handle = duckdb_v2_prepared_statement_handle; +}; +template <> +struct HandleTraits { + using handle = duckdb_v2_value_handle; +}; +template <> +struct HandleTraits { + using handle = duckdb_v2_logical_type_handle; +}; + +} // namespace detail +} // namespace cxx +} // namespace duckdb diff --git a/src/jni/duckdb_java.cpp b/src/jni/duckdb_java.cpp index 4cf0f2c83..192d142fc 100644 --- a/src/jni/duckdb_java.cpp +++ b/src/jni/duckdb_java.cpp @@ -1,50 +1,35 @@ #include "arrow.hpp" +#include "bindings.hpp" #include "config.hpp" -#include "duckdb.hpp" -#include "duckdb/catalog/catalog_search_path.hpp" -#include "duckdb/common/operator/cast_operators.hpp" -#include "duckdb/common/shared_ptr.hpp" -#include "duckdb/common/vector/array_vector.hpp" -#include "duckdb/common/vector/list_vector.hpp" -#include "duckdb/common/vector/struct_vector.hpp" -#include "duckdb/function/scalar/variant_utils.hpp" -#include "duckdb/function/table/arrow.hpp" -#include "duckdb/main/appender.hpp" -#include "duckdb/main/capi_v2/capi_v2_internal.hpp" -#include "duckdb/main/capi_v2/capi_v2_result_internal.hpp" -#include "duckdb/main/client_context.hpp" -#include "duckdb/main/client_data.hpp" -#include "duckdb/main/database_manager.hpp" -#include "duckdb/main/db_instance_cache.hpp" -#include "duckdb/main/extension/extension_loader.hpp" -#include "duckdb/parser/expression/function_expression.hpp" -#include "duckdb/parser/expression/star_expression.hpp" -#include "duckdb/parser/parsed_data/create_type_info.hpp" -#include "duckdb/parser/parsed_data/create_view_info.hpp" -#include "duckdb/parser/query_node/select_node.hpp" -#include "duckdb/parser/statement/create_statement.hpp" -#include "duckdb/parser/statement/select_statement.hpp" -#include "duckdb/parser/tableref/table_function_ref.hpp" #include "functions.hpp" #include "holders.hpp" #include "refs.hpp" #include "types.hpp" #include "util.hpp" +#include #include +#include #include #include +#include -using namespace duckdb; using namespace std; static jint JNI_VERSION = JNI_VERSION_1_6; void ThrowJNI(JNIEnv *env, const char *message) { - D_ASSERT(J_SQLException); env->ThrowNew(J_SQLException, message); } +void ThrowJNIException(JNIEnv *env, const std::exception &e) { + if (dynamic_cast(&e) != nullptr) { + env->ThrowNew(J_SQLTimeoutException, e.what()); + return; + } + env->ThrowNew(J_SQLException, e.what()); +} + JNIEXPORT jint JNICALL JNI_OnLoad(JavaVM *vm, void *reserved) { JNIEnv *env; if (vm->GetEnv(reinterpret_cast(&env), JNI_VERSION) != JNI_OK) { @@ -74,26 +59,91 @@ JNIEXPORT void JNICALL JNI_OnUnload(JavaVM *vm, void *reserved) { delete_global_refs(env); } -//! The database instance cache, used so that multiple connections to the same file point to the same database object -duckdb::DBInstanceCache instance_cache; +//! Quotes the string for the use in SQL +static std::string quote_literal(const std::string &value) { + std::string res = "'"; + for (char c : value) { + if (c == '\'') { + res += "''"; + } else { + res += c; + } + } + res += "'"; + return res; +} + +//! Quotes the identifier for the use in SQL +static std::string quote_identifier(const std::string &name) { + std::string res = "\""; + for (char c : name) { + if (c == '"') { + res += "\"\""; + } else { + res += c; + } + } + res += "\""; + return res; +} + +//! The connection of the statement or result, throws if it was closed +static std::shared_ptr lock_connection(const std::weak_ptr &connection) { + auto res = connection.lock(); + if (!res) { + throw JdbcException("Invalid Input Error: Attempting to use a result or a statement after its connection was " + "closed!"); + } + return res; +} + +//! The lock of the connection of the statement or result, throws if the connection was closed +static std::shared_ptr lock_connection_mutex(const std::weak_ptr &lock) { + auto res = lock.lock(); + if (!res) { + throw JdbcException("Invalid Input Error: Attempting to use a result or a statement after its connection was " + "closed!"); + } + return res; +} + +//! Reads the value of the first row and the first column of the query result as a string +static std::string query_single_string(cxx::Connection &conn, const std::string &sql) { + auto result = conn.Execute(sql); + std::string res; + bool found = false; + while (true) { + auto chunk = result.FetchChunk(); + if (!chunk) { + break; + } + if (!found && chunk.GetRowCount() > 0) { + auto value = chunk.GetVector(0).GetValue(0); + if (!value.IsNull()) { + res = value.ToText(); + } + found = true; + } + } + return res; +} jobject _duckdb_jdbc_startup(JNIEnv *env, jclass, jbyteArray database_j, jboolean read_only, jobject props, jboolean cache_instance) { auto database = jbyteArray_to_string(env, database_j); - std::unique_ptr config = create_db_config(env, read_only, props); - bool should_cache = cache_instance && database != ":memory:" && !database.empty(); - auto shared_db = instance_cache.GetOrCreateInstance(database, *config, should_cache); - auto conn_ref = new ConnectionHolder(shared_db); + auto instance = open_instance(env, database, read_only, props, cache_instance); + auto conn_ref = new ConnectionHolder(std::move(instance)); return env->NewDirectByteBuffer(conn_ref, 0); } jobject _duckdb_jdbc_connect(JNIEnv *env, jclass, jobject conn_ref_buf) { auto conn_ref = get_connection_ref(env, conn_ref_buf); - auto config = ClientConfig::GetConfig(*conn_ref->connection->context); - auto conn = new ConnectionHolder(conn_ref->db); - ClientConfig::GetConfig(*conn->connection->context) = config; - return env->NewDirectByteBuffer(conn, 0); + auto conn = std::make_unique(conn_ref->db); + + // the session settings of the new connection are the same as the ones of this connection + copy_session_settings(*conn_ref->connection, *conn->connection); + return env->NewDirectByteBuffer(conn.release(), 0); } jobject _duckdb_jdbc_create_db_ref(JNIEnv *env, jclass, jobject conn_ref_buf) { @@ -104,8 +154,7 @@ jobject _duckdb_jdbc_create_db_ref(JNIEnv *env, jclass, jobject conn_ref_buf) { jlong _duckdb_jdbc_db_address(JNIEnv *env, jclass, jobject conn_ref_buf) { auto conn_ref = get_connection_ref(env, conn_ref_buf); - // the instance cache returns a new DuckDB handle for every cache hit, the DatabaseInstance is the shared object - return (jlong)conn_ref->db->instance.get(); + return instance_address(*conn_ref->db); } void _duckdb_jdbc_destroy_db_ref(JNIEnv *env, jclass, jobject db_ref_buf) { @@ -119,92 +168,50 @@ void _duckdb_jdbc_destroy_db_ref(JNIEnv *env, jclass, jobject db_ref_buf) { } jstring _duckdb_jdbc_get_schema(JNIEnv *env, jclass, jobject conn_ref_buf) { - auto conn_ref = get_connection(env, conn_ref_buf); - if (!conn_ref) { - return nullptr; - } - - auto entry = ClientData::Get(*conn_ref->context).catalog_search_path->GetDefault(); - - return env->NewStringUTF(entry.GetSchema().c_str()); -} - -static void set_catalog_search_path(JNIEnv *env, jobject conn_ref_buf, CatalogSearchEntry search_entry) { - auto conn_ref = get_connection(env, conn_ref_buf); - if (!conn_ref) { - return; - } - - conn_ref->context->RunFunctionInTransaction([&]() { - ClientData::Get(*conn_ref->context).catalog_search_path->Set(search_entry, CatalogSetPathType::SET_SCHEMA); - }); + auto conn_holder = get_connection_ref(env, conn_ref_buf); + std::lock_guard guard(*conn_holder->lock); + auto schema = query_single_string(*conn_holder->connection, "SELECT current_schema()"); + return env->NewStringUTF(schema.c_str()); } void _duckdb_jdbc_set_schema(JNIEnv *env, jclass, jobject conn_ref_buf, jstring schema) { - set_catalog_search_path( - env, conn_ref_buf, CatalogSearchEntry(Identifier(INVALID_CATALOG), Identifier(jstring_to_string(env, schema)))); + auto conn_holder = get_connection_ref(env, conn_ref_buf); + std::lock_guard guard(*conn_holder->lock); + conn_holder->connection->Execute("SET schema = " + quote_literal(jstring_to_string(env, schema))).Drain(); } void _duckdb_jdbc_set_catalog(JNIEnv *env, jclass, jobject conn_ref_buf, jstring catalog) { - set_catalog_search_path( - env, conn_ref_buf, CatalogSearchEntry(Identifier(jstring_to_string(env, catalog)), Identifier(DEFAULT_SCHEMA))); + auto conn_holder = get_connection_ref(env, conn_ref_buf); + std::lock_guard guard(*conn_holder->lock); + conn_holder->connection->Execute("USE " + quote_identifier(jstring_to_string(env, catalog))).Drain(); } jstring _duckdb_jdbc_get_catalog(JNIEnv *env, jclass, jobject conn_ref_buf) { - auto conn_ref = get_connection(env, conn_ref_buf); - if (!conn_ref) { - return nullptr; - } - - auto entry = ClientData::Get(*conn_ref->context).catalog_search_path->GetDefault(); - if (entry.GetCatalog() == INVALID_CATALOG) { - entry.SetCatalog(DatabaseManager::GetDefaultDatabase(*conn_ref->context)); - } - - return env->NewStringUTF(entry.GetCatalog().c_str()); + auto conn_holder = get_connection_ref(env, conn_ref_buf); + std::lock_guard guard(*conn_holder->lock); + auto catalog = query_single_string(*conn_holder->connection, "SELECT current_database()"); + return env->NewStringUTF(catalog.c_str()); } void _duckdb_jdbc_set_auto_commit(JNIEnv *env, jclass, jobject conn_ref_buf, jboolean auto_commit) { - auto conn_ref = get_connection(env, conn_ref_buf); - if (!conn_ref) { - return; - } - conn_ref->context->RunFunctionInTransaction([&]() { conn_ref->SetAutoCommit(auto_commit); }); + // the auto-commit mode is handled by the Java side with the explicit transactions, the connection is always in + // the auto-commit mode here + get_connection(env, conn_ref_buf); } jboolean _duckdb_jdbc_get_auto_commit(JNIEnv *env, jclass, jobject conn_ref_buf) { - auto conn_ref = get_connection(env, conn_ref_buf); - if (!conn_ref) { - return false; - } - return conn_ref->IsAutoCommit(); + get_connection(env, conn_ref_buf); + return true; } void _duckdb_jdbc_interrupt(JNIEnv *env, jclass, jobject conn_ref_buf) { - auto conn_ref = get_connection(env, conn_ref_buf); - if (!conn_ref) { - return; - } - conn_ref->Interrupt(); + get_connection(env, conn_ref_buf).Interrupt(); } jobject _duckdb_jdbc_query_progress(JNIEnv *env, jclass, jobject conn_ref_buf) { - auto conn_ref = get_connection(env, conn_ref_buf); - if (!conn_ref) { - return nullptr; - } - auto conn_holder = get_connection_ref(env, conn_ref_buf); - auto conn = duckdb::capiv2::Convert(conn_holder->connection.get()); - double percentage = -1; - uint64_t rows_processed = 0; - uint64_t total_rows_to_process = 0; - v2_error err; - if (duckdb_v2_connection_progress_get(conn, &percentage, &rows_processed, &total_rows_to_process, err.out()) != - DUCKDB_V2_ERROR_NONE) { - throw InvalidInputException(err.message()); - } - return env->NewObject(J_QueryProgress, J_QueryProgress_init, static_cast(percentage), - uint64_to_jlong(rows_processed), uint64_to_jlong(total_rows_to_process)); + auto progress = get_connection(env, conn_ref_buf).GetQueryProgress(); + return env->NewObject(J_QueryProgress, J_QueryProgress_init, static_cast(progress.percentage), + uint64_to_jlong(progress.rows_processed), uint64_to_jlong(progress.total_rows_to_process)); } void _duckdb_jdbc_disconnect(JNIEnv *env, jclass, jobject conn_ref_buf) { @@ -217,263 +224,235 @@ void _duckdb_jdbc_disconnect(JNIEnv *env, jclass, jobject conn_ref_buf) { } } -#include "utf8proc_wrapper.hpp" - -jobject _duckdb_jdbc_prepare(JNIEnv *env, jclass, jobject conn_ref_buf, jbyteArray query_j) { - auto conn_ref = get_connection(env, conn_ref_buf); - if (!conn_ref) { - return nullptr; +//! Parses the query and returns its last statement. The statements before it are run, unless the query is prepared: +//! preparing must not have side effects, so a query with multiple statements is rejected then. +static cxx::SqlStatement extract_last_statement(cxx::Connection &conn, const std::string &query, bool is_prepare) { + auto iterator = conn.ParseSQL(query); + std::vector statements; + while (true) { + auto statement = iterator.Next(); + if (!statement) { + break; + } + statements.push_back(std::move(statement)); } - - auto query = jbyteArray_to_string(env, query_j); - - auto statements = conn_ref->ExtractStatements(query.c_str()); if (statements.empty()) { - throw InvalidInputException("No statements to execute."); + throw JdbcException("Invalid Input Error: No statements to execute."); } - // preparing must not have side effects, so multiple statements are rejected instead of - // executing all statements besides the last one - if (statements.size() > 1) { - throw InvalidInputException("Cannot prepare multiple statements at once, statements count: " + - std::to_string(statements.size())); + if (is_prepare && statements.size() > 1) { + throw JdbcException("Invalid Input Error: Cannot prepare multiple statements at once, statements count: " + + std::to_string(statements.size())); } - auto stmt_ref = make_uniq(); - stmt_ref->stmt = conn_ref->Prepare(std::move(statements.back())); - if (stmt_ref->stmt->HasError()) { - string error_msg = string(stmt_ref->stmt->GetError()); - stmt_ref->stmt = nullptr; - ThrowJNI(env, error_msg.c_str()); - return nullptr; + // if there are multiple statements, we directly execute the statements besides the last one + // we only return the result of the last statement to the user, unless one of the previous statements fails + for (size_t i = 0; i + 1 < statements.size(); i++) { + conn.Execute(statements[i]).Drain(); } + return std::move(statements.back()); +} + +jobject _duckdb_jdbc_prepare(JNIEnv *env, jclass, jobject conn_ref_buf, jbyteArray query_j) { + auto conn_holder = get_connection_ref(env, conn_ref_buf); + auto &conn = get_connection(env, conn_ref_buf); + std::lock_guard guard(*conn_holder->lock); + + auto query = jbyteArray_to_string(env, query_j); + + auto stmt_ref = std::make_unique(); + stmt_ref->connection = conn_holder->connection; + stmt_ref->lock = conn_holder->lock; + stmt_ref->statement.emplace(extract_last_statement(conn, query, true)); + stmt_ref->statement_type = stmt_ref->statement->GetStatementType(); + stmt_ref->stmt.emplace(conn.Prepare(*stmt_ref->statement)); + stmt_ref->signature.emplace(conn.Bind(*stmt_ref->statement)); return env->NewDirectByteBuffer(stmt_ref.release(), 0); } jobject _duckdb_jdbc_pending_query(JNIEnv *env, jclass, jobject conn_ref_buf, jbyteArray query_j) { - auto conn_ref = get_connection(env, conn_ref_buf); - if (!conn_ref) { - return nullptr; - } + auto conn_holder = get_connection_ref(env, conn_ref_buf); + auto &conn = get_connection(env, conn_ref_buf); + std::lock_guard guard(*conn_holder->lock); auto query = jbyteArray_to_string(env, query_j); - auto statements = conn_ref->ExtractStatements(query.c_str()); - if (statements.empty()) { - throw InvalidInputException("No statements to execute."); - } - - // if there are multiple statements, we directly execute the statements besides the last one - // we only return the result of the last statement to the user, unless one of the previous statements fails - for (idx_t i = 0; i + 1 < statements.size(); i++) { - auto res = conn_ref->Query(std::move(statements[i])); - if (res->HasError()) { - res->ThrowError(); - } - } + auto statement = extract_last_statement(conn, query, false); - Value result; - bool stream_results = - conn_ref->context->TryGetCurrentSetting("jdbc_stream_results", result) ? result.GetValue() : false; + bool stream_results = conn.GetConfig().GetOption("jdbc_stream_results").value.Get(); - auto pending_ref = make_uniq(); - pending_ref->pending = conn_ref->Submit(std::move(statements.back())); + auto pending_ref = std::make_unique(); + pending_ref->connection = conn_holder->connection; + pending_ref->lock = conn_holder->lock; + pending_ref->pending.emplace(conn.Execute(statement)); pending_ref->streaming = stream_results; return env->NewDirectByteBuffer(pending_ref.release(), 0); } -template -static void throw_execution_java_error(JNIEnv *env, T *res) { - std::string error_msg = std::string(res->GetError()); - duckdb::ExceptionType error_type = res->GetErrorType(); - jclass exc_type = duckdb::ExceptionType::INTERRUPT == error_type ? J_SQLTimeoutException : J_SQLException; - env->ThrowNew(exc_type, error_msg.c_str()); +static std::string result_type_to_string(cxx::ResultType type) { + switch (type) { + case cxx::ResultType::QUERY_RESULT: + return "QUERY_RESULT"; + case cxx::ResultType::CHANGED_ROWS: + return "CHANGED_ROWS"; + default: + return "NOTHING"; + } } -static duckdb::unique_ptr execute_prepared_statement(JNIEnv *env, jobject stmt_ref_buf, - jobjectArray params, bool stream_results) { - auto stmt_ref = reinterpret_cast(env->GetDirectBufferAddress(stmt_ref_buf)); - if (!stmt_ref || !stmt_ref->stmt) { - throw InvalidInputException("Invalid statement"); +//! Reads the schema and the result type of the result, fails if the result has an error +static void read_result_metadata(ResultHolder &holder, cxx::QueryResult &result) { + auto schema = result.GetSchema(); + holder.names.clear(); + holder.types.clear(); + for (idx_t i = 0; i < schema.GetFieldCount(); i++) { + holder.names.emplace_back(schema.GetFieldName(i)); + holder.types.push_back(schema.GetFieldType(i)); } + holder.result_type = result.GetResultType(); +} - duckdb::vector duckdb_params; - - idx_t param_len = env->GetArrayLength(params); +//! Whether the result is streamed instead of being read into the memory, streaming is only used for +//! the SELECT statements +static bool streams_by_default(cxx::StatementType written_type, cxx::ResultType result_type) { + return written_type == cxx::StatementType::SELECT && result_type == cxx::ResultType::QUERY_RESULT; +} - if (param_len != stmt_ref->stmt->GetParameterCount()) { - throw InvalidInputException("Parameter count mismatch"); - } +//! Completes the execution of the result into the holder: the rows are read into the memory, or the result is kept +//! to be streamed +static std::unique_ptr complete_result(cxx::Connection &conn, + const std::weak_ptr &conn_weak, + cxx::QueryResult result, cxx::StatementType written_type, + bool stream_results_user) { + auto holder = std::make_unique(); + holder->connection = conn_weak; - auto context = stmt_ref->stmt->TryGetContext(); - if (!context) { - throw InvalidInputException("Attempting to execute a prepared statement after its connection was closed!"); - } + // the first chunk is read to find out if the query is running without errors, also to complete the metadata + auto first_chunk = result.FetchChunk(); + read_result_metadata(*holder, result); - if (param_len > 0) { - for (idx_t i = 0; i < param_len; i++) { - auto param = env->GetObjectArrayElement(params, i); - duckdb::Value val = to_duckdb_value(env, param, *context); - env->DeleteLocalRef(param); - duckdb_params.push_back(std::move(val)); + bool stream_results = stream_results_user && streams_by_default(written_type, holder->result_type); + if (stream_results) { + if (first_chunk) { + holder->first_chunk.emplace(std::move(first_chunk)); } - } + holder->stream.emplace(std::move(result)); + return holder; + } + + auto &factory = conn.GetFactory(); + holder->materialized = std::make_unique(); + auto &data = *holder->materialized; + data.collection.emplace(factory.CreateColumnDataCollection(holder->types)); + auto append_state = data.collection->CreateAppendState(); + auto chunk = std::move(first_chunk); + while (chunk) { + data.collection->Append(append_state, chunk); + chunk = result.FetchChunk(); + } + data.shared_state.emplace(data.collection->CreateSharedScanState()); + data.worker_state.emplace(data.collection->CreateWorkerScanState()); + return holder; +} - duckdb::unique_ptr res; - if (stream_results) { - res = stmt_ref->stmt->Submit(duckdb_params); - } else { - res = stmt_ref->stmt->Execute(duckdb_params); - } +static cxx::QueryResult execute_prepared_statement(JNIEnv *env, StatementHolder &stmt_ref, jobjectArray params, + cxx::Connection &conn) { + idx_t param_len = env->GetArrayLength(params); - if (res->HasError()) { - throw_execution_java_error(env, res.get()); - return nullptr; + if (param_len != stmt_ref.signature->parameters.GetFieldCount()) { + throw JdbcException("Invalid Input Error: Parameter count mismatch"); } - return res; -} - -duckdb::unique_ptr> complete_query_streaming(JNIEnv *env, duckdb::unique_ptr pending) { - auto stream = make_uniq>(std::move(pending)); - while (!duckdb::IsObservable(stream->ExecuteTask())) { - } - if (stream->HasError()) { - throw_execution_java_error(env, stream.get()); - return nullptr; + std::vector duckdb_params; + for (idx_t i = 0; i < param_len; i++) { + auto param = env->GetObjectArrayElement(params, i); + auto val = to_duckdb_value(env, param, conn.GetFactory()); + env->DeleteLocalRef(param); + duckdb_params.push_back(std::move(val)); } - return stream; -} -duckdb::unique_ptr complete_query_materialized(JNIEnv *env, duckdb::unique_ptr pending) { - pending->Complete(); - if (pending->HasError()) { - throw_execution_java_error(env, pending.get()); - return nullptr; - } - return pending; + return stmt_ref.stmt->Execute(duckdb_params); } -jobject _duckdb_jdbc_execute(JNIEnv *env, jclass, jobject stmt_ref_buf, jobjectArray params) { +static StatementHolder &get_statement(JNIEnv *env, jobject stmt_ref_buf) { auto stmt_ref = reinterpret_cast(env->GetDirectBufferAddress(stmt_ref_buf)); if (!stmt_ref || !stmt_ref->stmt) { - throw InvalidInputException("Invalid statement"); - } - auto context = stmt_ref->stmt->TryGetContext(); - if (!context) { - throw InvalidInputException("Attempting to execute a prepared statement after its connection was closed!"); - } - Value result; - bool stream_results_user = - context->TryGetCurrentSetting("jdbc_stream_results", result) ? result.GetValue() : false; - - auto pending = execute_prepared_statement(env, stmt_ref_buf, params, stream_results_user); - if (pending == nullptr) { - return nullptr; - } - - bool stream_results_stmt = StreamsByDefault(stmt_ref->stmt->GetStatementType(), *pending); - bool stream_results = stream_results_user && stream_results_stmt; - - auto res_ref = make_uniq(); - - if (stream_results) { - auto stream = complete_query_streaming(env, std::move(pending)); - if (!stream) { - return nullptr; - } - res_ref->stream = std::move(stream); - } else { - auto res = complete_query_materialized(env, std::move(pending)); - if (!res) { - return nullptr; - } - res_ref->res = std::move(res); + throw JdbcException("Invalid Input Error: Invalid statement"); } + return *stmt_ref; +} - return env->NewDirectByteBuffer(res_ref.release(), 0); +jobject _duckdb_jdbc_execute(JNIEnv *env, jclass, jobject stmt_ref_buf, jobjectArray params) { + auto &stmt_ref = get_statement(env, stmt_ref_buf); + auto conn = stmt_ref.connection.lock(); + if (!conn) { + throw JdbcException("Invalid Input Error: Attempting to execute a prepared statement after its connection was " + "closed!"); + } + auto conn_lock = lock_connection_mutex(stmt_ref.lock); + std::lock_guard guard(*conn_lock); + bool stream_results_user = conn->GetConfig().GetOption("jdbc_stream_results").value.Get(); + + auto result = execute_prepared_statement(env, stmt_ref, params, *conn); + auto holder = + complete_result(*conn, stmt_ref.connection, std::move(result), stmt_ref.statement_type, stream_results_user); + return env->NewDirectByteBuffer(holder.release(), 0); } jobject _duckdb_jdbc_execute_capi(JNIEnv *env, jclass, jobject stmt_ref_buf, jobjectArray params) { - auto stmt_ref = reinterpret_cast(env->GetDirectBufferAddress(stmt_ref_buf)); - if (!stmt_ref || !stmt_ref->stmt) { - throw InvalidInputException("Invalid statement"); - } + auto &stmt_ref = get_statement(env, stmt_ref_buf); + auto conn = lock_connection(stmt_ref.connection); + auto conn_lock = lock_connection_mutex(stmt_ref.lock); + std::lock_guard guard(*conn_lock); - auto pending = execute_prepared_statement(env, stmt_ref_buf, params, true); - if (!pending) { - return nullptr; + idx_t param_len = env->GetArrayLength(params); + if (param_len != stmt_ref.signature->parameters.GetFieldCount()) { + throw JdbcException("Invalid Input Error: Parameter count mismatch"); } - - bool stream_results = StreamsByDefault(stmt_ref->stmt->GetStatementType(), *pending); - - // The completed result is adopted into the result state machine of the C API v2 (in the same state - // it gets into when it is ready to be consumed) and is read through the C API v2. There is no way to - // construct a C API v2 result from an engine result using C API v2. - auto wrapper = make_uniq(); - wrapper->context = stmt_ref->stmt->TryGetContext(); - wrapper->statement_type = stmt_ref->stmt->GetStatementType(); - if (stream_results) { - auto stream = complete_query_streaming(env, std::move(pending)); - if (!stream) { - return nullptr; - } - wrapper->types = stream->GetTypes(); - wrapper->names = stream->GetNames(); - wrapper->properties = stream->GetStatementProperties(); - wrapper->stream = std::move(stream); - wrapper->stream_when_ready = true; - } else { - auto res = complete_query_materialized(env, std::move(pending)); - if (!res) { - return nullptr; - } - wrapper->types = res->GetTypes(); - wrapper->names = res->GetNames(); - wrapper->properties = res->GetStatementProperties(); - wrapper->handle = std::move(res); - wrapper->stream_when_ready = false; + std::vector values; + std::vector value_handles; + for (idx_t i = 0; i < param_len; i++) { + auto param = env->GetObjectArrayElement(params, i); + values.push_back(to_duckdb_value(env, param, conn->GetFactory())); + env->DeleteLocalRef(param); + value_handles.push_back(values.back().handle()); } - wrapper->metadata_available = true; - wrapper->state = duckdb::capiv2::ResultWrapperV2::State::STREAMING; - - auto out = make_uniq(duckdb::capiv2::Convert(wrapper.release())); + // the result is read through the C API v2 by the Java side + v2_result result; + v2_error err; + if (duckdb_v2_prepared_statement_execute(stmt_ref.stmt->handle(), nullptr, nullptr, value_handles.data(), + static_cast(value_handles.size()), result.out(), + err.out()) != DUCKDB_V2_ERROR_NONE) { + throw JdbcException(err.message()); + } + auto out = std::make_unique(result.release()); + // the first chunk is read to find out if the query is running without errors + if (duckdb_v2_result_fetch_chunk(out->result.get(), out->first_chunk.out(), err.out()) != DUCKDB_V2_ERROR_NONE) { + throw JdbcException(err.message()); + } + out->has_first_chunk = true; return env->NewDirectByteBuffer(out.release(), 0); } jobject _duckdb_jdbc_execute_pending(JNIEnv *env, jclass, jobject pending_ref_buf) { auto pending_ref = reinterpret_cast(env->GetDirectBufferAddress(pending_ref_buf)); if (!pending_ref || !pending_ref->pending) { - throw InvalidInputException("Invalid pending query"); + throw JdbcException("Invalid Input Error: Invalid pending query"); } - if (pending_ref->pending->HasError()) { - throw_execution_java_error(env, pending_ref->pending.get()); - pending_ref->pending = nullptr; - return nullptr; - } + auto conn = lock_connection(pending_ref->connection); + auto conn_lock = lock_connection_mutex(pending_ref->lock); + std::lock_guard guard(*conn_lock); + auto result = std::move(*pending_ref->pending); + pending_ref->pending.reset(); // the pending result was submitted from the SQL statement as written, so its type is the written type - bool stream_results = StreamsByDefault(pending_ref->pending->GetStatementType(), *pending_ref->pending); - auto res_ref = make_uniq(); - - if (pending_ref->streaming && stream_results) { - auto stream = complete_query_streaming(env, std::move(pending_ref->pending)); - if (!stream) { - return nullptr; - } - res_ref->stream = std::move(stream); - } else { - auto res = complete_query_materialized(env, std::move(pending_ref->pending)); - if (!res) { - return nullptr; - } - res_ref->res = std::move(res); - } - - return env->NewDirectByteBuffer(res_ref.release(), 0); + auto written_type = result.GetStatementType(); + auto holder = + complete_result(*conn, pending_ref->connection, std::move(result), written_type, pending_ref->streaming); + return env->NewDirectByteBuffer(holder.release(), 0); } void _duckdb_jdbc_release(JNIEnv *env, jclass, jobject stmt_ref_buf) { @@ -506,22 +485,22 @@ void _duckdb_jdbc_free_result(JNIEnv *env, jclass, jobject res_ref_buf) { } } -static jobject build_meta(JNIEnv *env, size_t column_count, size_t n_param, const duckdb::vector &names, - const duckdb::vector &types, StatementProperties properties, - const duckdb::vector ¶m_types) { +static jobject build_meta(JNIEnv *env, size_t column_count, size_t n_param, const std::vector &names, + const std::vector &types, const std::string &return_type_str, + const std::vector ¶m_types) { auto name_array = env->NewObjectArray(column_count, J_String, nullptr); auto type_array = env->NewObjectArray(column_count, J_String, nullptr); auto type_detail_array = env->NewObjectArray(column_count, J_String, nullptr); for (idx_t col_idx = 0; col_idx < column_count; col_idx++) { std::string col_name; - if (types[col_idx].id() == LogicalTypeId::ENUM) { + if (types[col_idx].GetTypeId() == cxx::LogicalTypeId::ENUM) { col_name = "ENUM"; } else { - col_name = types[col_idx].ToString(); + col_name = types[col_idx].ToText(); } - const std::string &sname = names[col_idx].GetIdentifierName(); + const std::string &sname = names[col_idx]; jstring jname = decode_charbuffer_to_jstring(env, sname.c_str(), sname.length()); env->SetObjectArrayElement(name_array, col_idx, jname); env->DeleteLocalRef(jname); @@ -538,10 +517,10 @@ static jobject build_meta(JNIEnv *env, size_t column_count, size_t n_param, cons for (idx_t param_idx = 0; param_idx < n_param; param_idx++) { std::string param_name; - if (param_types[param_idx].id() == LogicalTypeId::ENUM) { + if (param_types[param_idx].GetTypeId() == cxx::LogicalTypeId::ENUM) { param_name = "ENUM"; } else { - param_name = param_types[param_idx].ToString(); + param_name = param_types[param_idx].ToText(); } jstring jname = env->NewStringUTF(param_name.c_str()); @@ -552,7 +531,7 @@ static jobject build_meta(JNIEnv *env, size_t column_count, size_t n_param, cons env->DeleteLocalRef(jdetail); } - jstring return_type = env->NewStringUTF(StatementReturnTypeToString(properties.return_type).c_str()); + jstring return_type = env->NewStringUTF(return_type_str.c_str()); jobject res = env->NewObject(J_DuckResultSetMeta, J_DuckResultSetMeta_init, n_param, column_count, name_array, type_array, type_detail_array, return_type, param_type_array, param_type_detail_array); @@ -565,92 +544,101 @@ static jobject build_meta(JNIEnv *env, size_t column_count, size_t n_param, cons return res; } -jobject _duckdb_jdbc_query_result_meta(JNIEnv *env, jclass, jobject res_ref_buf) { - auto res_ref = (ResultHolder *)env->GetDirectBufferAddress(res_ref_buf); - if (!res_ref || (!res_ref->res && !res_ref->stream) || (res_ref->res && res_ref->res->HasError()) || - (res_ref->stream && res_ref->stream->HasError())) { - throw InvalidInputException("Invalid result set"); - } - auto n_param = 0; // no params now - duckdb::vector param_types(n_param); - - if (res_ref->res) { - auto &res = res_ref->res; - return build_meta(env, res->ColumnCount(), n_param, res->GetNames(), res->GetTypes(), - res->GetStatementProperties(), param_types); - } else if (res_ref->stream) { - auto &res = res_ref->stream; - return build_meta(env, res->ColumnCount(), n_param, res->GetNames(), res->GetTypes(), - res->GetStatementProperties(), param_types); - } else { - throw InvalidInputException("Invalid result set"); +static ResultHolder &get_result(JNIEnv *env, jobject res_ref_buf) { + auto res_ref = reinterpret_cast(env->GetDirectBufferAddress(res_ref_buf)); + if (!res_ref || (!res_ref->stream && !res_ref->materialized)) { + throw JdbcException("Invalid Input Error: Invalid result set"); } + return *res_ref; } -jobject _duckdb_jdbc_prepared_statement_meta(JNIEnv *env, jclass, jobject stmt_ref_buf) { +jobject _duckdb_jdbc_query_result_meta(JNIEnv *env, jclass, jobject res_ref_buf) { + auto &res_ref = get_result(env, res_ref_buf); + std::vector param_types; // no params now + std::vector types; + for (auto &type : res_ref.types) { + types.push_back(type.Copy()); + } + return build_meta(env, res_ref.types.size(), 0, res_ref.names, types, result_type_to_string(res_ref.result_type), + param_types); +} - auto stmt_ref = reinterpret_cast(env->GetDirectBufferAddress(stmt_ref_buf)); - if (!stmt_ref || !stmt_ref->stmt || stmt_ref->stmt->HasError()) { - throw InvalidInputException("Invalid statement"); - } - - auto &stmt = stmt_ref->stmt; - auto n_param = stmt->GetParameterCount(); - duckdb::vector param_types(n_param); - if (n_param > 0) { - for (auto &it : stmt->GetNamedParameterMap()) { - LogicalType type; - if (stmt->TryGetParameterType(it.first, type)) { - param_types[it.second - 1] = type; - } +//! The return type of a prepared statement is not known before it is executed, it is derived from its columns +static std::string prepared_return_type(const StatementHolder &stmt_ref) { + auto &output = stmt_ref.signature->output; + if (output.GetFieldCount() == 0) { + return "NOTHING"; + } + if (output.GetFieldCount() == 1 && output.GetFieldName(0) == "Count" && + output.GetFieldType(0).GetTypeId() == cxx::LogicalTypeId::BIGINT) { + switch (stmt_ref.statement_type) { + case cxx::StatementType::INSERT: + case cxx::StatementType::UPDATE: + case cxx::StatementType::DELETE: + case cxx::StatementType::COPY: + case cxx::StatementType::MERGE_INTO: + return "CHANGED_ROWS"; + default: + break; } } - - return build_meta(env, stmt->ColumnCount(), n_param, stmt->GetNames(), stmt->GetTypes(), - stmt->GetStatementProperties(), param_types); + return "QUERY_RESULT"; } -jobject ProcessVector(JNIEnv *env, Connection *conn_ref, Vector &vec, idx_t row_count); +jobject _duckdb_jdbc_prepared_statement_meta(JNIEnv *env, jclass, jobject stmt_ref_buf) { + auto &stmt_ref = get_statement(env, stmt_ref_buf); -jobjectArray _duckdb_jdbc_fetch(JNIEnv *env, jclass, jobject res_ref_buf, jobject conn_ref_buf) { - auto res_ref = reinterpret_cast(env->GetDirectBufferAddress(res_ref_buf)); - if (!res_ref || (!res_ref->res && !res_ref->stream) || (res_ref->res && res_ref->res->HasError()) || - (res_ref->stream && res_ref->stream->HasError())) { - throw InvalidInputException("Invalid result set"); + auto &signature = *stmt_ref.signature; + auto n_param = signature.parameters.GetFieldCount(); + std::vector param_types; + for (idx_t i = 0; i < n_param; i++) { + param_types.push_back(signature.parameters.GetFieldType(i)); } - - auto conn_ref = get_connection(env, conn_ref_buf); - if (conn_ref == nullptr) { - return nullptr; + std::vector names; + std::vector types; + for (idx_t i = 0; i < signature.output.GetFieldCount(); i++) { + names.emplace_back(signature.output.GetFieldName(i)); + types.push_back(signature.output.GetFieldType(i)); } - if (res_ref->res) { - res_ref->chunk = res_ref->res->Fetch(); - if (res_ref->res->HasError()) { - throw_execution_java_error(env, res_ref->res.get()); - return nullptr; - } - } else if (res_ref->stream) { - res_ref->chunk = res_ref->stream->Fetch(); - if (res_ref->stream->HasError()) { - throw_execution_java_error(env, res_ref->stream.get()); - return nullptr; + return build_meta(env, types.size(), n_param, names, types, prepared_return_type(stmt_ref), param_types); +} + +jobject ProcessVector(JNIEnv *env, cxx::Factory &factory, cxx::Vector &vec, idx_t row_count); + +jobjectArray _duckdb_jdbc_fetch(JNIEnv *env, jclass, jobject res_ref_buf, jobject conn_ref_buf) { + auto &res_ref = get_result(env, res_ref_buf); + auto &conn = get_connection(env, conn_ref_buf); + auto &factory = conn.GetFactory(); + + res_ref.chunk.reset(); + if (res_ref.materialized) { + auto &data = *res_ref.materialized; + auto chunk = factory.CreateDataChunk(res_ref.types); + if (data.collection->Scan(*data.shared_state, *data.worker_state, chunk) && chunk.GetRowCount() > 0) { + res_ref.chunk.emplace(std::move(chunk)); } + } else if (res_ref.first_chunk) { + res_ref.chunk.emplace(std::move(*res_ref.first_chunk)); + res_ref.first_chunk.reset(); } else { - throw InvalidInputException("Invalid result set"); + auto chunk = res_ref.stream->FetchChunk(); + if (chunk) { + res_ref.chunk.emplace(std::move(chunk)); + } } - if (!res_ref->chunk) { - res_ref->chunk = make_uniq(); + if (!res_ref.chunk) { + return env->NewObjectArray(0, J_DuckVector, nullptr); } - auto row_count = res_ref->chunk->size(); - jobjectArray vec_array = - reinterpret_cast(env->NewObjectArray(res_ref->chunk->ColumnCount(), J_DuckVector, nullptr)); + auto row_count = res_ref.chunk->GetRowCount(); + auto column_count = res_ref.chunk->GetVectorCount(); + jobjectArray vec_array = reinterpret_cast(env->NewObjectArray(column_count, J_DuckVector, nullptr)); - for (idx_t col_idx = 0; col_idx < res_ref->chunk->ColumnCount(); col_idx++) { - auto &vec = res_ref->chunk->data[col_idx]; + for (idx_t col_idx = 0; col_idx < column_count; col_idx++) { + auto vec = res_ref.chunk->GetVector(col_idx); - jobject jvec = ProcessVector(env, conn_ref, vec, row_count); + jobject jvec = ProcessVector(env, factory, vec, row_count); env->SetObjectArrayElement(vec_array, col_idx, jvec); env->DeleteLocalRef(jvec); @@ -659,36 +647,38 @@ jobjectArray _duckdb_jdbc_fetch(JNIEnv *env, jclass, jobject res_ref_buf, jobjec return vec_array; } +//! Casts the vector to strings, the chunk that holds the result vector is returned to keep the result alive +static cxx::DataChunk cast_to_strings(cxx::Factory &factory, const cxx::Vector &vec) { + std::vector types; + types.push_back(factory.CreateType(cxx::LogicalTypeId::VARCHAR)); + auto chunk = factory.CreateDataChunk(types); + auto target = chunk.GetVector(0); + vec.Cast(factory, target); + target.Flatten(); + return chunk; +} + jobjectArray _duckdb_jdbc_cast_result_to_strings(JNIEnv *env, jclass, jobject res_ref_buf, jobject conn_ref_buf, jlong col_idx) { - auto res_ref = reinterpret_cast(env->GetDirectBufferAddress(res_ref_buf)); - if (!res_ref || (!res_ref->res && !res_ref->stream) || (res_ref->res && res_ref->res->HasError()) || - (res_ref->stream && res_ref->stream->HasError())) { - throw InvalidInputException("Invalid result set"); - } - - if (!res_ref->chunk) { + auto &res_ref = get_result(env, res_ref_buf); + if (!res_ref.chunk) { return nullptr; } + auto &conn = get_connection(env, conn_ref_buf); - auto conn_ref = get_connection(env, conn_ref_buf); - if (conn_ref == nullptr) { - return nullptr; - } - - auto row_count = res_ref->chunk->size(); - auto &complex_vec = res_ref->chunk->data[col_idx]; - Vector vec(LogicalType::VARCHAR); - VectorOperations::Cast(*conn_ref->context, complex_vec, vec, row_count); + auto row_count = res_ref.chunk->GetRowCount(); + auto complex_vec = res_ref.chunk->GetVector(static_cast(col_idx)); + auto cast_chunk = cast_to_strings(conn.GetFactory(), complex_vec); + auto vec = cast_chunk.GetVector(0); + auto view = vec.GetView(); jobjectArray string_data = env->NewObjectArray(row_count, J_String, nullptr); for (idx_t row_idx = 0; row_idx < row_count; row_idx++) { - if (FlatVector::IsNull(vec, row_idx)) { + if (!view.IsValid(row_idx)) { continue; } - const string_t *vec_data = FlatVector::GetData(vec); - auto d_str = vec_data[row_idx]; - auto j_str = decode_charbuffer_to_jstring(env, d_str.GetData(), d_str.GetSize()); + auto d_str = view.Data()[view.SelAt(row_idx)].view(); + auto j_str = decode_charbuffer_to_jstring(env, d_str.data(), d_str.size()); env->SetObjectArrayElement(string_data, row_idx, j_str); } @@ -696,22 +686,51 @@ jobjectArray _duckdb_jdbc_cast_result_to_strings(JNIEnv *env, jclass, jobject re } template -static jobject make_vec_data_buf(JNIEnv *env, Vector &vec, idx_t row_count) { - T *vec_data = FlatVector::GetDataMutable(vec); +static jobject make_vec_data_buf(JNIEnv *env, cxx::Vector &vec, idx_t row_count) { + T *vec_data = vec.GetDataMutable(); idx_t len = row_count * sizeof(T); return make_data_buf(env, vec_data, len); } -jobject ProcessVector(JNIEnv *env, Connection *conn_ref, Vector &vec, idx_t row_count) { - if (vec.GetVectorType() != VectorType::FLAT_VECTOR) { +//! The type of the entries of a MAP, that are STRUCTs of the keys and the values +static cxx::LogicalType map_entry_type(cxx::Factory &factory, const cxx::LogicalType &map_type) { + return factory.ParseType("STRUCT(\"key\" " + map_type.GetMapKeyType().ToText() + ", \"value\" " + + map_type.GetMapValueType().ToText() + ")"); +} + +//! Creates a Java vector of the specified type from a single value +static jobject process_value(JNIEnv *env, cxx::Factory &factory, const cxx::Value &value); + +static jobject process_vector_with_type(JNIEnv *env, cxx::Factory &factory, cxx::Vector &vec, + const cxx::LogicalType &type, idx_t row_count); + +jobject ProcessVector(JNIEnv *env, cxx::Factory &factory, cxx::Vector &vec, idx_t row_count) { + auto type = vec.GetLogicalType(); + return process_vector_with_type(env, factory, vec, type, row_count); +} + +static jobject process_vector_with_type(JNIEnv *env, cxx::Factory &factory, cxx::Vector &vec, + const cxx::LogicalType &type, idx_t row_count) { + using cxx::LogicalTypeId; + auto type_id = type.GetTypeId(); + bool is_variant = type_id == LogicalTypeId::VARIANT; + if (vec.GetVectorType() != cxx::VectorType::FLAT && !is_variant) { vec.Flatten(); } - jstring type_str = env->NewStringUTF(type_to_jduckdb_type(vec.GetType()).c_str()); + cxx::VectorView view {}; + if (!is_variant) { + view = vec.GetView(); + } + jstring type_str = env->NewStringUTF(type_to_jduckdb_type(type).c_str()); // construct nullmask jbooleanArray null_array = env->NewBooleanArray(row_count); jboolean *null_unique_array = env->GetBooleanArrayElements(null_array, nullptr); for (idx_t row_idx = 0; row_idx < row_count; row_idx++) { - null_unique_array[row_idx] = FlatVector::IsNull(vec, row_idx); + if (is_variant) { + null_unique_array[row_idx] = vec.GetValue(row_idx).IsNull(); + } else { + null_unique_array[row_idx] = !view.IsValid(row_idx); + } } env->ReleaseBooleanArrayElements(null_array, null_unique_array, 0); @@ -719,10 +738,13 @@ jobject ProcessVector(JNIEnv *env, Connection *conn_ref, Vector &vec, idx_t row_ jobject constlen_data = nullptr; jobjectArray varlen_data = nullptr; - Vector *string_vec = &vec; - duckdb::unique_ptr cast_vec; + // the source vector must not be modified, it is a part of the result chunk that can be cast again + // in getString() (with this vector as a child of a nested type) + std::optional cast_chunk; + std::optional cast_vec; + cxx::VectorView string_view_data = view; - switch (vec.GetType().id()) { + switch (type_id) { case LogicalTypeId::BOOLEAN: constlen_data = make_vec_data_buf(env, vec, row_count); break; @@ -751,32 +773,30 @@ jobject ProcessVector(JNIEnv *env, Connection *conn_ref, Vector &vec, idx_t row_ constlen_data = make_vec_data_buf(env, vec, row_count); break; case LogicalTypeId::HUGEINT: - constlen_data = make_vec_data_buf(env, vec, row_count); + constlen_data = make_vec_data_buf(env, vec, row_count); break; case LogicalTypeId::UHUGEINT: - constlen_data = make_vec_data_buf(env, vec, row_count); + constlen_data = make_vec_data_buf(env, vec, row_count); break; case LogicalTypeId::FLOAT: constlen_data = make_vec_data_buf(env, vec, row_count); break; case LogicalTypeId::DECIMAL: { - auto physical_type = vec.GetType().InternalType(); - - switch (physical_type) { - case PhysicalType::INT16: + switch (type.GetDecimalInternalTypeId()) { + case LogicalTypeId::SMALLINT: constlen_data = make_vec_data_buf(env, vec, row_count); break; - case PhysicalType::INT32: + case LogicalTypeId::INTEGER: constlen_data = make_vec_data_buf(env, vec, row_count); break; - case PhysicalType::INT64: + case LogicalTypeId::BIGINT: constlen_data = make_vec_data_buf(env, vec, row_count); break; - case PhysicalType::INT128: - constlen_data = make_vec_data_buf(env, vec, row_count); + case LogicalTypeId::HUGEINT: + constlen_data = make_vec_data_buf(env, vec, row_count); break; default: - throw InternalException("Unimplemented physical type for decimal"); + throw JdbcException("Internal Error: Unimplemented physical type for decimal"); } break; } @@ -784,31 +804,31 @@ jobject ProcessVector(JNIEnv *env, Connection *conn_ref, Vector &vec, idx_t row_ constlen_data = make_vec_data_buf(env, vec, row_count); break; case LogicalTypeId::DATE: - constlen_data = make_vec_data_buf(env, vec, row_count); + constlen_data = make_vec_data_buf(env, vec, row_count); break; case LogicalTypeId::TIME: - constlen_data = make_vec_data_buf(env, vec, row_count); + constlen_data = make_vec_data_buf(env, vec, row_count); break; case LogicalTypeId::TIME_NS: - constlen_data = make_vec_data_buf(env, vec, row_count); + constlen_data = make_vec_data_buf(env, vec, row_count); break; case LogicalTypeId::TIME_TZ: - constlen_data = make_vec_data_buf(env, vec, row_count); + constlen_data = make_vec_data_buf(env, vec, row_count); break; case LogicalTypeId::TIMESTAMP_SEC: case LogicalTypeId::TIMESTAMP_MS: case LogicalTypeId::TIMESTAMP: case LogicalTypeId::TIMESTAMP_NS: case LogicalTypeId::TIMESTAMP_TZ: - constlen_data = make_vec_data_buf(env, vec, row_count); + constlen_data = make_vec_data_buf(env, vec, row_count); break; case LogicalTypeId::ENUM: varlen_data = env->NewObjectArray(row_count, J_String, nullptr); for (idx_t row_idx = 0; row_idx < row_count; row_idx++) { - if (FlatVector::IsNull(vec, row_idx)) { + if (!view.IsValid(row_idx)) { continue; } - auto dstr = vec.GetValue(row_idx).ToString(); + auto dstr = vec.GetValue(row_idx).ToText(); jstring jstr = env->NewStringUTF(dstr.c_str()); env->SetObjectArrayElement(varlen_data, row_idx, jstr); env->DeleteLocalRef(jstr); @@ -819,23 +839,33 @@ jobject ProcessVector(JNIEnv *env, Connection *conn_ref, Vector &vec, idx_t row_ case LogicalTypeId::TUPLE: { varlen_data = env->NewObjectArray(row_count, J_DuckStruct, nullptr); - auto &entries = StructVector::GetEntries(vec); - auto columns = env->NewObjectArray(entries.size(), J_DuckVector, nullptr); - auto names = env->NewObjectArray(entries.size(), J_String, nullptr); - - for (idx_t entry_i = 0; entry_i < entries.size(); entry_i++) { - jobject j_vec = ProcessVector(env, conn_ref, entries[entry_i], row_count); + idx_t child_count = vec.GetChildCount(); + auto columns = env->NewObjectArray(child_count, J_DuckVector, nullptr); + auto names = env->NewObjectArray(child_count, J_String, nullptr); + + for (idx_t entry_i = 0; entry_i < child_count; entry_i++) { + auto child = vec.GetChild(entry_i); + std::string name; + if (type_id == LogicalTypeId::UNION) { + // the first entry of a union is its tag, that has no name + name = entry_i == 0 ? "" : type.GetUnionMemberName(entry_i - 1); + } else { + name = type.GetStructChildName(entry_i); + // TUPLE members are unnamed, use the positional names synthesized by DuckDB: "element1", ... + if (name.empty() && type_id == LogicalTypeId::TUPLE) { + name = "element" + std::to_string(entry_i + 1); + } + } + jobject j_vec = ProcessVector(env, factory, child, row_count); env->SetObjectArrayElement(columns, entry_i, j_vec); env->DeleteLocalRef(j_vec); - // TUPLE members are unnamed, use the positional names synthesized by DuckDB: "element1", "element2", ... - auto &child_name = StructType::GetChildName(vec.GetType(), entry_i); - std::string name = child_name.empty() ? TupleType::GetChildName(entry_i) : child_name.GetIdentifierName(); jstring jstr = env->NewStringUTF(name.c_str()); env->SetObjectArrayElement(names, entry_i, jstr); env->DeleteLocalRef(jstr); } + auto type_text = type.ToText(); for (idx_t row_idx = 0; row_idx < row_count; row_idx++) { - jstring jstr = env->NewStringUTF(vec.GetType().ToString().c_str()); + jstring jstr = env->NewStringUTF(type_text.c_str()); jobject jstruct = env->NewObject(J_DuckStruct, J_DuckStruct_init, names, columns, row_idx, jstr); env->SetObjectArrayElement(varlen_data, row_idx, jstruct); env->DeleteLocalRef(jstruct); @@ -851,16 +881,15 @@ jobject ProcessVector(JNIEnv *env, Connection *conn_ref, Vector &vec, idx_t row_ varlen_data = env->NewObjectArray(row_count, J_ByteArray, nullptr); for (idx_t row_idx = 0; row_idx < row_count; row_idx++) { - if (FlatVector::IsNull(vec, row_idx)) { + if (!view.IsValid(row_idx)) { continue; } - const string_t *vec_data = FlatVector::GetData(vec); - const string_t d_str = vec_data[row_idx]; + auto d_str = view.Data()[view.SelAt(row_idx)].view(); - auto j_arr = env->NewByteArray(d_str.GetSize()); + auto j_arr = env->NewByteArray(d_str.size()); auto j_arr_el = env->GetByteArrayElements(j_arr, nullptr); - memcpy(j_arr_el, d_str.GetData(), d_str.GetSize()); + memcpy(j_arr_el, d_str.data(), d_str.size()); env->ReleaseByteArrayElements(j_arr, j_arr_el, 0); env->SetObjectArrayElement(varlen_data, row_idx, j_arr); @@ -868,18 +897,17 @@ jobject ProcessVector(JNIEnv *env, Connection *conn_ref, Vector &vec, idx_t row_ } break; case LogicalTypeId::UUID: - constlen_data = make_vec_data_buf(env, vec, row_count); + constlen_data = make_vec_data_buf(env, vec, row_count); break; case LogicalTypeId::ARRAY: { varlen_data = env->NewObjectArray(row_count, J_DuckArray, nullptr); - auto &array_vector = ArrayVector::GetChildMutable(vec); - auto total_size = row_count * ArrayType::GetSize(vec.GetType()); - jobject j_vec = ProcessVector(env, conn_ref, array_vector, total_size); - - auto limit = ArrayType::GetSize(vec.GetType()); + auto array_vector = vec.GetChild(0); + auto limit = type.GetArraySize(); + auto total_size = row_count * limit; + jobject j_vec = ProcessVector(env, factory, array_vector, total_size); for (idx_t row_idx = 0; row_idx < row_count; row_idx++) { - if (FlatVector::IsNull(vec, row_idx)) { + if (!view.IsValid(row_idx)) { continue; } @@ -897,19 +925,32 @@ jobject ProcessVector(JNIEnv *env, Connection *conn_ref, Vector &vec, idx_t row_ case LogicalTypeId::LIST: { varlen_data = env->NewObjectArray(row_count, J_DuckArray, nullptr); - auto list_entries = FlatVector::GetData(vec); + auto list_entries = view.Data(); - auto list_size = ListVector::GetListSize(vec); - auto &list_vector = ListVector::GetChildMutable(vec); - auto j_vec = ProcessVector(env, conn_ref, list_vector, list_size); + // the child vector has the capacity of the list, the size is the end of the last list + idx_t list_size = 0; + for (idx_t row_idx = 0; row_idx < row_count; row_idx++) { + if (!view.IsValid(row_idx)) { + continue; + } + auto &entry = list_entries[view.SelAt(row_idx)]; + list_size = std::max(list_size, entry.offset + entry.length); + } + auto list_vector = vec.GetChild(0); + jobject j_vec; + if (type_id == LogicalTypeId::MAP) { + j_vec = process_vector_with_type(env, factory, list_vector, map_entry_type(factory, type), list_size); + } else { + j_vec = process_vector_with_type(env, factory, list_vector, type.GetListChildType(), list_size); + } for (idx_t row_idx = 0; row_idx < row_count; row_idx++) { - if (FlatVector::IsNull(vec, row_idx)) { + if (!view.IsValid(row_idx)) { continue; } - auto offset = list_entries[row_idx].offset; - auto limit = list_entries[row_idx].length; + auto offset = list_entries[view.SelAt(row_idx)].offset; + auto limit = list_entries[view.SelAt(row_idx)].length; auto j_obj = env->NewObject(J_DuckArray, J_DuckArray_init, j_vec, offset, limit); @@ -920,45 +961,32 @@ jobject ProcessVector(JNIEnv *env, Connection *conn_ref, Vector &vec, idx_t row_ break; } case LogicalTypeId::VARIANT: { - RecursiveUnifiedVectorFormat format; - Vector::RecursiveToUnifiedFormat(vec, format); - UnifiedVariantVectorData vector_data(format); varlen_data = env->NewObjectArray(row_count, J_Object, nullptr); for (idx_t row_idx = 0; row_idx < row_count; row_idx++) { - auto variant_val = VariantUtils::ConvertVariantToValue(vector_data, row_idx, 0); + auto variant_val = vec.GetValue(row_idx).VariantToValue(); if (variant_val.IsNull()) { continue; } - Vector variant_vec(variant_val.type()); - variant_vec.SetValue(0, variant_val); - jobject variant_j_vec = ProcessVector(env, conn_ref, variant_vec, 1); - env->CallVoidMethod(variant_j_vec, J_DuckVector_retainConstlenData); - check_java_exception_and_rethrow(env); + jobject variant_j_vec = process_value(env, factory, variant_val); env->SetObjectArrayElement(varlen_data, row_idx, variant_j_vec); env->DeleteLocalRef(variant_j_vec); } break; } default: { - // the source vector must not be modified, it is a part of the result chunk that can be cast again - // in getString() (with this vector as a child of a nested type) - cast_vec = make_uniq(LogicalType::VARCHAR); - VectorOperations::Cast(*conn_ref->context, vec, *cast_vec, row_count); - if (cast_vec->GetVectorType() != VectorType::FLAT_VECTOR) { - cast_vec->Flatten(); - } - string_vec = cast_vec.get(); + cast_chunk.emplace(cast_to_strings(factory, vec)); + cast_vec.emplace(cast_chunk->GetVector(0)); + string_view_data = cast_vec->GetView(); // fall through on purpose } case LogicalTypeId::VARCHAR: varlen_data = env->NewObjectArray(row_count, J_String, nullptr); for (idx_t row_idx = 0; row_idx < row_count; row_idx++) { - if (FlatVector::IsNull(*string_vec, row_idx)) { + if (!string_view_data.IsValid(row_idx)) { continue; } - const string_t *vec_data = FlatVector::GetData(*string_vec); - const string_t d_str = vec_data[row_idx]; - auto j_str = decode_charbuffer_to_jstring(env, d_str.GetData(), d_str.GetSize()); + auto d_str = string_view_data.Data()[string_view_data.SelAt(row_idx)].view(); + auto j_str = decode_charbuffer_to_jstring(env, d_str.data(), d_str.size()); env->SetObjectArrayElement(varlen_data, row_idx, j_str); env->DeleteLocalRef(j_str); } @@ -980,205 +1008,276 @@ jobject ProcessVector(JNIEnv *env, Connection *conn_ref, Vector &vec, idx_t row_ return jvec; } -jint _duckdb_jdbc_fetch_size(JNIEnv *, jclass) { - return STANDARD_VECTOR_SIZE; +static jobject process_value(JNIEnv *env, cxx::Factory &factory, const cxx::Value &value) { + auto type = value.GetLogicalType(); + std::vector types; + types.push_back(type.Copy()); + auto chunk = factory.CreateDataChunk(types); + auto vec = chunk.GetVector(0); + vec.SetSize(1); + vec.SetValue(0, value); + jobject j_vec = ProcessVector(env, factory, vec, 1); + // the fixed-size data of the Java vector points into the chunk, that is destroyed here, so it is copied + env->CallVoidMethod(j_vec, J_DuckVector_retainConstlenData); + check_java_exception_and_rethrow(env); + return j_vec; } -jobject _duckdb_jdbc_create_appender(JNIEnv *env, jclass, jobject conn_ref_buf, jbyteArray schema_name_j, - jbyteArray table_name_j) { +jint _duckdb_jdbc_fetch_size(JNIEnv *env, jclass cls) { + // the size of the chunks of the engine + return static_cast(Java_org_duckdb_DuckDBBindings_duckdb_1vector_1size(env, cls)); +} - auto conn_ref = get_connection(env, conn_ref_buf); - if (!conn_ref) { - return nullptr; +/** + * An appender of the rows that are appended one value at a time. The values are collected into a data chunk + * that is appended to the table when it is full or the appender is flushed. + */ +struct RowAppender { + std::shared_ptr connection; + std::optional appender; + std::optional chunk; + std::vector column_ids; + idx_t capacity = 0; + //! The index of the row that is being appended, and of the column to append to + idx_t row = 0; + idx_t column = 0; + bool in_row = false; + bool closed = false; + + cxx::Factory &factory() { + return connection->GetFactory(); + } + + void reset_chunk() { + chunk->Clear(); + for (idx_t i = 0; i < column_ids.size(); i++) { + chunk->GetVector(i).SetSize(capacity); + } + row = 0; + column = 0; + } + + //! Appends the collected rows to the table + void collect() { + if (row == 0) { + return; + } + for (idx_t i = 0; i < column_ids.size(); i++) { + chunk->GetVector(i).SetSize(row); + } + try { + appender->AppendChunk(*chunk); + } catch (...) { + reset_chunk(); + throw; + } + reset_chunk(); } +}; + +jobject _duckdb_jdbc_create_appender(JNIEnv *env, jclass, jobject conn_ref_buf, jbyteArray schema_name_j, + jbyteArray table_name_j) { + auto conn_holder = get_connection_ref(env, conn_ref_buf); + auto &conn = get_connection(env, conn_ref_buf); auto schema_name = jbyteArray_to_string(env, schema_name_j); auto table_name = jbyteArray_to_string(env, table_name_j); - auto appender = new Appender(*conn_ref, Identifier(schema_name), Identifier(table_name)); - return env->NewDirectByteBuffer(appender, 0); + + auto appender = std::make_unique(); + appender->connection = conn_holder->connection; + std::string table = schema_name.empty() ? quote_identifier(table_name) + : quote_identifier(schema_name) + "." + quote_identifier(table_name); + appender->appender.emplace(conn, table); + auto &types = appender->appender->ColumnTypes(); + for (auto &type : types) { + appender->column_ids.push_back(type.GetTypeId()); + } + appender->chunk.emplace(conn.GetFactory().CreateDataChunk(types)); + appender->capacity = appender->chunk->GetCapacity(); + appender->reset_chunk(); + return env->NewDirectByteBuffer(appender.release(), 0); } -static Appender *get_appender(JNIEnv *env, jobject appender_ref_buf) { - auto appender_ref = (Appender *)env->GetDirectBufferAddress(appender_ref_buf); - if (!appender_ref) { - throw InvalidInputException("Invalid appender"); +static RowAppender &get_appender(JNIEnv *env, jobject appender_ref_buf) { + auto appender_ref = (RowAppender *)env->GetDirectBufferAddress(appender_ref_buf); + if (!appender_ref || appender_ref->closed) { + throw JdbcException("Invalid Input Error: Invalid appender"); } - return appender_ref; + return *appender_ref; } void _duckdb_jdbc_appender_begin_row(JNIEnv *env, jclass, jobject appender_ref_buf) { - get_appender(env, appender_ref_buf)->BeginRow(); + // the values are appended to the columns in order, no matter how many times the row is begun + get_appender(env, appender_ref_buf).in_row = true; } void _duckdb_jdbc_appender_end_row(JNIEnv *env, jclass, jobject appender_ref_buf) { - get_appender(env, appender_ref_buf)->EndRow(); + auto &appender = get_appender(env, appender_ref_buf); + if (appender.column != appender.column_ids.size()) { + // the values of the incomplete row are dropped + appender.column = 0; + appender.in_row = false; + throw JdbcException("Invalid Input Error: Call to EndRow before all columns have been appended to"); + } + appender.in_row = false; + appender.column = 0; + appender.row++; + if (appender.row == appender.capacity) { + appender.collect(); + } } void _duckdb_jdbc_appender_flush(JNIEnv *env, jclass, jobject appender_ref_buf) { - get_appender(env, appender_ref_buf)->Flush(); + auto &appender = get_appender(env, appender_ref_buf); + appender.collect(); + appender.appender->Flush(); } void _duckdb_jdbc_appender_close(JNIEnv *env, jclass, jobject appender_ref_buf) { - auto appender = get_appender(env, appender_ref_buf); - appender->Close(); - delete appender; + auto appender = (RowAppender *)env->GetDirectBufferAddress(appender_ref_buf); + if (!appender) { + throw JdbcException("Invalid Input Error: Invalid appender"); + } + std::unique_ptr owned(appender); + if (owned->closed) { + return; + } + owned->closed = true; + owned->collect(); + owned->appender->Flush(); +} + +//! The vector of the column that is appended to +static cxx::Vector appender_vector(RowAppender &appender) { + if (appender.column >= appender.column_ids.size()) { + throw JdbcException("Invalid Input Error: Too many appends for chunk!"); + } + return appender.chunk->GetVector(appender.column); +} + +//! Appends the value to the column, that is cast to the type of the column +static void append_value(RowAppender &appender, const cxx::Value &value) { + auto vec = appender_vector(appender); + vec.SetValue(appender.row, value); + appender.column++; +} + +//! Appends the primitive value directly if the column has the same type, otherwise the value is cast +template +static void append_primitive(RowAppender &appender, cxx::LogicalTypeId id, T value) { + if (appender.column < appender.column_ids.size() && appender.column_ids[appender.column] == id) { + auto vec = appender.chunk->GetVector(appender.column); + vec.GetDataMutable()[appender.row] = value; + vec.GetValidityMutable().SetValid(appender.row); + appender.column++; + return; + } + append_value(appender, cxx::Value::Create(appender.factory(), value)); } void _duckdb_jdbc_appender_append_boolean(JNIEnv *env, jclass, jobject appender_ref_buf, jboolean value) { - get_appender(env, appender_ref_buf)->Append((bool)value); + append_primitive(get_appender(env, appender_ref_buf), cxx::LogicalTypeId::BOOLEAN, value != 0); } void _duckdb_jdbc_appender_append_byte(JNIEnv *env, jclass, jobject appender_ref_buf, jbyte value) { - get_appender(env, appender_ref_buf)->Append((int8_t)value); + append_primitive(get_appender(env, appender_ref_buf), cxx::LogicalTypeId::TINYINT, (int8_t)value); } void _duckdb_jdbc_appender_append_short(JNIEnv *env, jclass, jobject appender_ref_buf, jshort value) { - get_appender(env, appender_ref_buf)->Append((int16_t)value); + append_primitive(get_appender(env, appender_ref_buf), cxx::LogicalTypeId::SMALLINT, (int16_t)value); } void _duckdb_jdbc_appender_append_int(JNIEnv *env, jclass, jobject appender_ref_buf, jint value) { - get_appender(env, appender_ref_buf)->Append((int32_t)value); + append_primitive(get_appender(env, appender_ref_buf), cxx::LogicalTypeId::INTEGER, (int32_t)value); } void _duckdb_jdbc_appender_append_long(JNIEnv *env, jclass, jobject appender_ref_buf, jlong value) { - get_appender(env, appender_ref_buf)->Append((int64_t)value); + append_primitive(get_appender(env, appender_ref_buf), cxx::LogicalTypeId::BIGINT, (int64_t)value); } void _duckdb_jdbc_appender_append_float(JNIEnv *env, jclass, jobject appender_ref_buf, jfloat value) { - get_appender(env, appender_ref_buf)->Append((float)value); + append_primitive(get_appender(env, appender_ref_buf), cxx::LogicalTypeId::FLOAT, (float)value); } void _duckdb_jdbc_appender_append_double(JNIEnv *env, jclass, jobject appender_ref_buf, jdouble value) { - get_appender(env, appender_ref_buf)->Append((double)value); + append_primitive(get_appender(env, appender_ref_buf), cxx::LogicalTypeId::DOUBLE, (double)value); } void _duckdb_jdbc_appender_append_timestamp(JNIEnv *env, jclass, jobject appender_ref_buf, jlong value) { - timestamp_t timestamp = timestamp_t((int64_t)value); - get_appender(env, appender_ref_buf)->Append(Value::TIMESTAMP(timestamp)); + auto &appender = get_appender(env, appender_ref_buf); + append_value(appender, cxx::Value::Create(appender.factory(), cxx::timestamp_t {static_cast(value)})); } void _duckdb_jdbc_appender_append_decimal(JNIEnv *env, jclass, jobject appender_ref_buf, jobject value) { - Value val = create_value_from_bigdecimal(env, value); - get_appender(env, appender_ref_buf)->Append(val); + auto &appender = get_appender(env, appender_ref_buf); + append_value(appender, create_value_from_bigdecimal(env, value, appender.factory())); +} + +static void append_null(RowAppender &appender) { + auto vec = appender_vector(appender); + vec.SetNull(appender.row); + appender.column++; } void _duckdb_jdbc_appender_append_string(JNIEnv *env, jclass, jobject appender_ref_buf, jbyteArray value) { + auto &appender = get_appender(env, appender_ref_buf); if (env->IsSameObject(value, NULL)) { - get_appender(env, appender_ref_buf)->Append(nullptr); + append_null(appender); return; } auto string_value = jbyteArray_to_string(env, value); - get_appender(env, appender_ref_buf)->Append(string_value.c_str()); + append_value(appender, cxx::Value::Create(appender.factory(), cxx::varchar_t(string_value))); } void _duckdb_jdbc_appender_append_bytes(JNIEnv *env, jclass, jobject appender_ref_buf, jbyteArray value) { + auto &appender = get_appender(env, appender_ref_buf); if (env->IsSameObject(value, NULL)) { - get_appender(env, appender_ref_buf)->Append(nullptr); + append_null(appender); return; } auto string_value = jbyteArray_to_string(env, value); - get_appender(env, appender_ref_buf)->Append(Value::BLOB_RAW(string_value)); + append_value(appender, cxx::Value::Create(appender.factory(), cxx::blob_t(string_value))); } void _duckdb_jdbc_appender_append_null(JNIEnv *env, jclass, jobject appender_ref_buf) { - get_appender(env, appender_ref_buf)->Append(nullptr); + append_null(get_appender(env, appender_ref_buf)); } jlong _duckdb_jdbc_arrow_stream(JNIEnv *env, jclass, jobject res_ref_buf, jobject conn_ref_buf, jlong batch_size) { if (!res_ref_buf) { - throw InvalidInputException("Invalid result set"); - } - auto res_ref = reinterpret_cast(env->GetDirectBufferAddress(res_ref_buf)); - if (!res_ref || (!res_ref->res && !res_ref->stream) || (res_ref->res && res_ref->res->HasError()) || - (res_ref->stream && res_ref->stream->HasError())) { - throw InvalidInputException("Invalid result set"); + throw JdbcException("Invalid Input Error: Invalid result set"); } + auto &res_ref = get_result(env, res_ref_buf); if (batch_size <= 0) { - throw InvalidInputException("Arrow batch size must be greater than 0"); + throw JdbcException("Invalid Input Error: Arrow batch size must be greater than 0"); } auto conn_holder = get_connection_ref(env, conn_ref_buf); - - auto state = make_shared_ptr(std::move(res_ref->res), std::move(res_ref->stream), - static_cast(batch_size)); - res_ref->chunk = nullptr; - conn_holder->track_arrow_stream(state); - return reinterpret_cast(JavaResultArrowStream::Export(std::move(state))); + std::lock_guard guard(*conn_holder->lock); + res_ref.chunk.reset(); + return reinterpret_cast(create_result_arrow_stream(*conn_holder, res_ref, static_cast(batch_size))); } -class JavaArrowScanFactory : public ArrowScanFactory { -public: - explicit JavaArrowScanFactory(duckdb::shared_ptr state_p) : state(std::move(state_p)) { - } - - void GetSchema(ArrowSchema &schema) override { - state->GetSchema(schema); - } - - duckdb::unique_ptr ProduceStream(ArrowStreamParameters &) override { - return state->Take(); - } - -private: - duckdb::shared_ptr state; -}; - void _duckdb_jdbc_arrow_register(JNIEnv *env, jclass, jobject conn_ref_buf, jlong arrow_array_stream_pointer, jbyteArray name_j) { - auto conn = get_connection(env, conn_ref_buf); - if (conn == nullptr) { - return; - } auto conn_holder = get_connection_ref(env, conn_ref_buf); auto name = jbyteArray_to_string(env, name_j); auto arrow_array_stream = reinterpret_cast(arrow_array_stream_pointer); if (!arrow_array_stream || !arrow_array_stream->release) { - throw InvalidInputException("This stream has been released"); - } - - auto state = make_shared_ptr(arrow_array_stream); - conn_holder->track_arrow_stream(state); - auto factory = make_shared_ptr(std::move(state)); - // construct the `arrow_scan_dumb(...)` function expression - auto scan = make_uniq(); - scan->function = - make_uniq("arrow_scan_dumb", duckdb::vector>()); - scan->bind_info = std::move(factory); - // construct the `SELECT * FROM arrow_scan_dumb(...)` statement - auto node = make_uniq(); - node->select_list.push_back(make_uniq()); - node->from_table = std::move(scan); - auto select = make_uniq(); - select->node = std::move(node); - // construct the `CREATE TEMP VIEW AS` statement using the select statement - auto info = make_uniq(); - info->query = std::move(select); - info->temporary = true; - info->SetQualifiedName(QualifiedName(Identifier(), Identifier::InvalidSchema(), Identifier(name))); - info->on_conflict = OnCreateConflict::REPLACE_ON_CONFLICT; - auto statement = make_uniq(); - statement->info = std::move(info); - // execute the CREATE VIEW - conn->Query(std::move(statement))->ThrowIfError("Failed to create view '" + name + "': "); + throw JdbcException("Invalid Input Error: This stream has been released"); + } + register_arrow_stream(*conn_holder, arrow_array_stream, name); } void _duckdb_jdbc_arrow_close_streams(JNIEnv *env, jclass, jobject conn_ref_buf) { get_connection_ref(env, conn_ref_buf)->close_arrow_streams(); } -static ProfilerPrintFormat GetProfilerPrintFormat(JNIEnv *env, jobject format) { - jobject jname = env->CallObjectMethod(format, J_ProfilerPrintFormat_getName); +jstring _duckdb_jdbc_get_profiling_information(JNIEnv *env, jclass, jobject conn_ref_buf, jobject j_format) { + auto &conn = get_connection(env, conn_ref_buf); + jobject jname = env->CallObjectMethod(j_format, J_ProfilerPrintFormat_getName); check_java_exception_and_rethrow(env); const std::string name = jstring_to_string(env, static_cast(jname)); - return ProfilerPrintFormat(name); -} - -jstring _duckdb_jdbc_get_profiling_information(JNIEnv *env, jclass, jobject conn_ref_buf, jobject j_format) { - auto connection = get_connection(env, conn_ref_buf); - if (!connection) { - throw InvalidInputException("Invalid connection"); - } - auto format = GetProfilerPrintFormat(env, j_format); - auto profiling_info = connection->GetProfilingInformation(format); + auto profiling_info = conn.GetProfilingInformation(name == "default" ? std::string() : name); return env->NewStringUTF(profiling_info.c_str()); } diff --git a/src/jni/functions.cpp b/src/jni/functions.cpp index 564f6c252..73bba3e56 100644 --- a/src/jni/functions.cpp +++ b/src/jni/functions.cpp @@ -8,8 +8,7 @@ JNIEXPORT jobject JNICALL Java_org_duckdb_DuckDBNative_duckdb_1jdbc_1startup(JNI try { return _duckdb_jdbc_startup(env, param0, param1, param2, param3, param4); } catch (const std::exception &e) { - duckdb::ErrorData error(e); - ThrowJNI(env, error.Message().c_str()); + ThrowJNIException(env, e); return nullptr; } @@ -19,8 +18,7 @@ JNIEXPORT jobject JNICALL Java_org_duckdb_DuckDBNative_duckdb_1jdbc_1connect(JNI try { return _duckdb_jdbc_connect(env, param0, param1); } catch (const std::exception &e) { - duckdb::ErrorData error(e); - ThrowJNI(env, error.Message().c_str()); + ThrowJNIException(env, e); return nullptr; } @@ -30,8 +28,7 @@ JNIEXPORT jobject JNICALL Java_org_duckdb_DuckDBNative_duckdb_1jdbc_1create_1db_ try { return _duckdb_jdbc_create_db_ref(env, param0, param1); } catch (const std::exception &e) { - duckdb::ErrorData error(e); - ThrowJNI(env, error.Message().c_str()); + ThrowJNIException(env, e); return nullptr; } @@ -41,8 +38,7 @@ JNIEXPORT jlong JNICALL Java_org_duckdb_DuckDBNative_duckdb_1jdbc_1db_1address(J try { return _duckdb_jdbc_db_address(env, param0, param1); } catch (const std::exception &e) { - duckdb::ErrorData error(e); - ThrowJNI(env, error.Message().c_str()); + ThrowJNIException(env, e); return 0; } @@ -52,8 +48,7 @@ JNIEXPORT void JNICALL Java_org_duckdb_DuckDBNative_duckdb_1jdbc_1destroy_1db_1r try { return _duckdb_jdbc_destroy_db_ref(env, param0, param1); } catch (const std::exception &e) { - duckdb::ErrorData error(e); - ThrowJNI(env, error.Message().c_str()); + ThrowJNIException(env, e); } } @@ -62,8 +57,7 @@ JNIEXPORT void JNICALL Java_org_duckdb_DuckDBNative_duckdb_1jdbc_1set_1auto_1com try { return _duckdb_jdbc_set_auto_commit(env, param0, param1, param2); } catch (const std::exception &e) { - duckdb::ErrorData error(e); - ThrowJNI(env, error.Message().c_str()); + ThrowJNIException(env, e); } } @@ -72,8 +66,7 @@ JNIEXPORT jboolean JNICALL Java_org_duckdb_DuckDBNative_duckdb_1jdbc_1get_1auto_ try { return _duckdb_jdbc_get_auto_commit(env, param0, param1); } catch (const std::exception &e) { - duckdb::ErrorData error(e); - ThrowJNI(env, error.Message().c_str()); + ThrowJNIException(env, e); return false; } @@ -83,8 +76,7 @@ JNIEXPORT void JNICALL Java_org_duckdb_DuckDBNative_duckdb_1jdbc_1disconnect(JNI try { return _duckdb_jdbc_disconnect(env, param0, param1); } catch (const std::exception &e) { - duckdb::ErrorData error(e); - ThrowJNI(env, error.Message().c_str()); + ThrowJNIException(env, e); } } @@ -93,8 +85,7 @@ JNIEXPORT void JNICALL Java_org_duckdb_DuckDBNative_duckdb_1jdbc_1set_1schema(JN try { return _duckdb_jdbc_set_schema(env, param0, param1, param2); } catch (const std::exception &e) { - duckdb::ErrorData error(e); - ThrowJNI(env, error.Message().c_str()); + ThrowJNIException(env, e); } } @@ -103,8 +94,7 @@ JNIEXPORT void JNICALL Java_org_duckdb_DuckDBNative_duckdb_1jdbc_1set_1catalog(J try { return _duckdb_jdbc_set_catalog(env, param0, param1, param2); } catch (const std::exception &e) { - duckdb::ErrorData error(e); - ThrowJNI(env, error.Message().c_str()); + ThrowJNIException(env, e); } } @@ -113,8 +103,7 @@ JNIEXPORT jstring JNICALL Java_org_duckdb_DuckDBNative_duckdb_1jdbc_1get_1schema try { return _duckdb_jdbc_get_schema(env, param0, param1); } catch (const std::exception &e) { - duckdb::ErrorData error(e); - ThrowJNI(env, error.Message().c_str()); + ThrowJNIException(env, e); return nullptr; } @@ -124,8 +113,7 @@ JNIEXPORT jstring JNICALL Java_org_duckdb_DuckDBNative_duckdb_1jdbc_1get_1catalo try { return _duckdb_jdbc_get_catalog(env, param0, param1); } catch (const std::exception &e) { - duckdb::ErrorData error(e); - ThrowJNI(env, error.Message().c_str()); + ThrowJNIException(env, e); return nullptr; } @@ -135,8 +123,7 @@ JNIEXPORT jobject JNICALL Java_org_duckdb_DuckDBNative_duckdb_1jdbc_1prepare(JNI try { return _duckdb_jdbc_prepare(env, param0, param1, param2); } catch (const std::exception &e) { - duckdb::ErrorData error(e); - ThrowJNI(env, error.Message().c_str()); + ThrowJNIException(env, e); return nullptr; } @@ -146,8 +133,7 @@ JNIEXPORT jobject JNICALL Java_org_duckdb_DuckDBNative_duckdb_1jdbc_1pending_1qu try { return _duckdb_jdbc_pending_query(env, param0, param1, param2); } catch (const std::exception &e) { - duckdb::ErrorData error(e); - ThrowJNI(env, error.Message().c_str()); + ThrowJNIException(env, e); return nullptr; } @@ -157,8 +143,7 @@ JNIEXPORT void JNICALL Java_org_duckdb_DuckDBNative_duckdb_1jdbc_1release(JNIEnv try { return _duckdb_jdbc_release(env, param0, param1); } catch (const std::exception &e) { - duckdb::ErrorData error(e); - ThrowJNI(env, error.Message().c_str()); + ThrowJNIException(env, e); } } @@ -167,8 +152,7 @@ JNIEXPORT void JNICALL Java_org_duckdb_DuckDBNative_duckdb_1jdbc_1release_1pendi try { _duckdb_jdbc_release_pending(env, param0, param1); } catch (const std::exception &e) { - duckdb::ErrorData error(e); - ThrowJNI(env, error.Message().c_str()); + ThrowJNIException(env, e); } } @@ -177,8 +161,7 @@ JNIEXPORT jobject JNICALL Java_org_duckdb_DuckDBNative_duckdb_1jdbc_1query_1resu try { return _duckdb_jdbc_query_result_meta(env, param0, param1); } catch (const std::exception &e) { - duckdb::ErrorData error(e); - ThrowJNI(env, error.Message().c_str()); + ThrowJNIException(env, e); return nullptr; } @@ -188,8 +171,7 @@ JNIEXPORT jobject JNICALL Java_org_duckdb_DuckDBNative_duckdb_1jdbc_1prepared_1s try { return _duckdb_jdbc_prepared_statement_meta(env, param0, param1); } catch (const std::exception &e) { - duckdb::ErrorData error(e); - ThrowJNI(env, error.Message().c_str()); + ThrowJNIException(env, e); return nullptr; } @@ -199,8 +181,7 @@ JNIEXPORT jobject JNICALL Java_org_duckdb_DuckDBNative_duckdb_1jdbc_1execute(JNI try { return _duckdb_jdbc_execute(env, param0, param1, param2); } catch (const std::exception &e) { - duckdb::ErrorData error(e); - ThrowJNI(env, error.Message().c_str()); + ThrowJNIException(env, e); return nullptr; } @@ -210,8 +191,7 @@ JNIEXPORT jobject JNICALL Java_org_duckdb_DuckDBNative_duckdb_1jdbc_1execute_1ca try { return _duckdb_jdbc_execute_capi(env, param0, param1, param2); } catch (const std::exception &e) { - duckdb::ErrorData error(e); - ThrowJNI(env, error.Message().c_str()); + ThrowJNIException(env, e); return nullptr; } @@ -221,8 +201,7 @@ JNIEXPORT jobject JNICALL Java_org_duckdb_DuckDBNative_duckdb_1jdbc_1execute_1pe try { return _duckdb_jdbc_execute_pending(env, param0, param1); } catch (const std::exception &e) { - duckdb::ErrorData error(e); - ThrowJNI(env, error.Message().c_str()); + ThrowJNIException(env, e); return nullptr; } @@ -232,8 +211,7 @@ JNIEXPORT void JNICALL Java_org_duckdb_DuckDBNative_duckdb_1jdbc_1free_1result(J try { return _duckdb_jdbc_free_result(env, param0, param1); } catch (const std::exception &e) { - duckdb::ErrorData error(e); - ThrowJNI(env, error.Message().c_str()); + ThrowJNIException(env, e); } } @@ -242,8 +220,7 @@ JNIEXPORT jobjectArray JNICALL Java_org_duckdb_DuckDBNative_duckdb_1jdbc_1fetch( try { return _duckdb_jdbc_fetch(env, param0, param1, param2); } catch (const std::exception &e) { - duckdb::ErrorData error(e); - ThrowJNI(env, error.Message().c_str()); + ThrowJNIException(env, e); return nullptr; } @@ -253,8 +230,7 @@ JNIEXPORT jobjectArray JNICALL Java_org_duckdb_DuckDBNative_duckdb_1jdbc_1cast_1 try { return _duckdb_jdbc_cast_result_to_strings(env, param0, param1, param2, param3); } catch (const std::exception &e) { - duckdb::ErrorData error(e); - ThrowJNI(env, error.Message().c_str()); + ThrowJNIException(env, e); return nullptr; } @@ -264,8 +240,7 @@ JNIEXPORT jint JNICALL Java_org_duckdb_DuckDBNative_duckdb_1jdbc_1fetch_1size(JN try { return _duckdb_jdbc_fetch_size(env, param0); } catch (const std::exception &e) { - duckdb::ErrorData error(e); - ThrowJNI(env, error.Message().c_str()); + ThrowJNIException(env, e); return -1; } @@ -275,8 +250,7 @@ JNIEXPORT jlong JNICALL Java_org_duckdb_DuckDBNative_duckdb_1jdbc_1arrow_1stream try { return _duckdb_jdbc_arrow_stream(env, param0, param1, param2, param3); } catch (const std::exception &e) { - duckdb::ErrorData error(e); - ThrowJNI(env, error.Message().c_str()); + ThrowJNIException(env, e); return -1; } @@ -286,8 +260,7 @@ JNIEXPORT void JNICALL Java_org_duckdb_DuckDBNative_duckdb_1jdbc_1arrow_1registe try { return _duckdb_jdbc_arrow_register(env, param0, param1, param2, param3); } catch (const std::exception &e) { - duckdb::ErrorData error(e); - ThrowJNI(env, error.Message().c_str()); + ThrowJNIException(env, e); } } @@ -296,8 +269,7 @@ JNIEXPORT void JNICALL Java_org_duckdb_DuckDBNative_duckdb_1jdbc_1arrow_1close_1 try { return _duckdb_jdbc_arrow_close_streams(env, param0, param1); } catch (const std::exception &e) { - duckdb::ErrorData error(e); - ThrowJNI(env, error.Message().c_str()); + ThrowJNIException(env, e); } } @@ -306,8 +278,7 @@ JNIEXPORT jobject JNICALL Java_org_duckdb_DuckDBNative_duckdb_1jdbc_1create_1app try { return _duckdb_jdbc_create_appender(env, param0, param1, param2, param3); } catch (const std::exception &e) { - duckdb::ErrorData error(e); - ThrowJNI(env, error.Message().c_str()); + ThrowJNIException(env, e); return nullptr; } @@ -317,8 +288,7 @@ JNIEXPORT void JNICALL Java_org_duckdb_DuckDBNative_duckdb_1jdbc_1appender_1begi try { return _duckdb_jdbc_appender_begin_row(env, param0, param1); } catch (const std::exception &e) { - duckdb::ErrorData error(e); - ThrowJNI(env, error.Message().c_str()); + ThrowJNIException(env, e); } } @@ -327,8 +297,7 @@ JNIEXPORT void JNICALL Java_org_duckdb_DuckDBNative_duckdb_1jdbc_1appender_1end_ try { return _duckdb_jdbc_appender_end_row(env, param0, param1); } catch (const std::exception &e) { - duckdb::ErrorData error(e); - ThrowJNI(env, error.Message().c_str()); + ThrowJNIException(env, e); } } @@ -337,8 +306,7 @@ JNIEXPORT void JNICALL Java_org_duckdb_DuckDBNative_duckdb_1jdbc_1appender_1flus try { return _duckdb_jdbc_appender_flush(env, param0, param1); } catch (const std::exception &e) { - duckdb::ErrorData error(e); - ThrowJNI(env, error.Message().c_str()); + ThrowJNIException(env, e); } } @@ -347,8 +315,7 @@ JNIEXPORT void JNICALL Java_org_duckdb_DuckDBNative_duckdb_1jdbc_1interrupt(JNIE try { return _duckdb_jdbc_interrupt(env, param0, param1); } catch (const std::exception &e) { - duckdb::ErrorData error(e); - ThrowJNI(env, error.Message().c_str()); + ThrowJNIException(env, e); } } @@ -357,8 +324,7 @@ JNIEXPORT jobject JNICALL Java_org_duckdb_DuckDBNative_duckdb_1jdbc_1query_1prog try { return _duckdb_jdbc_query_progress(env, param0, param1); } catch (const std::exception &e) { - duckdb::ErrorData error(e); - ThrowJNI(env, error.Message().c_str()); + ThrowJNIException(env, e); return nullptr; } } @@ -367,8 +333,7 @@ JNIEXPORT void JNICALL Java_org_duckdb_DuckDBNative_duckdb_1jdbc_1appender_1clos try { return _duckdb_jdbc_appender_close(env, param0, param1); } catch (const std::exception &e) { - duckdb::ErrorData error(e); - ThrowJNI(env, error.Message().c_str()); + ThrowJNIException(env, e); } } @@ -377,8 +342,7 @@ JNIEXPORT void JNICALL Java_org_duckdb_DuckDBNative_duckdb_1jdbc_1appender_1appe try { return _duckdb_jdbc_appender_append_boolean(env, param0, param1, param2); } catch (const std::exception &e) { - duckdb::ErrorData error(e); - ThrowJNI(env, error.Message().c_str()); + ThrowJNIException(env, e); } } @@ -387,8 +351,7 @@ JNIEXPORT void JNICALL Java_org_duckdb_DuckDBNative_duckdb_1jdbc_1appender_1appe try { return _duckdb_jdbc_appender_append_byte(env, param0, param1, param2); } catch (const std::exception &e) { - duckdb::ErrorData error(e); - ThrowJNI(env, error.Message().c_str()); + ThrowJNIException(env, e); } } @@ -397,8 +360,7 @@ JNIEXPORT void JNICALL Java_org_duckdb_DuckDBNative_duckdb_1jdbc_1appender_1appe try { return _duckdb_jdbc_appender_append_short(env, param0, param1, param2); } catch (const std::exception &e) { - duckdb::ErrorData error(e); - ThrowJNI(env, error.Message().c_str()); + ThrowJNIException(env, e); } } @@ -407,8 +369,7 @@ JNIEXPORT void JNICALL Java_org_duckdb_DuckDBNative_duckdb_1jdbc_1appender_1appe try { return _duckdb_jdbc_appender_append_int(env, param0, param1, param2); } catch (const std::exception &e) { - duckdb::ErrorData error(e); - ThrowJNI(env, error.Message().c_str()); + ThrowJNIException(env, e); } } @@ -417,8 +378,7 @@ JNIEXPORT void JNICALL Java_org_duckdb_DuckDBNative_duckdb_1jdbc_1appender_1appe try { return _duckdb_jdbc_appender_append_long(env, param0, param1, param2); } catch (const std::exception &e) { - duckdb::ErrorData error(e); - ThrowJNI(env, error.Message().c_str()); + ThrowJNIException(env, e); } } @@ -427,8 +387,7 @@ JNIEXPORT void JNICALL Java_org_duckdb_DuckDBNative_duckdb_1jdbc_1appender_1appe try { return _duckdb_jdbc_appender_append_float(env, param0, param1, param2); } catch (const std::exception &e) { - duckdb::ErrorData error(e); - ThrowJNI(env, error.Message().c_str()); + ThrowJNIException(env, e); } } @@ -437,8 +396,7 @@ JNIEXPORT void JNICALL Java_org_duckdb_DuckDBNative_duckdb_1jdbc_1appender_1appe try { return _duckdb_jdbc_appender_append_double(env, param0, param1, param2); } catch (const std::exception &e) { - duckdb::ErrorData error(e); - ThrowJNI(env, error.Message().c_str()); + ThrowJNIException(env, e); } } @@ -447,8 +405,7 @@ JNIEXPORT void JNICALL Java_org_duckdb_DuckDBNative_duckdb_1jdbc_1appender_1appe try { return _duckdb_jdbc_appender_append_string(env, param0, param1, param2); } catch (const std::exception &e) { - duckdb::ErrorData error(e); - ThrowJNI(env, error.Message().c_str()); + ThrowJNIException(env, e); } } @@ -457,8 +414,7 @@ JNIEXPORT void JNICALL Java_org_duckdb_DuckDBNative_duckdb_1jdbc_1appender_1appe try { return _duckdb_jdbc_appender_append_bytes(env, param0, param1, param2); } catch (const std::exception &e) { - duckdb::ErrorData error(e); - ThrowJNI(env, error.Message().c_str()); + ThrowJNIException(env, e); } } @@ -467,8 +423,7 @@ JNIEXPORT void JNICALL Java_org_duckdb_DuckDBNative_duckdb_1jdbc_1appender_1appe try { return _duckdb_jdbc_appender_append_timestamp(env, param0, param1, param2); } catch (const std::exception &e) { - duckdb::ErrorData error(e); - ThrowJNI(env, error.Message().c_str()); + ThrowJNIException(env, e); } } @@ -477,8 +432,7 @@ JNIEXPORT void JNICALL Java_org_duckdb_DuckDBNative_duckdb_1jdbc_1appender_1appe try { return _duckdb_jdbc_appender_append_decimal(env, param0, param1, param2); } catch (const std::exception &e) { - duckdb::ErrorData error(e); - ThrowJNI(env, error.Message().c_str()); + ThrowJNIException(env, e); } } @@ -487,8 +441,7 @@ JNIEXPORT void JNICALL Java_org_duckdb_DuckDBNative_duckdb_1jdbc_1appender_1appe try { return _duckdb_jdbc_appender_append_null(env, param0, param1); } catch (const std::exception &e) { - duckdb::ErrorData error(e); - ThrowJNI(env, error.Message().c_str()); + ThrowJNIException(env, e); } } @@ -497,8 +450,7 @@ JNIEXPORT jstring JNICALL Java_org_duckdb_DuckDBNative_duckdb_1jdbc_1get_1profil try { return _duckdb_jdbc_get_profiling_information(env, param0, param1, param2); } catch (const std::exception &e) { - duckdb::ErrorData error(e); - ThrowJNI(env, error.Message().c_str()); + ThrowJNIException(env, e); return nullptr; } diff --git a/src/jni/functions.cpp.template b/src/jni/functions.cpp.template index 4fa4537e1..9e25a98b9 100644 --- a/src/jni/functions.cpp.template +++ b/src/jni/functions.cpp.template @@ -9,8 +9,7 @@ JNIEXPORT {{ function.return_type or 'void' }} JNICALL {{function.name}}({{funct try { return {{function.short_name}}({{function.names}}); } catch (const std::exception &e) { - duckdb::ErrorData error(e); - ThrowJNI(env, error.Message().c_str()); + ThrowJNIException(env, e); {% if function.return_type == 'jboolean' %} return false; diff --git a/src/jni/functions.hpp b/src/jni/functions.hpp index c7f72177b..ac5c80d74 100644 --- a/src/jni/functions.hpp +++ b/src/jni/functions.hpp @@ -2,13 +2,14 @@ #pragma once -#include "duckdb/common/assert.hpp" -#include "duckdb/common/error_data.hpp" #include "org_duckdb_DuckDBNative.h" #include void ThrowJNI(JNIEnv* env, const char* message); +//! Throws a SQLTimeoutException for the interrupted queries and a SQLException for all other errors +void ThrowJNIException(JNIEnv* env, const std::exception& e); + jobject _duckdb_jdbc_startup(JNIEnv * env, jclass param0, jbyteArray param1, jboolean param2, jobject param3, jboolean param4); JNIEXPORT jobject JNICALL Java_org_duckdb_DuckDBNative_duckdb_1jdbc_1startup(JNIEnv * env, jclass param0, jbyteArray param1, jboolean param2, jobject param3, jboolean param4); diff --git a/src/jni/functions.hpp.template b/src/jni/functions.hpp.template index 9f90d37e1..03968239f 100644 --- a/src/jni/functions.hpp.template +++ b/src/jni/functions.hpp.template @@ -2,12 +2,13 @@ #pragma once -#include "duckdb/common/assert.hpp" -#include "duckdb/common/error_data.hpp" #include "org_duckdb_DuckDBNative.h" #include void ThrowJNI(JNIEnv* env, const char* message); + +//! Throws a SQLTimeoutException for the interrupted queries and a SQLException for all other errors +void ThrowJNIException(JNIEnv* env, const std::exception& e); {% for function in header.functions %} {{function.return_type or 'void'}} {{function.short_name}}({{function.params}}); diff --git a/src/jni/holders.cpp b/src/jni/holders.cpp index 48d561f66..93adb9064 100644 --- a/src/jni/holders.cpp +++ b/src/jni/holders.cpp @@ -6,26 +6,40 @@ ConnectionHolder *get_connection_ref(JNIEnv *env, jobject conn_ref_buf) { if (!conn_ref_buf) { - throw duckdb::ConnectionException("Invalid connection buffer ref"); + throw JdbcException("Invalid connection buffer ref"); } auto conn_holder = reinterpret_cast(env->GetDirectBufferAddress(conn_ref_buf)); if (!conn_holder) { - throw duckdb::ConnectionException("Invalid connection buffer"); + throw JdbcException("Invalid connection buffer"); } return conn_holder; } -void ConnectionHolder::track_arrow_stream(duckdb::shared_ptr state) { +void ConnectionHolder::track_arrow_stream(std::shared_ptr state) { std::lock_guard guard(arrow_streams_lock); - auto expired = [](const duckdb::weak_ptr &weak) { + auto expired = [](const std::weak_ptr &weak) { return weak.expired(); }; arrow_streams.erase(std::remove_if(arrow_streams.begin(), arrow_streams.end(), expired), arrow_streams.end()); arrow_streams.emplace_back(std::move(state)); } +std::shared_ptr ConnectionHolder::replace_registered_stream(const std::string &name, + std::shared_ptr state) { + std::lock_guard guard(arrow_streams_lock); + std::shared_ptr replaced; + auto it = registered_streams.find(name); + if (it != registered_streams.end()) { + replaced = std::move(it->second); + it->second = std::move(state); + } else { + registered_streams.emplace(name, std::move(state)); + } + return replaced; +} + void ConnectionHolder::close_arrow_streams() { - duckdb::vector> live; + std::vector> live; { std::lock_guard guard(arrow_streams_lock); // Last stream created is first closed @@ -36,26 +50,43 @@ void ConnectionHolder::close_arrow_streams() { } } arrow_streams.clear(); + registered_streams.clear(); } for (auto &state : live) { state->Close(); } } -/** - * Throws a SQLException and returns nullptr if a valid Connection can't be retrieved from the buffer. - */ -duckdb::Connection *get_connection(JNIEnv *env, jobject conn_ref_buf) { - auto conn_holder = get_connection_ref(env, conn_ref_buf); - auto conn_ref = conn_holder->connection.get(); - if (!conn_ref || !conn_ref->context) { - throw duckdb::ConnectionException("Invalid connection"); +void copy_session_settings(cxx::Connection &src, cxx::Connection &dst) { + auto &src_config = src.GetConfig(); + auto &dst_config = dst.GetConfig(); + for (size_t i = 0; i < src_config.GetOptionCount(); i++) { + auto description = src_config.DescribeOption(i); + if (!description.SupportsScope(cxx::SettingScope::SESSION)) { + continue; + } + std::string name(description.GetName()); + // the catalog and the schema of the connection are not a part of its settings + if (name == "schema" || name == "search_path") { + continue; + } + auto option = src_config.GetOption(name); + if (option.scope != cxx::SettingScope::SESSION || option.value.IsNull()) { + continue; + } + dst_config.SetOption(name, option.value, cxx::SettingScope::SESSION); } +} - return conn_ref; +cxx::Connection &get_connection(JNIEnv *env, jobject conn_ref_buf) { + auto conn_holder = get_connection_ref(env, conn_ref_buf); + if (!conn_holder->connection) { + throw JdbcException("Invalid connection"); + } + return *conn_holder->connection; } -static duckdb::capiv2::CV2Connection *conn_ref_buf_to_v2_conn(JNIEnv *env, jobject conn_ref_buf) { +cxx::Connection *conn_ref_buf_to_engine_conn(JNIEnv *env, jobject conn_ref_buf) { if (conn_ref_buf == nullptr) { env->ThrowNew(J_SQLException, "Invalid connection buffer"); return nullptr; @@ -65,24 +96,19 @@ static duckdb::capiv2::CV2Connection *conn_ref_buf_to_v2_conn(JNIEnv *env, jobje env->ThrowNew(J_SQLException, "Invalid connection holder"); return nullptr; } - auto conn_ref = conn_holder->connection.get(); - if (conn_ref == nullptr || conn_ref->context == nullptr) { + if (!conn_holder->connection) { env->ThrowNew(J_SQLException, "Invalid connection"); return nullptr; } - return conn_ref; + return conn_holder->connection.get(); } duckdb_v2_connection_handle conn_ref_buf_to_conn(JNIEnv *env, jobject conn_ref_buf) { - auto conn_ref = conn_ref_buf_to_v2_conn(env, conn_ref_buf); - if (conn_ref == nullptr) { + auto conn = conn_ref_buf_to_engine_conn(env, conn_ref_buf); + if (conn == nullptr) { return nullptr; } - return duckdb::capiv2::Convert(conn_ref); -} - -duckdb::Connection *conn_ref_buf_to_engine_conn(JNIEnv *env, jobject conn_ref_buf) { - return conn_ref_buf_to_v2_conn(env, conn_ref_buf); + return conn->handle(); } ChunkedResultHolder::ChunkedResultHolder(duckdb_v2_result_handle result_p) : result(result_p) { diff --git a/src/jni/holders.hpp b/src/jni/holders.hpp index 20966c3f6..1d21cc369 100644 --- a/src/jni/holders.hpp +++ b/src/jni/holders.hpp @@ -1,24 +1,56 @@ #pragma once #include "capi_v2.hpp" -#include "duckdb.hpp" -#include "duckdb/main/capi_v2/capi_v2_internal.hpp" +#include "cxx_handles.hpp" #include "refs.hpp" #include +#include #include +#include #include +#include #include +namespace cxx = duckdb::cxx; + +/** + * A database instance of the stable C++ API. The instances that are opened with the instance cache enabled are shared + * between connections to the same database file. + */ +struct InstanceHolder { + explicit InstanceHolder(cxx::Instance instance_p) : instance(std::move(instance_p)) { + } + + //! The instances that are not shared are opened in an environment of their own, same named in-memory databases of + //! such instances are isolated from each other + InstanceHolder(std::unique_ptr environment_p, cxx::Instance instance_p) + : environment(std::move(environment_p)), instance(std::move(instance_p)) { + } + + InstanceHolder(const InstanceHolder &) = delete; + + InstanceHolder &operator=(const InstanceHolder &) = delete; + + //! The cache key (the normalized database path), is empty for instances that are not cached + std::string key; + //! The configuration the instance was opened with, only used to check the compatibility with the new connections + std::vector> options; + bool read_only = false; + //! Declared before the instance, as the environment must outlive it + std::unique_ptr environment; + cxx::Instance instance; +}; + /** * Holds a copy of a shared_ptr to an existing DB instance. * Is used to keep this DB alive (and accessible from DB cache) * even after the last connection to this DB is closed. */ struct DBHolder { - duckdb::shared_ptr db; + std::shared_ptr db; - DBHolder(duckdb::shared_ptr _db) : db(std::move(_db)) {}; + DBHolder(std::shared_ptr _db) : db(std::move(_db)) {}; DBHolder(const DBHolder &) = delete; @@ -37,30 +69,49 @@ struct ArrowStreamState { }; /** - * Associates a duckdb::Connection with a duckdb::DuckDB. The DB may be shared amongst many ConnectionHolders, but the - * Connection is unique to this holder. Every Java DuckDBConnection has exactly 1 of these holders, and they are never - * shared. The holder is freed when the DuckDBConnection is closed. When the last holder sharing a DuckDB is freed, the - * DuckDB is released as well. + * Associates a connection with a database instance. The instance may be shared amongst many ConnectionHolders, but the + * connection is unique to this holder. Every Java DuckDBConnection has exactly 1 of these holders, and they are never + * shared. The holder is freed when the DuckDBConnection is closed. When the last holder sharing an instance is freed, + * the instance is released as well. * - * The connection is created as a capiv2::CV2Connection (that is a duckdb::Connection) so it can also be used as - * a connection handle of the C API v2. + * The connection handle is also used as a connection handle of the C API v2 by the bindings. */ struct ConnectionHolder { - const duckdb::shared_ptr db; - const duckdb::unique_ptr connection; - - ConnectionHolder(duckdb::shared_ptr _db) - : db(_db), connection(duckdb::make_uniq(*_db)) { +private: + struct State { + explicit State(cxx::Connection connection_p) : connection(std::move(connection_p)) { + } + + cxx::Connection connection; + //! A connection can be used by one thread at a time, the Java side can share a connection between threads + std::mutex lock; + }; + + std::shared_ptr state; + +public: + const std::shared_ptr db; + //! Shared with the statements of this connection, so they can find out that the connection was closed + const std::shared_ptr connection; + const std::shared_ptr lock; + + explicit ConnectionHolder(std::shared_ptr _db) + : state(std::make_shared(_db->instance.Connect())), db(_db), connection(state, &state->connection), + lock(state, &state->lock) { } ~ConnectionHolder() { close_arrow_streams(); } - void track_arrow_stream(duckdb::shared_ptr state); + void track_arrow_stream(std::shared_ptr state); void close_arrow_streams(); + //! Remembers the stream that is registered with the name, returns the stream that was registered with it before + std::shared_ptr replace_registered_stream(const std::string &name, + std::shared_ptr state); + DBHolder *create_db_ref() { return new DBHolder(db); } @@ -68,22 +119,52 @@ struct ConnectionHolder { private: std::mutex arrow_streams_lock; //! Streams are untracked implicitly when they are released by their consumers - duckdb::vector> arrow_streams; + std::vector> arrow_streams; + //! The streams of the views that are created for the registered streams + std::unordered_map> registered_streams; }; struct StatementHolder { - duckdb::unique_ptr stmt; + std::weak_ptr connection; + std::weak_ptr lock; + std::optional statement; + std::optional stmt; + //! The columns of the result and the parameters of the statement + std::optional signature; + cxx::StatementType statement_type = cxx::StatementType::INVALID; }; +/** + * A query that is submitted but is not yet completed, the execution of the query is deferred until it is read. + */ struct PendingHolder { - duckdb::unique_ptr pending; + std::weak_ptr connection; + std::weak_ptr lock; + std::optional pending; bool streaming = false; }; +/** + * Column data of a result that is read into memory, it does not hold the connection that the result was created on. + */ +struct MaterializedData { + std::optional collection; + std::optional shared_state; + std::optional worker_state; +}; + struct ResultHolder { - duckdb::unique_ptr res; - duckdb::unique_ptr> stream; - duckdb::unique_ptr chunk; + std::weak_ptr connection; + std::vector names; + std::vector types; + cxx::ResultType result_type = cxx::ResultType::QUERY_RESULT; + //! Set for the results that are streamed, the connection is busy until the result is freed + std::optional stream; + //! Set for the results that are read into memory + std::unique_ptr materialized; + //! The first chunk of a streamed result, that was read to check that the query is running without errors + std::optional first_chunk; + std::optional chunk; }; /** @@ -97,6 +178,9 @@ struct ChunkedResultHolder { std::vector column_types; bool has_error = false; std::string error; + //! The first chunk of the result, that was read to check that the query is running without errors + v2_data_chunk first_chunk; + bool has_first_chunk = false; //! Takes ownership of the result, throws if the result schema cannot be read explicit ChunkedResultHolder(duckdb_v2_result_handle result_p); @@ -139,17 +223,33 @@ struct LocalRefHolder { ~LocalRefHolder() noexcept; }; +/** + * Thrown for the errors that are detected by the driver itself. + */ +struct JdbcException : public std::runtime_error { + explicit JdbcException(const std::string &message) : std::runtime_error(message) { + } +}; + +/** + * Copies the session settings of the connection to the other one, the catalog and the schema are not copied. + */ +void copy_session_settings(cxx::Connection &src, cxx::Connection &dst); + ConnectionHolder *get_connection_ref(JNIEnv *env, jobject conn_ref_buf); -duckdb::Connection *get_connection(JNIEnv *env, jobject conn_ref_buf); +/** + * Throws if a valid connection can't be retrieved from the buffer. + */ +cxx::Connection &get_connection(JNIEnv *env, jobject conn_ref_buf); /** * Returns the C API v2 handle of the connection of the specified holder. Throws a SQLException and returns nullptr - * if a valid Connection can't be retrieved from the buffer. + * if a valid connection can't be retrieved from the buffer. */ duckdb_v2_connection_handle conn_ref_buf_to_conn(JNIEnv *env, jobject conn_ref_buf); /** - * Same as conn_ref_buf_to_conn, returns the engine connection. + * Same as conn_ref_buf_to_conn, returns the connection of the stable C++ API. */ -duckdb::Connection *conn_ref_buf_to_engine_conn(JNIEnv *env, jobject conn_ref_buf); +cxx::Connection *conn_ref_buf_to_engine_conn(JNIEnv *env, jobject conn_ref_buf); diff --git a/src/jni/types.cpp b/src/jni/types.cpp index 2bcbb8668..5d2df7d55 100644 --- a/src/jni/types.cpp +++ b/src/jni/types.cpp @@ -1,38 +1,128 @@ #include "types.hpp" +#include "holders.hpp" #include "refs.hpp" #include "util.hpp" +#include #include #include -std::string type_to_jduckdb_type(duckdb::LogicalType logical_type) { - switch (logical_type.id()) { - case duckdb::LogicalTypeId::DECIMAL: { +using duckdb::cxx::Factory; +using duckdb::cxx::LogicalTypeId; +using duckdb::cxx::Value; + +std::string type_id_to_string(LogicalTypeId id) { + switch (id) { + case LogicalTypeId::INVALID: + return "INVALID"; + case LogicalTypeId::SQLNULL: + return "NULL"; + case LogicalTypeId::UNKNOWN: + return "UNKNOWN"; + case LogicalTypeId::ANY: + return "ANY"; + case LogicalTypeId::TYPE: + return "TYPE"; + case LogicalTypeId::BOOLEAN: + return "BOOLEAN"; + case LogicalTypeId::TINYINT: + return "TINYINT"; + case LogicalTypeId::SMALLINT: + return "SMALLINT"; + case LogicalTypeId::INTEGER: + return "INTEGER"; + case LogicalTypeId::BIGINT: + return "BIGINT"; + case LogicalTypeId::DATE: + return "DATE"; + case LogicalTypeId::TIME: + return "TIME"; + case LogicalTypeId::TIMESTAMP_SEC: + return "TIMESTAMP_S"; + case LogicalTypeId::TIMESTAMP_MS: + return "TIMESTAMP_MS"; + case LogicalTypeId::TIMESTAMP: + return "TIMESTAMP"; + case LogicalTypeId::TIMESTAMP_NS: + return "TIMESTAMP_NS"; + case LogicalTypeId::DECIMAL: + return "DECIMAL"; + case LogicalTypeId::FLOAT: + return "FLOAT"; + case LogicalTypeId::DOUBLE: + return "DOUBLE"; + case LogicalTypeId::VARCHAR: + return "VARCHAR"; + case LogicalTypeId::BLOB: + return "BLOB"; + case LogicalTypeId::INTERVAL: + return "INTERVAL"; + case LogicalTypeId::UTINYINT: + return "UTINYINT"; + case LogicalTypeId::USMALLINT: + return "USMALLINT"; + case LogicalTypeId::UINTEGER: + return "UINTEGER"; + case LogicalTypeId::UBIGINT: + return "UBIGINT"; + case LogicalTypeId::TIMESTAMP_TZ: + return "TIMESTAMP WITH TIME ZONE"; + case LogicalTypeId::TIMESTAMP_TZ_NS: + return "TIMESTAMPTZ_NS"; + case LogicalTypeId::TIME_TZ: + return "TIME WITH TIME ZONE"; + case LogicalTypeId::TIME_NS: + return "TIME_NS"; + case LogicalTypeId::BIT: + return "BIT"; + case LogicalTypeId::BIGNUM: + return "BIGNUM"; + case LogicalTypeId::UHUGEINT: + return "UHUGEINT"; + case LogicalTypeId::HUGEINT: + return "HUGEINT"; + case LogicalTypeId::UUID: + return "UUID"; + case LogicalTypeId::GEOMETRY: + return "GEOMETRY"; + case LogicalTypeId::STRUCT: + return "STRUCT"; + case LogicalTypeId::LIST: + return "LIST"; + case LogicalTypeId::MAP: + return "MAP"; + case LogicalTypeId::ENUM: + return "ENUM"; + case LogicalTypeId::UNION: + return "UNION"; + case LogicalTypeId::ARRAY: + return "ARRAY"; + case LogicalTypeId::VARIANT: + return "VARIANT"; + case LogicalTypeId::TUPLE: + return "TUPLE"; + default: + return "INVALID"; + } +} - uint32_t width = 0; - uint32_t scale = 0; - logical_type.GetDecimalProperties(width, scale); +std::string type_to_jduckdb_type(const duckdb::cxx::LogicalType &logical_type) { + switch (logical_type.GetTypeId()) { + case LogicalTypeId::DECIMAL: { + uint32_t width = logical_type.GetDecimalWidth(); + uint32_t scale = logical_type.GetDecimalScale(); std::string width_scale = std::to_string(width) + std::string(";") + std::to_string(scale); - auto physical_type = logical_type.InternalType(); - switch (physical_type) { - case duckdb::PhysicalType::INT16: { - std::string res = std::string("DECIMAL16;") + width_scale; - return res; - } - case duckdb::PhysicalType::INT32: { - std::string res = std::string("DECIMAL32;") + width_scale; - return res; - } - case duckdb::PhysicalType::INT64: { - std::string res = std::string("DECIMAL64;") + width_scale; - return res; - } - case duckdb::PhysicalType::INT128: { - std::string res = std::string("DECIMAL128;") + width_scale; - return res; - } + switch (logical_type.GetDecimalInternalTypeId()) { + case LogicalTypeId::SMALLINT: + return std::string("DECIMAL16;") + width_scale; + case LogicalTypeId::INTEGER: + return std::string("DECIMAL32;") + width_scale; + case LogicalTypeId::BIGINT: + return std::string("DECIMAL64;") + width_scale; + case LogicalTypeId::HUGEINT: + return std::string("DECIMAL128;") + width_scale; default: return std::string("no physical type found"); } @@ -40,14 +130,19 @@ std::string type_to_jduckdb_type(duckdb::LogicalType logical_type) { default: // JSON requires special handling because it is mapped // to JsonNode class - if (logical_type.IsJSONType()) { - return logical_type.GetAlias(); + if (logical_type.GetName() == "JSON") { + return std::string(logical_type.GetName()); } - return duckdb::EnumUtil::ToString(logical_type.id()); + return type_id_to_string(logical_type.GetTypeId()); } } -duckdb::Value create_value_from_bigdecimal(JNIEnv *env, jobject decimal) { +//! A NULL of the type that is cast to any other type +static Value create_null_value(Factory &factory) { + return Value::CreateNull(factory, factory.ParseType("NULL")); +} + +Value create_value_from_bigdecimal(JNIEnv *env, jobject decimal, Factory &factory) { jint precision = env->CallIntMethod(decimal, J_BigDecimal_precision); check_java_exception_and_rethrow(env); jint scale = env->CallIntMethod(decimal, J_BigDecimal_scale); @@ -61,37 +156,35 @@ duckdb::Value create_value_from_bigdecimal(JNIEnv *env, jobject decimal) { // DECIMAL scale is unsigned, so negative values are not supported if (scale < 0) { - throw duckdb::InvalidInputException("Converting from a BigDecimal with negative scale is not supported"); + throw JdbcException("Invalid Input Error: Converting from a BigDecimal with negative scale is not supported"); } - duckdb::Value val; - if (precision <= 18) { // normal sizes -> avoid string processing jobject no_point_dec = env->CallObjectMethod(decimal, J_BigDecimal_scaleByPowTen, scale); check_java_exception_and_rethrow(env); jlong result = env->CallLongMethod(no_point_dec, J_BigDecimal_longValue); check_java_exception_and_rethrow(env); - val = duckdb::Value::DECIMAL((int64_t)result, (uint8_t)precision, (uint8_t)scale); + return Value::CreateDecimal(factory, duckdb::cxx::int128_t {static_cast(result), result < 0 ? -1 : 0}, + static_cast(precision), static_cast(scale)); } else if (precision <= 38) { // larger than int64 -> get string and cast jobject str_val = env->CallObjectMethod(decimal, J_BigDecimal_toPlainString); check_java_exception_and_rethrow(env); - auto *str_char = env->GetStringUTFChars((jstring)str_val, 0); - val = duckdb::Value(str_char); - val = val.DefaultCastAs(duckdb::LogicalType::DECIMAL(precision, scale)); - env->ReleaseStringUTFChars((jstring)str_val, str_char); + auto str = jstring_to_string(env, static_cast(str_val)); + auto val = Value::Create(factory, duckdb::cxx::varchar_t(str)); + auto type = factory.ParseType("DECIMAL(" + std::to_string(precision) + "," + std::to_string(scale) + ")"); + return val.Cast(factory, type); } - - return val; + // the precision is not supported, same as a NULL value + return create_null_value(factory); } -static duckdb::Value create_value_from_hugeint(JNIEnv *env, jobject hugeint) { +static Value create_value_from_hugeint(JNIEnv *env, jobject hugeint, Factory &factory) { jlong lower = env->GetLongField(hugeint, J_HugeInt_lower); jlong upper = env->GetLongField(hugeint, J_HugeInt_upper); - duckdb::hugeint_t hi(upper, lower); - return duckdb::Value::HUGEINT(std::move(hi)); + return Value::Create(factory, duckdb::cxx::int128_t {static_cast(lower), static_cast(upper)}); } -static duckdb::Value create_value_from_uuid(JNIEnv *env, jobject param) { +static Value create_value_from_uuid(JNIEnv *env, jobject param, Factory &factory) { jlong most_significant = env->CallLongMethod(param, J_UUID_getMostSignificantBits); check_java_exception_and_rethrow(env); // Account for the following logic in UUID::FromString: @@ -99,23 +192,24 @@ static duckdb::Value create_value_from_uuid(JNIEnv *env, jobject param) { most_significant ^= (std::numeric_limits::min)(); jlong least_significant = env->CallLongMethod(param, J_UUID_getLeastSignificantBits); check_java_exception_and_rethrow(env); - duckdb::hugeint_t hi = duckdb::hugeint_t(most_significant, least_significant); - return duckdb::Value::UUID(std::move(hi)); + duckdb::cxx::int128_t storage {static_cast(least_significant), static_cast(most_significant)}; + return Value::Create(factory, duckdb::cxx::uuid_t(storage)); } -static duckdb::Value create_value_from_map(JNIEnv *env, jobject param, duckdb::ClientContext &context) { +static Value create_value_from_map(JNIEnv *env, jobject param, Factory &factory) { jstring jstr = reinterpret_cast(env->CallObjectMethod(param, J_DuckMap_getSQLTypeName)); check_java_exception_and_rethrow(env); auto typeName = jstring_to_string(env, jstr); - duckdb::LogicalType type; - context.RunFunctionInTransaction([&]() { type = duckdb::TransformStringToLogicalType(typeName, context); }); + auto type = factory.ParseType(typeName); + auto key_type = type.GetMapKeyType(); + auto value_type = type.GetMapValueType(); auto entrySet = env->CallObjectMethod(param, J_Map_entrySet); check_java_exception_and_rethrow(env); auto iterator = env->CallObjectMethod(entrySet, J_Set_iterator); check_java_exception_and_rethrow(env); - duckdb::vector entries; + std::vector> entries; while (env->CallBooleanMethod(iterator, J_Iterator_hasNext)) { check_java_exception_and_rethrow(env); auto entry = env->CallObjectMethod(iterator, J_Iterator_next); @@ -125,44 +219,44 @@ static duckdb::Value create_value_from_map(JNIEnv *env, jobject param, duckdb::C check_java_exception_and_rethrow(env); auto value = env->CallObjectMethod(entry, J_Entry_getValue); check_java_exception_and_rethrow(env); - D_ASSERT(key); - D_ASSERT(value); - entries.push_back(duckdb::Value::STRUCT( - {{"key", to_duckdb_value(env, key, context)}, {"value", to_duckdb_value(env, value, context)}})); + entries.emplace_back(to_duckdb_value(env, key, factory).Cast(factory, key_type), + to_duckdb_value(env, value, factory).Cast(factory, value_type)); } check_java_exception_and_rethrow(env); - return duckdb::Value::MAP(duckdb::ListType::GetChildType(type), entries); + if (entries.empty()) { + return Value::CreateMap(factory, key_type, value_type); + } + return Value::CreateMap(factory, entries); } -static duckdb::Value create_value_from_struct(JNIEnv *env, jobject param, duckdb::ClientContext &context) { +static Value create_value_from_struct(JNIEnv *env, jobject param, Factory &factory) { jstring jstr = reinterpret_cast(env->CallObjectMethod(param, J_Struct_getSQLTypeName)); check_java_exception_and_rethrow(env); auto typeName = jstring_to_string(env, jstr); - duckdb::LogicalType type; - context.RunFunctionInTransaction([&]() { type = TransformStringToLogicalType(typeName, context); }); + auto type = factory.ParseType(typeName); jobjectArray jvalues = reinterpret_cast(env->CallObjectMethod(param, J_Struct_getAttributes)); check_java_exception_and_rethrow(env); int size = env->GetArrayLength(jvalues); - duckdb::child_list_t values; + std::vector> values; for (int i = 0; i < size; i++) { - auto name = duckdb::StructType::GetChildName(type, i); + auto name = type.GetStructChildName(static_cast(i)); auto jvalue = env->GetObjectArrayElement(jvalues, i); - auto value = to_duckdb_value(env, jvalue, context); + auto value = to_duckdb_value(env, jvalue, factory); env->DeleteLocalRef(jvalue); - values.emplace_back(name, std::move(value)); + values.emplace_back(name, value.Cast(factory, type.GetStructChildType(static_cast(i)))); } - return duckdb::Value::STRUCT(std::move(values)); + return Value::CreateStruct(factory, values); } -static duckdb::Value create_value_from_array(JNIEnv *env, jobject param, duckdb::ClientContext &context) { +static Value create_value_from_array(JNIEnv *env, jobject param, Factory &factory) { jstring jstr = reinterpret_cast(env->CallObjectMethod(param, J_Array_getBaseTypeName)); check_java_exception_and_rethrow(env); auto typeName = jstring_to_string(env, jstr); @@ -170,92 +264,94 @@ static duckdb::Value create_value_from_array(JNIEnv *env, jobject param, duckdb: check_java_exception_and_rethrow(env); int size = env->GetArrayLength(jvalues); - duckdb::LogicalType type; - context.RunFunctionInTransaction([&]() { type = TransformStringToLogicalType(typeName, context); }); + auto type = factory.ParseType(typeName); - duckdb::vector values; + std::vector values; for (int i = 0; i < size; i++) { auto jvalue = env->GetObjectArrayElement(jvalues, i); - auto value = to_duckdb_value(env, jvalue, context); + auto value = to_duckdb_value(env, jvalue, factory); env->DeleteLocalRef(jvalue); - values.emplace_back(std::move(value)); + values.emplace_back(value.Cast(factory, type)); } - return (duckdb::Value::LIST(type, values)); + if (values.empty()) { + return Value::CreateList(factory, type); + } + return Value::CreateList(factory, values); } -duckdb::Value to_duckdb_value(JNIEnv *env, jobject param, duckdb::ClientContext &context) { +Value to_duckdb_value(JNIEnv *env, jobject param, Factory &factory) { param = env->CallStaticObjectMethod(J_Timestamp, J_Timestamp_valueOf, param); check_java_exception_and_rethrow(env); if (param == nullptr) { - return (duckdb::Value()); + return create_null_value(factory); } else if (env->IsInstanceOf(param, J_Bool)) { jboolean val = env->CallBooleanMethod(param, J_Bool_booleanValue); check_java_exception_and_rethrow(env); - return duckdb::Value::BOOLEAN(val); + return Value::Create(factory, static_cast(val)); } else if (env->IsInstanceOf(param, J_Byte)) { jbyte val = env->CallByteMethod(param, J_Byte_byteValue); check_java_exception_and_rethrow(env); - return duckdb::Value::TINYINT(val); + return Value::Create(factory, static_cast(val)); } else if (env->IsInstanceOf(param, J_Short)) { jshort val = env->CallShortMethod(param, J_Short_shortValue); check_java_exception_and_rethrow(env); - return duckdb::Value::SMALLINT(val); + return Value::Create(factory, static_cast(val)); } else if (env->IsInstanceOf(param, J_Int)) { jint val = env->CallIntMethod(param, J_Int_intValue); check_java_exception_and_rethrow(env); - return duckdb::Value::INTEGER(val); + return Value::Create(factory, static_cast(val)); } else if (env->IsInstanceOf(param, J_Long)) { jlong val = env->CallLongMethod(param, J_Long_longValue); check_java_exception_and_rethrow(env); - return duckdb::Value::BIGINT(val); + return Value::Create(factory, static_cast(val)); } else if (env->IsInstanceOf(param, J_HugeInt)) { - return create_value_from_hugeint(env, param); + return create_value_from_hugeint(env, param, factory); } else if (env->IsInstanceOf(param, J_TimestampTZ)) { // Check for subclass before superclass! jlong val = env->CallLongMethod(param, J_TimestampTZ_getMicrosEpoch); check_java_exception_and_rethrow(env); - return duckdb::Value::TIMESTAMPTZ(static_cast(val)); + return Value::Create(factory, duckdb::cxx::timestamp_tz_t {static_cast(val)}); } else if (env->IsInstanceOf(param, J_DuckDBDate)) { jlong val = env->CallLongMethod(param, J_DuckDBDate_getDaysSinceEpoch); check_java_exception_and_rethrow(env); - return duckdb::Value::DATE(static_cast(val)); + return Value::Create(factory, duckdb::cxx::date_t {static_cast(val)}); } else if (env->IsInstanceOf(param, J_DuckDBTime)) { jlong val = env->CallLongMethod(param, J_Timestamp_getMicrosEpoch); check_java_exception_and_rethrow(env); - return duckdb::Value::TIME(static_cast(val)); + return Value::Create(factory, duckdb::cxx::dtime_t {static_cast(val)}); } else if (env->IsInstanceOf(param, J_TimestampNS)) { // Check for subclass before superclass! jlong val = env->CallLongMethod(param, J_TimestampNS_getNanosEpoch); check_java_exception_and_rethrow(env); - return duckdb::Value::TIMESTAMPNS(static_cast(val)); + return Value::Create(factory, duckdb::cxx::timestamp_ns_t {static_cast(val)}); } else if (env->IsInstanceOf(param, J_Timestamp)) { jlong val = env->CallLongMethod(param, J_Timestamp_getMicrosEpoch); check_java_exception_and_rethrow(env); - return duckdb::Value::TIMESTAMP(static_cast(val)); + return Value::Create(factory, duckdb::cxx::timestamp_t {static_cast(val)}); } else if (env->IsInstanceOf(param, J_Float)) { jfloat val = env->CallFloatMethod(param, J_Float_floatValue); check_java_exception_and_rethrow(env); - return duckdb::Value::FLOAT(val); + return Value::Create(factory, static_cast(val)); } else if (env->IsInstanceOf(param, J_Double)) { jdouble val = env->CallDoubleMethod(param, J_Double_doubleValue); check_java_exception_and_rethrow(env); - return duckdb::Value::DOUBLE(val); + return Value::Create(factory, static_cast(val)); } else if (env->IsInstanceOf(param, J_BigDecimal)) { - return create_value_from_bigdecimal(env, param); + return create_value_from_bigdecimal(env, param, factory); } else if (env->IsInstanceOf(param, J_String)) { auto param_string = jstring_to_string(env, (jstring)param); - return (duckdb::Value(param_string)); + return Value::Create(factory, duckdb::cxx::varchar_t(param_string)); } else if (env->IsInstanceOf(param, J_ByteArray)) { - return (duckdb::Value::BLOB_RAW(jbyteArray_to_string(env, (jbyteArray)param))); + return Value::Create(factory, duckdb::cxx::blob_t(jbyteArray_to_string(env, (jbyteArray)param))); } else if (env->IsInstanceOf(param, J_UUID)) { - return create_value_from_uuid(env, param); + return create_value_from_uuid(env, param, factory); } else if (env->IsInstanceOf(param, J_DuckMap)) { - return create_value_from_map(env, param, context); + return create_value_from_map(env, param, factory); } else if (env->IsInstanceOf(param, J_Struct)) { - return create_value_from_struct(env, param, context); + return create_value_from_struct(env, param, factory); } else if (env->IsInstanceOf(param, J_Array)) { - return create_value_from_array(env, param, context); + return create_value_from_array(env, param, factory); } else { - throw duckdb::InvalidInputException("Unsupported parameter type"); + throw JdbcException("Invalid Input Error: Unsupported parameter type"); } } diff --git a/src/jni/types.hpp b/src/jni/types.hpp index adbf36da9..c9e87ef47 100644 --- a/src/jni/types.hpp +++ b/src/jni/types.hpp @@ -1,11 +1,16 @@ #pragma once -#include "duckdb.hpp" +#include "duckdb_cpp.hpp" #include +#include -std::string type_to_jduckdb_type(duckdb::LogicalType logical_type); +//! The type name that is used by the Java side, DECIMAL types also have the width and the scale +std::string type_to_jduckdb_type(const duckdb::cxx::LogicalType &logical_type); -duckdb::Value create_value_from_bigdecimal(JNIEnv *env, jobject decimal); +//! The name of the type, same as the string representation of the type ID in the engine +std::string type_id_to_string(duckdb::cxx::LogicalTypeId id); -duckdb::Value to_duckdb_value(JNIEnv *env, jobject param, duckdb::ClientContext &context); +duckdb::cxx::Value create_value_from_bigdecimal(JNIEnv *env, jobject decimal, duckdb::cxx::Factory &factory); + +duckdb::cxx::Value to_duckdb_value(JNIEnv *env, jobject param, duckdb::cxx::Factory &factory); diff --git a/src/main/java/org/duckdb/DuckDBResultSet.java b/src/main/java/org/duckdb/DuckDBResultSet.java index 3e9560ea8..b7e624c50 100644 --- a/src/main/java/org/duckdb/DuckDBResultSet.java +++ b/src/main/java/org/duckdb/DuckDBResultSet.java @@ -130,7 +130,7 @@ private void check(int columnIndex) throws SQLException { * When the connection is closed before the reader, the reader fails to load next batches. * * @param arrow_buffer_allocator an instance of {@link org.apache.arrow.memory.BufferAllocator} - * @param arrow_batch_size batch size of arrow vectors to return + * @param arrow_batch_size maximum number of rows of the arrow vectors to return, the batches can be smaller * @return an instance of {@link org.apache.arrow.vector.ipc.ArrowReader} */ public synchronized Object arrowExportStream(Object arrow_buffer_allocator, long arrow_batch_size) diff --git a/src/test/external/TestArrow.java b/src/test/external/TestArrow.java index b405a15de..ada83e9d7 100644 --- a/src/test/external/TestArrow.java +++ b/src/test/external/TestArrow.java @@ -657,7 +657,13 @@ public static void test_arrow_export_batch_size() throws Exception { sum += vec.get(i); } } - assertListsEqual(batchSizes, asList(4096, 4096, 1808)); + // batches are filled by the threads of the query, so they can be smaller than the batch size + int rows = 0; + for (int size : batchSizes) { + assertTrue(size > 0 && size <= 4096, "batch size: " + size); + rows += size; + } + assertEquals(rows, 10000); assertEquals(sum, 9999L * 10000L / 2); } } @@ -687,7 +693,7 @@ public static void test_arrow_export_streaming_result() throws Exception { } assertEquals(count, 100000L); assertEquals(sum, 99999L * 100000L / 2); - assertEquals(batches, 10); + assertTrue(batches >= 10); } } diff --git a/src/test/java/org/duckdb/TestDuckDBJDBC.java b/src/test/java/org/duckdb/TestDuckDBJDBC.java index f37db5886..298f42252 100644 --- a/src/test/java/org/duckdb/TestDuckDBJDBC.java +++ b/src/test/java/org/duckdb/TestDuckDBJDBC.java @@ -2469,7 +2469,7 @@ public static void test_query_progress() throws Exception { assertThrows(() -> stmt.executeQuery("WITH RECURSIVE cte AS NOT MATERIALIZED (" + "SELECT * from test_fib1 UNION ALL SELECT cte.i + 1, cte.f, " - + "cte.p + cte.f from cte WHERE cte.i < 1000000) " + + "cte.p + cte.f from cte WHERE cte.i < 1000000000) " + "SELECT avg(f) FROM cte"), SQLException.class); diff --git a/vendor.py b/vendor.py index 90835d9fb..bb36bac27 100644 --- a/vendor.py +++ b/vendor.py @@ -14,6 +14,7 @@ def sanitize_path(x): help='Path to the DuckDB Version to be vendored in', required=True, type=str) args = parser.parse_args() +args.duckdb = os.path.abspath(args.duckdb) # list of extensions to bundle extensions = ['core_functions', 'parquet', 'icu', 'json'] @@ -40,6 +41,14 @@ def sanitize_path(x): jemalloc_source_list = [x for x in source_list if x.startswith("duckdb/third_party/jemalloc/")] jemalloc_include_list = [x for x in include_list if x.startswith("third_party/jemalloc/")] +# the stable C++ API is compiled into the driver, it is not a part of the engine sources +import shutil +cpp_api_dir = os.path.join(target_dir, 'tools', 'cpp') +shutil.rmtree(cpp_api_dir, ignore_errors=True) +os.makedirs(cpp_api_dir) +for cpp_api_file in ['duckdb_cpp.cpp', 'duckdb_cpp.hpp', 'duckdb_cpp_extension.hpp']: + shutil.copyfile(os.path.join(args.duckdb, 'tools', 'cpp', cpp_api_file), os.path.join(cpp_api_dir, cpp_api_file)) + # clean up paths source_list = [os.path.relpath(x, basedir) if os.path.isabs(x) else os.path.join('src', x) for x in source_list if x not in jemalloc_source_list]