From 0395d07e198b2982421d6cdf827f4ecc02acad1a Mon Sep 17 00:00:00 2001 From: Robinho-MR Date: Wed, 25 Nov 2026 13:35:19 +0000 Subject: [PATCH 1/8] Port the native part of the driver to the stable C++ API --- CMakeLists.txt | 2 + CMakeLists.txt.in | 2 + .../duckdb/main/capi_v2/extension_api_v2.hpp | 3 + src/duckdb/src/include/duckdb_extension_v2.h | 8 + src/duckdb/src/include/duckdb_v2.h | 45 + .../src/main/capi/v2/capi_v2_connection.cpp | 10 + src/duckdb/src/main/capi/v2/capi_v2_value.cpp | 24 + src/duckdb/tools/cpp/duckdb_cpp.cpp | 7730 ++++++++++++++++ src/duckdb/tools/cpp/duckdb_cpp.hpp | 7735 +++++++++++++++++ src/duckdb/tools/cpp/duckdb_cpp_extension.hpp | 48 + src/jni/arrow.cpp | 564 +- src/jni/arrow.hpp | 93 +- src/jni/bindings_appender.cpp | 254 +- src/jni/bindings_result.cpp | 6 + src/jni/config.cpp | 230 +- src/jni/config.hpp | 16 +- src/jni/cxx_handles.hpp | 34 + src/jni/duckdb_java.cpp | 1279 +-- src/jni/functions.cpp | 144 +- src/jni/functions.cpp.template | 3 +- src/jni/functions.hpp | 5 +- src/jni/functions.hpp.template | 5 +- src/jni/holders.cpp | 55 +- src/jni/holders.hpp | 147 +- src/jni/types.cpp | 278 +- src/jni/types.hpp | 13 +- vendor.py | 9 + 27 files changed, 17554 insertions(+), 1188 deletions(-) create mode 100644 src/duckdb/tools/cpp/duckdb_cpp.cpp create mode 100644 src/duckdb/tools/cpp/duckdb_cpp.hpp create mode 100644 src/duckdb/tools/cpp/duckdb_cpp_extension.hpp create mode 100644 src/jni/cxx_handles.hpp diff --git a/CMakeLists.txt b/CMakeLists.txt index 25e834785..37572bf5b 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/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 eed383294..818907de2 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_connection_get_context) + (duckdb_v2_connection_handle conn, duckdb_v2_context_handle *out_context, 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_connection_get_context = duckdb_v2_connection_get_context; return result; } diff --git a/src/duckdb/src/include/duckdb_extension_v2.h b/src/duckdb/src/include/duckdb_extension_v2.h index 851782c11..7cf2b809d 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_connection_get_context) + (duckdb_v2_connection_handle conn, duckdb_v2_context_handle *out_context, duckdb_v2_error_info_handle *err); #endif // capigen:end appended } duckdb_ext_api_v2; @@ -4066,6 +4068,12 @@ 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_connection_get_context duckdb_ext_api.duckdb_v2_connection_get_context +#endif +#if DUCKDB_V2_API_ALLOW_UNSTABLE +#define duckdb_v2_value_unpack_variant duckdb_ext_api.duckdb_v2_value_unpack_variant +#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 35e3fb21a..ed1ad74d4 100644 --- a/src/duckdb/src/include/duckdb_v2.h +++ b/src/duckdb/src/include/duckdb_v2.h @@ -1981,6 +1981,29 @@ DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_connection_create(duckdb_v2_instance_hand DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_connection_destroy(duckdb_v2_connection_handle *conn); #endif +#if DUCKDB_V2_API_ALLOW_UNSTABLE +/*! + * Borrows the context of a connection. + * + * The context is the handle that the functions which a callback runs under take, such as the Arrow exporter and + * importer, so it lets a client use them outside of a callback, for the queries of one connection. Each call that is + * made with it joins the connection's transaction, or runs in a transaction of its own when none is open. The returned + * handle is borrowed: it is valid for as long as the connection is, and must not be destroyed. + * + * history: + * - unstable: v2.0.0 + * + * @param conn The connection. + * @param out_context Receives the borrowed context. + * @param err Optional. On failure, receives an opaque info handle the caller must destroy via + * `duckdb_v2_error_info_destroy()`. + * @return DUCKDB_V2_ERROR + */ +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_connection_get_context(duckdb_v2_connection_handle conn, + duckdb_v2_context_handle *out_context, + duckdb_v2_error_info_handle *err); +#endif + #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! * Interrupts the query currently executing on the connection. @@ -18977,6 +19000,28 @@ 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. A nested value is unpacked all the way down, so a + * variant that holds a list of variants gives a list of typed values. A NULL VARIANT gives a NULL value. A value that + * is not a VARIANT returns ERROR_INPUT_INVALID. The returned value is caller-owned; destroy it via value_destroy. + * + * history: + * - unstable: v2.0.0 + * + * @param value The VARIANT value to unpack. + * @param out_unpacked 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_unpack_variant(duckdb_v2_value_handle value, + duckdb_v2_value_handle *out_unpacked, + 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_connection.cpp b/src/duckdb/src/main/capi/v2/capi_v2_connection.cpp index 2d88d63cb..e6914a467 100644 --- a/src/duckdb/src/main/capi/v2/capi_v2_connection.cpp +++ b/src/duckdb/src/main/capi/v2/capi_v2_connection.cpp @@ -26,6 +26,16 @@ DUCKDB_V2_ERROR duckdb_v2_connection_destroy(duckdb_v2_connection_handle *conn) }); } +DUCKDB_V2_ERROR duckdb_v2_connection_get_context(duckdb_v2_connection_handle conn, + duckdb_v2_context_handle *out_context, + duckdb_v2_error_info_handle *err) { + DUCKDB_CHECK_ARG(conn); + DUCKDB_CHECK_ARG(out_context); + *out_context = nullptr; + return WithErrorHandler( + err, [&]() { *out_context = Convert(static_cast(&Convert(conn)->context_handle)); }); +} + // --------------------------------------------------------------------------- // Query process management // --------------------------------------------------------------------------- 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 f90c79071..85220bb17 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_unpack_variant(duckdb_v2_value_handle value, duckdb_v2_value_handle *out_unpacked, + duckdb_v2_error_info_handle *err) { + DUCKDB_CHECK_ARG(value); + DUCKDB_CHECK_ARG(out_unpacked); + *out_unpacked = nullptr; + return WithErrorHandler(err, [&]() { + auto &v = *Convert(value); + if (v.type().id() != duckdb::LogicalTypeId::VARIANT) { + throw duckdb::InvalidInputException("duckdb_v2_value_unpack_variant expects a VARIANT value"); + } + if (v.IsNull()) { + *out_unpacked = 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_unpacked = 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..d2dc81120 --- /dev/null +++ b/src/duckdb/tools/cpp/duckdb_cpp.cpp @@ -0,0 +1,7730 @@ +// 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; +} + +// Borrows the context of a connection handle. +auto GetContextHandle(void *connection) -> duckdb_v2_context_handle { + duckdb_v2_context_handle context = nullptr; + CheckedAPICall(duckdb_v2_connection_get_context, static_cast(connection), &context); + return context; +} + +// 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))), + context(detail::HandleFactory::Make(GetContextHandle(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::UnpackVariant() const -> Value { + duckdb_v2_value_handle unpacked = nullptr; + CheckedAPICall(duckdb_v2_value_unpack_variant, handle(), &unpacked); + return detail::HandleFactory::Make(unpacked); +} + +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, uint8_t width, uint8_t scale) const { + duckdb_v2_hugeint_t payload {}; + uint8_t actual_width = 0; + uint8_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, uint8_t width, uint8_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..bec0666c9 --- /dev/null +++ b/src/duckdb/tools/cpp/duckdb_cpp.hpp @@ -0,0 +1,7735 @@ +#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)), context(std::move(other.context)) { + 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(context, other.context); + 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; + } + + /// The context of this connection, for what takes a context outside of a callback, such as `ArrowExporter`. + /// Each use joins the connection's transaction, or runs in a transaction of its own when none is open. Borrowed, + /// and valid only while the connection is. + auto GetContext() -> Context & { + return context; + } + + /// 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; + Context context; + + 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; + uint8_t width; + uint8_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. + 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, in [1, 255]; 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, uint8_t width, uint8_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 nested value is unpacked all the way down. A NULL VARIANT gives a NULL value. + /// @throws InvalidInputException When the value is not a VARIANT. + auto UnpackVariant() 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, uint8_t width, uint8_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..d370a4884 100644 --- a/src/jni/arrow.cpp +++ b/src/jni/arrow.cpp @@ -1,184 +1,466 @@ #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" -void JavaResultArrowStream::Close() { - std::lock_guard guard(lock); - closed = true; - chunk = nullptr; - res = nullptr; - res_stream = nullptr; -} +#include +#include +#include +#include +#include -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; -} - -JavaResultArrowStream &JavaResultArrowStream::GetState(ArrowArrayStream *stream) { - return *reinterpret_cast(stream->private_data)->state; -} +/** + * State of an Arrow stream that exports the chunks of a result. The result is moved out of the Java-owned holder. + */ +class JavaResultArrowStream : public ArrowStreamState { +public: + JavaResultArrowStream(std::shared_ptr connection_p, ResultHolder &source, idx_t batch_size) + : connection(std::move(connection_p)), batch_size(batch_size) { + names = std::move(source.names); + types = std::move(source.types); + stream = std::move(source.stream); + source.stream.reset(); + materialized = std::move(source.materialized); + first_chunk = std::move(source.first_chunk); + source.first_chunk.reset(); + std::vector exporter_types; + for (auto &type : types) { + exporter_types.push_back(type.Copy()); + } + exporter.emplace(connection->GetContext(), exporter_types, names, batch_size); + } -int JavaResultArrowStream::GetSchema(ArrowArrayStream *stream, ArrowSchema *out) { - if (!stream->release) { - return -1; + void Close() override { + std::lock_guard guard(lock); + closed = true; + exporter.reset(); + stream.reset(); + materialized.reset(); + first_chunk.reset(); } - 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; + + //! 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; } - return 0; -} -int JavaResultArrowStream::GetNext(ArrowArrayStream *stream, ArrowArray *out) { - if (!stream->release) { - return -1; +private: + 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; - if (self.closed) { - self.last_error = ErrorData(ConnectionException("Connection was closed")); - return -1; + + static int GetSchema(ArrowArrayStream *stream, ArrowSchema *out) { + if (!stream->release) { + return -1; + } + auto &self = GetState(stream); + std::lock_guard guard(self.lock); + out->release = nullptr; + try { + if (self.closed) { + throw JdbcException("Connection Error: Connection was closed"); + } + self.exporter->GetSchema(*out); + } catch (const std::exception &e) { + self.last_error = e.what(); + return EIO; + } + return 0; } - 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; + + static int GetNext(ArrowArrayStream *stream, ArrowArray *out) { + if (!stream->release) { + return -1; + } + auto &self = GetState(stream); + std::lock_guard guard(self.lock); + out->release = nullptr; + try { + if (self.closed) { + throw JdbcException("Connection Error: Connection was closed"); + } + while (true) { + if (self.exporter->NextArray(*out)) { + return 0; } - if (!self.chunk) { - break; + if (self.finished) { + // the end of the stream + out->release = nullptr; + return 0; } - continue; + auto chunk = self.NextChunk(); + if (!chunk) { + self.finished = true; + self.exporter->Flush(); + continue; + } + self.exporter->Append(*chunk); + } + } catch (const std::exception &e) { + self.last_error = e.what(); + return EIO; + } + } + + 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; + } + + //! Loads the next chunk of the result, the chunk is empty at the end of the result + std::optional NextChunk() { + if (materialized) { + auto chunk = connection->GetFactory().CreateDataChunk(types); + if (materialized->collection->Scan(*materialized->shared_state, *materialized->worker_state, chunk) && + chunk.GetRowCount() > 0) { + return std::optional(std::move(chunk)); } - 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; + return std::nullopt; + } + if (first_chunk) { + auto chunk = std::move(*first_chunk); + first_chunk.reset(); + return std::optional(std::move(chunk)); } - if (count > 0) { - *out = appender.Finalize(); + auto chunk = stream->FetchChunk(); + if (!chunk) { + return std::nullopt; } - } catch (std::exception &e) { - self.last_error = ErrorData(e); - return -1; + return std::optional(std::move(chunk)); } - return 0; + + std::mutex lock; + std::shared_ptr connection; + std::vector names; + std::vector types; + std::optional stream; + std::unique_ptr materialized; + std::optional first_chunk; + std::optional exporter; + idx_t batch_size; + bool finished = false; + 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.connection, result, batch_size); + conn_holder.track_arrow_stream(state); + return JavaResultArrowStream::Export(std::move(state)); } -const char *JavaResultArrowStream::GetLastError(ArrowArrayStream *stream) { - if (!stream->release) { - return "stream was released"; +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; + } + + ~JavaRegisteredArrowStream() override { + Close(); + } + + 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"); + } + 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")); + } + } + + //! 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; } - auto &self = GetState(stream); - std::lock_guard guard(self.lock); - return self.last_error.HasError() ? self.last_error.Message().c_str() : nullptr; + + 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; } -void JavaResultArrowStream::Release(ArrowArrayStream *stream) { - if (!stream || !stream->release) { - return; +void JavaRegisteredArrowStream::Close() { + { + std::lock_guard guard(lock); + if (stream.release) { + stream.release(&stream); + stream.release = nullptr; + } + } + arrow_stream_registry().Remove(id); +} + +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 ba6398302..a8d28aa03 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,108 @@ 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 + auto &src_config = conn_ref->connection->GetConfig(); + auto &dst_config = conn->connection->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 env->NewDirectByteBuffer(conn.release(), 0); } jobject _duckdb_jdbc_create_db_ref(JNIEnv *env, jclass, jobject conn_ref_buf) { @@ -104,8 +171,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 +185,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,265 +241,229 @@ 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 runs all its statements but the last one, returns the last statement +static cxx::SqlStatement extract_last_statement(cxx::Connection &conn, const std::string &query) { + 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."); } // 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(); - } + for (size_t i = 0; i + 1 < statements.size(); i++) { + conn.Execute(statements[i]).Drain(); } + return std::move(statements.back()); +} - 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; - } +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)); + 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); - 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())) { + 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)); } - if (stream->HasError()) { - throw_execution_java_error(env, stream.get()); - return nullptr; - } - 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) { @@ -508,22 +496,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); @@ -540,10 +528,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()); @@ -554,7 +542,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); @@ -567,92 +555,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); @@ -661,36 +658,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) { - return nullptr; - } - - auto conn_ref = get_connection(env, conn_ref_buf); - if (conn_ref == nullptr) { + auto &res_ref = get_result(env, res_ref_buf); + if (!res_ref.chunk) { return nullptr; } + auto &conn = get_connection(env, conn_ref_buf); - 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); } @@ -698,22 +697,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); @@ -721,10 +749,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; @@ -753,32 +784,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; } @@ -786,31 +815,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); @@ -821,23 +850,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); @@ -853,16 +892,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); @@ -870,18 +908,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; } @@ -899,19 +936,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); @@ -922,45 +972,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).UnpackVariant(); 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); } @@ -982,205 +1019,275 @@ 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))); + 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..67b89b59f 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,22 @@ 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) { +cxx::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"); + if (!conn_holder->connection) { + throw JdbcException("Invalid connection"); } - - return conn_ref; + 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 +75,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..701c138cd 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,28 @@ 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) { + } +}; + 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/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] From a6079a54cfe53092c858340089a9831cffbbabc5 Mon Sep 17 00:00:00 2001 From: Robinho-MR Date: Wed, 25 Nov 2026 15:48:11 +0000 Subject: [PATCH 2/8] Export Arrow results with a query over the rows instead of a context exporter --- .../duckdb/main/capi_v2/extension_api_v2.hpp | 3 - src/duckdb/src/include/duckdb_extension_v2.h | 3 - src/duckdb/src/include/duckdb_v2.h | 23 --- .../src/main/capi/v2/capi_v2_connection.cpp | 10 -- src/duckdb/tools/cpp/duckdb_cpp.cpp | 9 +- src/duckdb/tools/cpp/duckdb_cpp.hpp | 12 +- src/jni/arrow.cpp | 159 ++++++++---------- src/jni/duckdb_java.cpp | 20 +-- src/jni/holders.cpp | 21 +++ src/jni/holders.hpp | 5 + src/main/java/org/duckdb/DuckDBResultSet.java | 2 +- src/test/external/TestArrow.java | 10 +- 12 files changed, 112 insertions(+), 165 deletions(-) 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 818907de2..eed383294 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,8 +1713,6 @@ 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_connection_get_context) - (duckdb_v2_connection_handle conn, duckdb_v2_context_handle *out_context, duckdb_v2_error_info_handle *err); } duckdb_ext_api_v2; //===--------------------------------------------------------------------===// @@ -2484,7 +2482,6 @@ 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_connection_get_context = duckdb_v2_connection_get_context; return result; } diff --git a/src/duckdb/src/include/duckdb_extension_v2.h b/src/duckdb/src/include/duckdb_extension_v2.h index 7cf2b809d..b99870270 100644 --- a/src/duckdb/src/include/duckdb_extension_v2.h +++ b/src/duckdb/src/include/duckdb_extension_v2.h @@ -1787,8 +1787,6 @@ 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_connection_get_context) - (duckdb_v2_connection_handle conn, duckdb_v2_context_handle *out_context, duckdb_v2_error_info_handle *err); #endif // capigen:end appended } duckdb_ext_api_v2; @@ -4069,7 +4067,6 @@ typedef struct { #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_connection_get_context duckdb_ext_api.duckdb_v2_connection_get_context #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE #define duckdb_v2_value_unpack_variant duckdb_ext_api.duckdb_v2_value_unpack_variant diff --git a/src/duckdb/src/include/duckdb_v2.h b/src/duckdb/src/include/duckdb_v2.h index ed1ad74d4..c2d8babd0 100644 --- a/src/duckdb/src/include/duckdb_v2.h +++ b/src/duckdb/src/include/duckdb_v2.h @@ -1981,29 +1981,6 @@ DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_connection_create(duckdb_v2_instance_hand DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_connection_destroy(duckdb_v2_connection_handle *conn); #endif -#if DUCKDB_V2_API_ALLOW_UNSTABLE -/*! - * Borrows the context of a connection. - * - * The context is the handle that the functions which a callback runs under take, such as the Arrow exporter and - * importer, so it lets a client use them outside of a callback, for the queries of one connection. Each call that is - * made with it joins the connection's transaction, or runs in a transaction of its own when none is open. The returned - * handle is borrowed: it is valid for as long as the connection is, and must not be destroyed. - * - * history: - * - unstable: v2.0.0 - * - * @param conn The connection. - * @param out_context Receives the borrowed context. - * @param err Optional. On failure, receives an opaque info handle the caller must destroy via - * `duckdb_v2_error_info_destroy()`. - * @return DUCKDB_V2_ERROR - */ -DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_connection_get_context(duckdb_v2_connection_handle conn, - duckdb_v2_context_handle *out_context, - duckdb_v2_error_info_handle *err); -#endif - #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! * Interrupts the query currently executing on the connection. diff --git a/src/duckdb/src/main/capi/v2/capi_v2_connection.cpp b/src/duckdb/src/main/capi/v2/capi_v2_connection.cpp index e6914a467..2d88d63cb 100644 --- a/src/duckdb/src/main/capi/v2/capi_v2_connection.cpp +++ b/src/duckdb/src/main/capi/v2/capi_v2_connection.cpp @@ -26,16 +26,6 @@ DUCKDB_V2_ERROR duckdb_v2_connection_destroy(duckdb_v2_connection_handle *conn) }); } -DUCKDB_V2_ERROR duckdb_v2_connection_get_context(duckdb_v2_connection_handle conn, - duckdb_v2_context_handle *out_context, - duckdb_v2_error_info_handle *err) { - DUCKDB_CHECK_ARG(conn); - DUCKDB_CHECK_ARG(out_context); - *out_context = nullptr; - return WithErrorHandler( - err, [&]() { *out_context = Convert(static_cast(&Convert(conn)->context_handle)); }); -} - // --------------------------------------------------------------------------- // Query process management // --------------------------------------------------------------------------- diff --git a/src/duckdb/tools/cpp/duckdb_cpp.cpp b/src/duckdb/tools/cpp/duckdb_cpp.cpp index d2dc81120..b6602f4bd 100644 --- a/src/duckdb/tools/cpp/duckdb_cpp.cpp +++ b/src/duckdb/tools/cpp/duckdb_cpp.cpp @@ -306,13 +306,6 @@ auto GetConfigHandle(GETTER getter, void *source) -> duckdb_v2_config_handle { return config; } -// Borrows the context of a connection handle. -auto GetContextHandle(void *connection) -> duckdb_v2_context_handle { - duckdb_v2_context_handle context = nullptr; - CheckedAPICall(duckdb_v2_connection_get_context, static_cast(connection), &context); - return context; -} - // Borrow a string as a length-delimited view for the C API. auto ToStr(const std::string &s) -> std::string_view { return s; @@ -1013,7 +1006,7 @@ Connection::Connection(void *impl, bool owned) GetFactoryHandle(duckdb_v2_connection_get_factory, impl))), config(detail::HandleFactory::Make( GetConfigHandle(duckdb_v2_connection_get_config, impl))), - context(detail::HandleFactory::Make(GetContextHandle(impl))), owned(owned) { + owned(owned) { } Connection::~Connection() { diff --git a/src/duckdb/tools/cpp/duckdb_cpp.hpp b/src/duckdb/tools/cpp/duckdb_cpp.hpp index bec0666c9..4abe7ad55 100644 --- a/src/duckdb/tools/cpp/duckdb_cpp.hpp +++ b/src/duckdb/tools/cpp/duckdb_cpp.hpp @@ -900,8 +900,7 @@ class Connection final : public detail::Handle { friend detail::HandleFactory; public: - Connection(Connection &&other) noexcept - : factory(std::move(other.factory)), config(std::move(other.config)), context(std::move(other.context)) { + Connection(Connection &&other) noexcept : factory(std::move(other.factory)), config(std::move(other.config)) { std::swap(impl, other.impl); std::swap(owned, other.owned); } @@ -910,7 +909,6 @@ class Connection final : public detail::Handle { std::swap(impl, other.impl); std::swap(factory, other.factory); std::swap(config, other.config); - std::swap(context, other.context); std::swap(owned, other.owned); return *this; } @@ -933,13 +931,6 @@ class Connection final : public detail::Handle { return factory; } - /// The context of this connection, for what takes a context outside of a callback, such as `ArrowExporter`. - /// Each use joins the connection's transaction, or runs in a transaction of its own when none is open. Borrowed, - /// and valid only while the connection is. - auto GetContext() -> Context & { - return context; - } - /// 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. @@ -1149,7 +1140,6 @@ class Connection final : public detail::Handle { explicit Connection(void *impl, bool owned); Factory factory; Config config; - Context context; auto ExecuteArrowNamed(const SqlStatement &statement, const NamedParam *parameters, idx_t parameter_count, ArrowFormat format) -> ArrowResult; diff --git a/src/jni/arrow.cpp b/src/jni/arrow.cpp index d370a4884..01cf9498c 100644 --- a/src/jni/arrow.cpp +++ b/src/jni/arrow.cpp @@ -9,33 +9,62 @@ #include /** - * State of an Arrow stream that exports the chunks of a result. The result is moved out of the Java-owned holder. + * 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(std::shared_ptr connection_p, ResultHolder &source, idx_t batch_size) - : connection(std::move(connection_p)), batch_size(batch_size) { - names = std::move(source.names); - types = std::move(source.types); - stream = std::move(source.stream); - source.stream.reset(); - materialized = std::move(source.materialized); - first_chunk = std::move(source.first_chunk); - source.first_chunk.reset(); - std::vector exporter_types; - for (auto &type : types) { - exporter_types.push_back(type.Copy()); + 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(); } - exporter.emplace(connection->GetContext(), exporter_types, names, batch_size); + + 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); + } + + ~JavaResultArrowStream() override { + Close(); } void Close() override { std::lock_guard guard(lock); closed = true; - exporter.reset(); - stream.reset(); - materialized.reset(); - first_chunk.reset(); + // 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(); } //! Creates a stream that shares the state, the stream is deleted when it is released @@ -52,6 +81,8 @@ class JavaResultArrowStream : public ArrowStreamState { } private: + static constexpr const char *ROWS_TABLE_NAME = "__jdbc_result_rows"; + struct Exported { ArrowArrayStream stream; std::shared_ptr state; @@ -61,23 +92,29 @@ class JavaResultArrowStream : public ArrowStreamState { return *reinterpret_cast(stream->private_data)->state; } + //! 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); - std::lock_guard guard(self.lock); out->release = nullptr; - try { - if (self.closed) { - throw JdbcException("Connection Error: Connection was closed"); - } - self.exporter->GetSchema(*out); - } catch (const std::exception &e) { - self.last_error = e.what(); - return EIO; - } - return 0; + return self.Forward([&]() { return self.inner.get_schema(&self.inner, out); }); } static int GetNext(ArrowArrayStream *stream, ArrowArray *out) { @@ -85,33 +122,8 @@ class JavaResultArrowStream : public ArrowStreamState { return -1; } auto &self = GetState(stream); - std::lock_guard guard(self.lock); out->release = nullptr; - try { - if (self.closed) { - throw JdbcException("Connection Error: Connection was closed"); - } - while (true) { - if (self.exporter->NextArray(*out)) { - return 0; - } - if (self.finished) { - // the end of the stream - out->release = nullptr; - return 0; - } - auto chunk = self.NextChunk(); - if (!chunk) { - self.finished = true; - self.exporter->Flush(); - continue; - } - self.exporter->Append(*chunk); - } - } catch (const std::exception &e) { - self.last_error = e.what(); - return EIO; - } + return self.Forward([&]() { return self.inner.get_next(&self.inner, out); }); } static const char *GetLastError(ArrowArrayStream *stream) { @@ -132,44 +144,19 @@ class JavaResultArrowStream : public ArrowStreamState { delete exported; } - //! Loads the next chunk of the result, the chunk is empty at the end of the result - std::optional NextChunk() { - if (materialized) { - auto chunk = connection->GetFactory().CreateDataChunk(types); - if (materialized->collection->Scan(*materialized->shared_state, *materialized->worker_state, chunk) && - chunk.GetRowCount() > 0) { - return std::optional(std::move(chunk)); - } - return std::nullopt; - } - if (first_chunk) { - auto chunk = std::move(*first_chunk); - first_chunk.reset(); - return std::optional(std::move(chunk)); - } - auto chunk = stream->FetchChunk(); - if (!chunk) { - return std::nullopt; - } - return std::optional(std::move(chunk)); - } - std::mutex lock; - std::shared_ptr connection; std::vector names; - std::vector types; - std::optional stream; - std::unique_ptr materialized; - std::optional first_chunk; - std::optional exporter; - idx_t batch_size; - bool finished = false; + 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.connection, result, batch_size); + auto state = std::make_shared(conn_holder, result, batch_size); conn_holder.track_arrow_stream(state); return JavaResultArrowStream::Export(std::move(state)); } diff --git a/src/jni/duckdb_java.cpp b/src/jni/duckdb_java.cpp index a8d28aa03..44550509e 100644 --- a/src/jni/duckdb_java.cpp +++ b/src/jni/duckdb_java.cpp @@ -142,24 +142,7 @@ jobject _duckdb_jdbc_connect(JNIEnv *env, jclass, jobject conn_ref_buf) { auto conn = std::make_unique(conn_ref->db); // the session settings of the new connection are the same as the ones of this connection - auto &src_config = conn_ref->connection->GetConfig(); - auto &dst_config = conn->connection->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); - } + copy_session_settings(*conn_ref->connection, *conn->connection); return env->NewDirectByteBuffer(conn.release(), 0); } @@ -1264,6 +1247,7 @@ jlong _duckdb_jdbc_arrow_stream(JNIEnv *env, jclass, jobject res_ref_buf, jobjec throw JdbcException("Invalid Input Error: Arrow batch size must be greater than 0"); } auto conn_holder = get_connection_ref(env, conn_ref_buf); + 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))); } diff --git a/src/jni/holders.cpp b/src/jni/holders.cpp index 67b89b59f..93adb9064 100644 --- a/src/jni/holders.cpp +++ b/src/jni/holders.cpp @@ -57,6 +57,27 @@ void ConnectionHolder::close_arrow_streams() { } } +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); + } +} + cxx::Connection &get_connection(JNIEnv *env, jobject conn_ref_buf) { auto conn_holder = get_connection_ref(env, conn_ref_buf); if (!conn_holder->connection) { diff --git a/src/jni/holders.hpp b/src/jni/holders.hpp index 701c138cd..1d21cc369 100644 --- a/src/jni/holders.hpp +++ b/src/jni/holders.hpp @@ -231,6 +231,11 @@ struct JdbcException : public std::runtime_error { } }; +/** + * 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); /** 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); } } From bfafcf1eabce9329eb974b07f567738b6b707940 Mon Sep 17 00:00:00 2001 From: Robinho-MR Date: Thu, 26 Nov 2026 09:28:38 +0000 Subject: [PATCH 3/8] Use GetVariantContent --- src/duckdb/src/include/duckdb_extension_v2.h | 2 +- src/duckdb/src/include/duckdb_v2.h | 6 +++--- src/duckdb/src/main/capi/v2/capi_v2_value.cpp | 12 ++++++------ src/duckdb/tools/cpp/duckdb_cpp.cpp | 4 ++-- src/duckdb/tools/cpp/duckdb_cpp.hpp | 2 +- src/jni/duckdb_java.cpp | 2 +- 6 files changed, 14 insertions(+), 14 deletions(-) diff --git a/src/duckdb/src/include/duckdb_extension_v2.h b/src/duckdb/src/include/duckdb_extension_v2.h index b99870270..194219737 100644 --- a/src/duckdb/src/include/duckdb_extension_v2.h +++ b/src/duckdb/src/include/duckdb_extension_v2.h @@ -4069,7 +4069,7 @@ typedef struct { #if DUCKDB_V2_API_ALLOW_UNSTABLE #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE -#define duckdb_v2_value_unpack_variant duckdb_ext_api.duckdb_v2_value_unpack_variant +#define duckdb_v2_value_get_variant_content duckdb_ext_api.duckdb_v2_value_get_variant_content #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 c2d8babd0..34a6c3b28 100644 --- a/src/duckdb/src/include/duckdb_v2.h +++ b/src/duckdb/src/include/duckdb_v2.h @@ -18990,12 +18990,12 @@ DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_value_get_child(duckdb_v2_value_handle va * - unstable: v2.0.0 * * @param value The VARIANT value to unpack. - * @param out_unpacked Receives the owned value. + * @param out_content 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_unpack_variant(duckdb_v2_value_handle value, - duckdb_v2_value_handle *out_unpacked, +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_value_get_variant_content(duckdb_v2_value_handle value, + duckdb_v2_value_handle *out_content, duckdb_v2_error_info_handle *err); #endif 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 85220bb17..58437d69a 100644 --- a/src/duckdb/src/main/capi/v2/capi_v2_value.cpp +++ b/src/duckdb/src/main/capi/v2/capi_v2_value.cpp @@ -920,18 +920,18 @@ 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_unpack_variant(duckdb_v2_value_handle value, duckdb_v2_value_handle *out_unpacked, +DUCKDB_V2_ERROR duckdb_v2_value_get_variant_content(duckdb_v2_value_handle value, duckdb_v2_value_handle *out_content, duckdb_v2_error_info_handle *err) { DUCKDB_CHECK_ARG(value); - DUCKDB_CHECK_ARG(out_unpacked); - *out_unpacked = nullptr; + DUCKDB_CHECK_ARG(out_content); + *out_content = nullptr; return WithErrorHandler(err, [&]() { auto &v = *Convert(value); if (v.type().id() != duckdb::LogicalTypeId::VARIANT) { - throw duckdb::InvalidInputException("duckdb_v2_value_unpack_variant expects a VARIANT value"); + throw duckdb::InvalidInputException("duckdb_v2_value_get_variant_content expects a VARIANT value"); } if (v.IsNull()) { - *out_unpacked = Emit(duckdb::Value()); + *out_content = Emit(duckdb::Value()); return; } duckdb::Vector vec(v.type()); @@ -939,7 +939,7 @@ DUCKDB_V2_ERROR duckdb_v2_value_unpack_variant(duckdb_v2_value_handle value, duc duckdb::RecursiveUnifiedVectorFormat format; duckdb::Vector::RecursiveToUnifiedFormat(vec, format); duckdb::UnifiedVariantVectorData data(format); - *out_unpacked = Emit(duckdb::VariantUtils::ConvertVariantToValue(data, 0, 0)); + *out_content = Emit(duckdb::VariantUtils::ConvertVariantToValue(data, 0, 0)); }); } diff --git a/src/duckdb/tools/cpp/duckdb_cpp.cpp b/src/duckdb/tools/cpp/duckdb_cpp.cpp index b6602f4bd..b00585d9b 100644 --- a/src/duckdb/tools/cpp/duckdb_cpp.cpp +++ b/src/duckdb/tools/cpp/duckdb_cpp.cpp @@ -1832,9 +1832,9 @@ auto Value::GetChild(idx_t index) const -> Value { return detail::HandleFactory::Make(child); } -auto Value::UnpackVariant() const -> Value { +auto Value::GetVariantContent() const -> Value { duckdb_v2_value_handle unpacked = nullptr; - CheckedAPICall(duckdb_v2_value_unpack_variant, handle(), &unpacked); + CheckedAPICall(duckdb_v2_value_get_variant_content, handle(), &unpacked); return detail::HandleFactory::Make(unpacked); } diff --git a/src/duckdb/tools/cpp/duckdb_cpp.hpp b/src/duckdb/tools/cpp/duckdb_cpp.hpp index 4abe7ad55..1aa2c2691 100644 --- a/src/duckdb/tools/cpp/duckdb_cpp.hpp +++ b/src/duckdb/tools/cpp/duckdb_cpp.hpp @@ -2231,7 +2231,7 @@ class Value final : public detail::Handle { /// The value that a VARIANT value holds, with the type that it was stored with: a TINYINT, a VARCHAR, a LIST of /// STRUCTs, ... A nested value is unpacked all the way down. A NULL VARIANT gives a NULL value. /// @throws InvalidInputException When the value is not a VARIANT. - auto UnpackVariant() const -> Value; + auto GetVariantContent() const -> Value; /// Shorthand for `GetChild`. auto operator[](idx_t index) const -> Value { diff --git a/src/jni/duckdb_java.cpp b/src/jni/duckdb_java.cpp index 44550509e..6759c824e 100644 --- a/src/jni/duckdb_java.cpp +++ b/src/jni/duckdb_java.cpp @@ -957,7 +957,7 @@ static jobject process_vector_with_type(JNIEnv *env, cxx::Factory &factory, cxx: case LogicalTypeId::VARIANT: { varlen_data = env->NewObjectArray(row_count, J_Object, nullptr); for (idx_t row_idx = 0; row_idx < row_count; row_idx++) { - auto variant_val = vec.GetValue(row_idx).UnpackVariant(); + auto variant_val = vec.GetValue(row_idx).GetVariantContent(); if (variant_val.IsNull()) { continue; } From 8a1f9047a1d7efb74f1e90f63ed41fa09a0f22d8 Mon Sep 17 00:00:00 2001 From: Robinho-MR Date: Thu, 26 Nov 2026 09:57:05 +0000 Subject: [PATCH 4/8] Use VariantToValue --- src/duckdb/src/include/duckdb_extension_v2.h | 2 +- src/duckdb/src/include/duckdb_v2.h | 6 +++--- src/duckdb/src/main/capi/v2/capi_v2_value.cpp | 12 ++++++------ src/duckdb/tools/cpp/duckdb_cpp.cpp | 4 ++-- src/duckdb/tools/cpp/duckdb_cpp.hpp | 2 +- src/jni/duckdb_java.cpp | 2 +- 6 files changed, 14 insertions(+), 14 deletions(-) diff --git a/src/duckdb/src/include/duckdb_extension_v2.h b/src/duckdb/src/include/duckdb_extension_v2.h index 194219737..b2169a1c9 100644 --- a/src/duckdb/src/include/duckdb_extension_v2.h +++ b/src/duckdb/src/include/duckdb_extension_v2.h @@ -4069,7 +4069,7 @@ typedef struct { #if DUCKDB_V2_API_ALLOW_UNSTABLE #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE -#define duckdb_v2_value_get_variant_content duckdb_ext_api.duckdb_v2_value_get_variant_content +#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 34a6c3b28..fccd7881c 100644 --- a/src/duckdb/src/include/duckdb_v2.h +++ b/src/duckdb/src/include/duckdb_v2.h @@ -18990,12 +18990,12 @@ DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_value_get_child(duckdb_v2_value_handle va * - unstable: v2.0.0 * * @param value The VARIANT value to unpack. - * @param out_content Receives the owned value. + * @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_get_variant_content(duckdb_v2_value_handle value, - duckdb_v2_value_handle *out_content, +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 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 58437d69a..163fea104 100644 --- a/src/duckdb/src/main/capi/v2/capi_v2_value.cpp +++ b/src/duckdb/src/main/capi/v2/capi_v2_value.cpp @@ -920,18 +920,18 @@ 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_get_variant_content(duckdb_v2_value_handle value, duckdb_v2_value_handle *out_content, +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_content); - *out_content = nullptr; + 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_get_variant_content expects a VARIANT value"); + throw duckdb::InvalidInputException("duckdb_v2_value_variant_to_value expects a VARIANT value"); } if (v.IsNull()) { - *out_content = Emit(duckdb::Value()); + *out_value = Emit(duckdb::Value()); return; } duckdb::Vector vec(v.type()); @@ -939,7 +939,7 @@ DUCKDB_V2_ERROR duckdb_v2_value_get_variant_content(duckdb_v2_value_handle value duckdb::RecursiveUnifiedVectorFormat format; duckdb::Vector::RecursiveToUnifiedFormat(vec, format); duckdb::UnifiedVariantVectorData data(format); - *out_content = Emit(duckdb::VariantUtils::ConvertVariantToValue(data, 0, 0)); + *out_value = Emit(duckdb::VariantUtils::ConvertVariantToValue(data, 0, 0)); }); } diff --git a/src/duckdb/tools/cpp/duckdb_cpp.cpp b/src/duckdb/tools/cpp/duckdb_cpp.cpp index b00585d9b..1a64bd5da 100644 --- a/src/duckdb/tools/cpp/duckdb_cpp.cpp +++ b/src/duckdb/tools/cpp/duckdb_cpp.cpp @@ -1832,9 +1832,9 @@ auto Value::GetChild(idx_t index) const -> Value { return detail::HandleFactory::Make(child); } -auto Value::GetVariantContent() const -> Value { +auto Value::VariantToValue() const -> Value { duckdb_v2_value_handle unpacked = nullptr; - CheckedAPICall(duckdb_v2_value_get_variant_content, handle(), &unpacked); + CheckedAPICall(duckdb_v2_value_variant_to_value, handle(), &unpacked); return detail::HandleFactory::Make(unpacked); } diff --git a/src/duckdb/tools/cpp/duckdb_cpp.hpp b/src/duckdb/tools/cpp/duckdb_cpp.hpp index 1aa2c2691..e32a72975 100644 --- a/src/duckdb/tools/cpp/duckdb_cpp.hpp +++ b/src/duckdb/tools/cpp/duckdb_cpp.hpp @@ -2231,7 +2231,7 @@ class Value final : public detail::Handle { /// The value that a VARIANT value holds, with the type that it was stored with: a TINYINT, a VARCHAR, a LIST of /// STRUCTs, ... A nested value is unpacked all the way down. A NULL VARIANT gives a NULL value. /// @throws InvalidInputException When the value is not a VARIANT. - auto GetVariantContent() const -> Value; + auto VariantToValue() const -> Value; /// Shorthand for `GetChild`. auto operator[](idx_t index) const -> Value { diff --git a/src/jni/duckdb_java.cpp b/src/jni/duckdb_java.cpp index 6759c824e..7d9d412fc 100644 --- a/src/jni/duckdb_java.cpp +++ b/src/jni/duckdb_java.cpp @@ -957,7 +957,7 @@ static jobject process_vector_with_type(JNIEnv *env, cxx::Factory &factory, cxx: case LogicalTypeId::VARIANT: { varlen_data = env->NewObjectArray(row_count, J_Object, nullptr); for (idx_t row_idx = 0; row_idx < row_count; row_idx++) { - auto variant_val = vec.GetValue(row_idx).GetVariantContent(); + auto variant_val = vec.GetValue(row_idx).VariantToValue(); if (variant_val.IsNull()) { continue; } From 10e7fa3f89941f5b7ecdebafe2b39b62de01f82c Mon Sep 17 00:00:00 2001 From: Robinho-MR Date: Thu, 26 Nov 2026 13:30:38 +0000 Subject: [PATCH 5/8] Update vendored DuckDB sources to ca7a503a52 --- CMakeLists.txt | 3 +- .../aggregate/algebraic/avg.cpp | 2 +- .../aggregate/distributive/arg_min_max.cpp | 12 + .../aggregate/nested/binned_histogram.cpp | 18 +- .../core_functions/scalar/blob/encode.cpp | 9 + .../core_functions/scalar/list/range.cpp | 31 +- .../core_functions/scalar/math/numeric.cpp | 8 +- .../icu/collation/collation_collator.cpp | 4 +- src/duckdb/extension/icu/icu-list-range.cpp | 23 +- .../extension/parquet/column_reader.cpp | 10 +- .../extension/parquet/column_writer.cpp | 15 +- .../parquet/include/column_reader.hpp | 1 + .../parquet/include/parquet_decimal_utils.hpp | 6 +- .../parquet/include/parquet_page_index.hpp | 7 +- .../parquet/include/parquet_reader.hpp | 5 +- .../writer/parquet_write_operators.hpp | 67 +- .../include/writer/parquet_write_stats.hpp | 78 + .../writer/templated_column_writer.hpp | 5 +- .../extension/parquet/parquet_extension.cpp | 8 +- .../extension/parquet/parquet_page_index.cpp | 4 +- .../extension/parquet/parquet_reader.cpp | 34 +- .../extension/parquet/parquet_statistics.cpp | 17 +- .../extension/parquet/parquet_writer.cpp | 33 +- .../parquet/reader/decimal_column_reader.cpp | 38 +- .../variant/parquet_variant_shredding.cpp | 2 +- .../writer/primitive_column_writer.cpp | 55 +- ...nerated_extension_loader_package_build.cpp | 8 +- src/duckdb/src/common/enum_util.cpp | 110 +- .../common/enums/logical_operator_type.cpp | 2 + .../src/common/enums/optimizer_type.cpp | 1 + .../common/enums/physical_operator_type.cpp | 2 + src/duckdb/src/common/file_system.cpp | 37 - .../src/common/multi_file/multi_file_list.cpp | 81 - .../common/multi_file/multi_file_reader.cpp | 28 +- .../table_function_multi_file_list.cpp | 194 + src/duckdb/src/common/open_file_info.cpp | 2 +- src/duckdb/src/common/opener_file_system.cpp | 25 +- src/duckdb/src/common/process_util.cpp | 2 +- .../src/common/row_operations/row_matcher.cpp | 13 +- src/duckdb/src/common/sort/topn_heap.cpp | 223 +- .../types/column/column_data_collection.cpp | 148 +- .../column/column_data_collection_segment.cpp | 55 +- src/duckdb/src/common/types/time.cpp | 13 + .../variant/parquet_variant_encoding.cpp | 31 +- .../variant/parquet_variant_iterator.cpp | 19 +- .../src/common/types/variant/variant.cpp | 215 + .../types/variant/variant_comparison.cpp | 129 +- .../common/types/variant/variant_iterator.cpp | 98 +- .../comparison_operators.cpp | 4 +- .../vector_operations/string_comparison.cpp | 97 + src/duckdb/src/common/virtual_file_system.cpp | 172 +- .../execute_comparison.cpp | 5 +- src/duckdb/src/execution/index/art/art.cpp | 108 +- src/duckdb/src/execution/join_hashtable.cpp | 275 +- .../operator/aggregate/physical_window.cpp | 188 +- .../csv_scanner/encode/csv_encoder.cpp | 22 +- .../scanner/string_value_scanner.cpp | 8 + .../filter/physical_top_key_filter.cpp | 295 + .../helper/physical_update_extensions.cpp | 33 +- .../operator/persistent/physical_insert.cpp | 4 +- .../operator/persistent/physical_update.cpp | 8 + .../scan/physical_expression_scan.cpp | 16 +- .../operator/scan/physical_table_scan.cpp | 10 +- .../operator/schema/physical_create_index.cpp | 4 +- .../physical_plan/plan_aggregate.cpp | 3 +- .../physical_plan/plan_expression_get.cpp | 12 +- .../execution/physical_plan/plan_limit.cpp | 7 +- .../physical_plan/plan_top_key_filter.cpp | 16 + .../src/execution/physical_plan_generator.cpp | 2 + src/duckdb/src/function/builtin_encodings.cpp | 55 +- .../function/cast/nested_to_varchar_cast.cpp | 2 +- .../function/cast/variant/from_variant.cpp | 2 +- .../src/function/cast/variant/to_json.cpp | 4 +- src/duckdb/src/function/function_list.cpp | 1 + .../system/extension_repository_url.cpp | 68 + .../scalar/variant/variant_array_length.cpp | 2 +- .../scalar/variant/variant_comparator.cpp | 7 +- .../scalar/variant/variant_contains.cpp | 58 +- .../scalar/variant/variant_extract_string.cpp | 4 +- .../function/scalar/variant/variant_keys.cpp | 2 +- .../scalar/variant/variant_normalize.cpp | 4 +- .../scalar/variant/variant_path_function.cpp | 11 +- .../function/scalar/variant/variant_type.cpp | 3 +- .../function/scalar/variant/variant_value.cpp | 6 +- src/duckdb/src/function/table/glob.cpp | 251 +- src/duckdb/src/function/table/read_duckdb.cpp | 158 +- src/duckdb/src/function/table/table_scan.cpp | 42 +- .../function/table/version/pragma_version.cpp | 6 +- .../function/variant/variant_shredding.cpp | 2 +- .../function/window/window_value_function.cpp | 2 + .../src/include/duckdb/common/buffer_ptr.hpp | 8 + .../src/include/duckdb/common/enum_util.hpp | 32 + .../common/enums/logical_operator_type.hpp | 1 + .../duckdb/common/enums/optimizer_type.hpp | 3 +- .../common/enums/physical_operator_type.hpp | 1 + .../common/exception/http_exception.hpp | 10 +- .../include/duckdb/common/file_open_flags.hpp | 2 +- .../src/include/duckdb/common/file_system.hpp | 21 - .../common/multi_file/multi_file_function.hpp | 4 +- .../common/multi_file/multi_file_list.hpp | 28 - .../table_function_multi_file_list.hpp | 58 + .../include/duckdb/common/open_file_info.hpp | 2 +- .../duckdb/common/opener_file_system.hpp | 121 +- .../common/operator/comparison_operators.hpp | 32 + .../include/duckdb/common/shared_ptr_ipp.hpp | 3 + .../duckdb/common/sorting/topn_heap.hpp | 74 +- .../column/column_data_collection_segment.hpp | 19 +- .../duckdb/common/types/selection_vector.hpp | 5 + .../duckdb/common/types/string_type.hpp | 56 +- .../include/duckdb/common/types/variant.hpp | 13 + .../variant/parquet_variant_iterator.hpp | 12 +- .../common/types/variant/variant_builder.hpp | 16 +- .../common/types/variant_comparison.hpp | 12 +- .../duckdb/common/types/variant_iterator.hpp | 16 +- .../duckdb/common/types/variant_visitor.hpp | 113 +- .../duckdb/common/unordered_multimap.hpp | 15 + .../vector_operations/string_comparison.hpp | 93 + .../duckdb/common/virtual_file_system.hpp | 130 +- .../duckdb/execution/index/art/art.hpp | 1 + .../duckdb/execution/join_hashtable.hpp | 11 + .../csv_scanner/encode/csv_encoder.hpp | 7 +- .../filter/physical_top_key_filter.hpp | 72 + .../helper/physical_update_extensions.hpp | 9 +- .../operator/persistent/physical_update.hpp | 3 + .../scan/physical_expression_scan.hpp | 6 +- .../execution/perfect_hash_join_table.hpp | 2 +- .../execution/physical_plan_generator.hpp | 1 + .../duckdb/execution/radix_ht_adaptivity.hpp | 8 +- .../duckdb/execution/reservoir_sample.hpp | 3 + .../duckdb/function/arg_properties.hpp | 8 + .../cast/variant/variant_to_variant.hpp | 8 +- .../function/scalar/system_functions.hpp | 10 + .../function/scalar/variant_path_function.hpp | 2 +- .../function/variant/variant_normalize.hpp | 2 +- .../function/variant/variant_shredding.hpp | 2 +- .../variant/variant_value_convert.hpp | 4 +- .../duckdb/function/window_function.hpp | 4 + .../duckdb/main/capi_v2/capi_v2_internal.hpp | 5 + .../duckdb/main/capi_v2/extension_api_v2.hpp | 7 +- .../src/include/duckdb/main/client_data.hpp | 6 + src/duckdb/src/include/duckdb/main/config.hpp | 7 +- .../duckdb/main/database_file_opener.hpp | 18 +- .../include/duckdb/main/extension_helper.hpp | 26 + .../main/extension_repository_manager.hpp | 12 +- .../include/duckdb/main/http/http_util.hpp | 18 +- .../src/include/duckdb/main/settings.hpp | 2 +- .../duckdb/optimizer/expression_rewriter.hpp | 7 +- .../duckdb/optimizer/group_by_top_key.hpp | 77 + .../join_order/cardinality_value.hpp | 8 + .../optimizer/join_order/cost_model.hpp | 2 + .../join_order/greedy_join_enumerator.hpp | 21 + .../join_order/join_order_candidate.hpp | 14 +- .../join_order/join_order_linearizer.hpp | 50 + .../join_order/join_order_operator.hpp | 4 +- .../optimizer/join_order/join_order_plan.hpp | 34 + .../join_order/join_order_precedence.hpp | 103 + .../optimizer/join_order/join_order_rank.hpp | 36 + .../join_order/join_order_source_stats.hpp | 2 +- .../join_order/join_relation_set.hpp | 19 +- .../join_order/linearized_plan_enumerator.hpp | 46 + .../optimizer/join_order/plan_enumerator.hpp | 1 + .../optimizer/join_order/query_graph.hpp | 3 + .../join_order/query_graph_manager.hpp | 6 +- .../optimizer/join_order/relation_manager.hpp | 2 + .../duckdb/optimizer/mark_join_simplifier.hpp | 5 +- .../duckdb/optimizer/projection_pullup.hpp | 19 +- .../duckdb/optimizer/regex_range_filter.hpp | 5 +- .../duckdb/optimizer/row_number_rewriter.hpp | 4 +- .../optimizer/rule/monotone_preimage.hpp | 7 +- .../optimizer/scalar_aggregate_merger.hpp | 10 +- .../duckdb/optimizer/topn_optimizer.hpp | 10 + .../optimizer/topn_window_elimination.hpp | 2 + .../include/duckdb/parallel/async_result.hpp | 8 + .../parallel/pipeline_broadcast_exchange.hpp | 3 + .../expression/bound_aggregate_expression.hpp | 2 + .../include/duckdb/planner/logical_tokens.hpp | 1 + .../include/duckdb/planner/operator/list.hpp | 1 + .../duckdb/planner/operator/logical_limit.hpp | 3 + .../operator/logical_top_key_filter.hpp | 63 + .../caching_file_system_wrapper.hpp | 10 - .../duckdb/storage/table/append_state.hpp | 3 +- .../duckdb/storage/table/scan_state.hpp | 2 + .../duckdb/transaction/local_storage.hpp | 42 +- src/duckdb/src/include/duckdb_extension_v2.h | 9 +- src/duckdb/src/include/duckdb_v2.h | 60 +- src/duckdb/src/logging/log_manager.cpp | 3 +- src/duckdb/src/logging/log_types.cpp | 5 + .../src/main/capi/v2/capi_v2_logical_type.cpp | 42 +- src/duckdb/src/main/capi/v2/capi_v2_value.cpp | 58 +- src/duckdb/src/main/client_data.cpp | 1 + src/duckdb/src/main/client_verify.cpp | 24 +- src/duckdb/src/main/config.cpp | 5 +- src/duckdb/src/main/context.cpp | 7 +- src/duckdb/src/main/database.cpp | 26 +- src/duckdb/src/main/db_instance_cache.cpp | 4 +- .../src/main/extension/extension_helper.cpp | 118 +- .../extension/extension_install_dynamic.cpp | 2 +- .../extension_repository_manager.cpp | 61 +- .../src/main/http/http_client_httplib.cpp | 10 +- src/duckdb/src/main/http/http_util.cpp | 51 +- src/duckdb/src/main/secret/secret_storage.cpp | 2 +- .../src/main/settings/custom_settings.cpp | 20 +- .../apply_functional_dependencies.cpp | 6 + .../duplicate_eliminated_domain_optimizer.cpp | 2 +- .../src/optimizer/expression_rewriter.cpp | 113 +- src/duckdb/src/optimizer/group_by_top_key.cpp | 532 + .../join_order/cardinality_estimator.cpp | 77 +- .../src/optimizer/join_order/cost_model.cpp | 4 + .../join_order/greedy_join_enumerator.cpp | 243 +- .../join_order/join_order_candidate.cpp | 72 +- .../join_order/join_order_linearizer.cpp | 207 + .../join_order/join_order_operator.cpp | 8 +- .../optimizer/join_order/join_order_plan.cpp | 80 + .../join_order/join_order_precedence.cpp | 572 + .../optimizer/join_order/join_order_rank.cpp | 56 + .../join_order/join_relation_set.cpp | 49 +- .../join_order/linearized_plan_enumerator.cpp | 175 + .../optimizer/join_order/plan_enumerator.cpp | 12 +- .../src/optimizer/join_order/query_graph.cpp | 18 + .../join_order/query_graph_manager.cpp | 83 +- .../optimizer/join_order/relation_manager.cpp | 80 +- .../src/optimizer/join_simplification.cpp | 16 +- .../src/optimizer/late_materialization.cpp | 6 +- .../src/optimizer/mark_join_simplifier.cpp | 163 +- src/duckdb/src/optimizer/optimizer.cpp | 21 +- .../src/optimizer/projection_placement.cpp | 631 +- .../src/optimizer/projection_pullup.cpp | 70 +- .../src/optimizer/regex_range_filter.cpp | 20 +- .../src/optimizer/row_number_rewriter.cpp | 40 +- .../src/optimizer/rule/monotone_preimage.cpp | 83 +- .../src/optimizer/scalar_aggregate_merger.cpp | 457 +- src/duckdb/src/optimizer/topn_optimizer.cpp | 84 +- .../src/optimizer/topn_window_elimination.cpp | 30 + src/duckdb/src/optimizer/window_fusion.cpp | 4 +- src/duckdb/src/parallel/async_result.cpp | 18 + .../parallel/pipeline_broadcast_exchange.cpp | 39 +- .../parser/expression/value_expression.cpp | 4 +- .../src/parser/parsed_expression_iterator.cpp | 29 +- .../transformer/peg_transformer_factory.cpp | 1 + .../transform_generated_trampoline.cpp | 16554 ++++++++-------- .../expression/bind_star_expression.cpp | 32 + .../binder/query_node/bind_select_node.cpp | 3 +- .../statement/bind_update_extensions.cpp | 2 + .../binder/tableref/bind_basetableref.cpp | 2 +- .../logical_operator_repeatability.cpp | 1 + .../src/planner/logical_operator_visitor.cpp | 7 + .../src/planner/operator/logical_limit.cpp | 10 + .../operator/logical_top_key_filter.cpp | 27 + .../planner/sql_export/sql_export_window.cpp | 12 +- src/duckdb/src/planner/table_filter_state.cpp | 43 +- .../compression/validity_uncompressed.cpp | 188 +- src/duckdb/src/storage/data_table.cpp | 8 +- .../caching_file_system_wrapper.cpp | 36 - src/duckdb/src/storage/local_storage.cpp | 147 +- .../serialize_logical_operator.cpp | 16 + .../table/column_data_checkpointer.cpp | 6 +- .../src/storage/table/row_group_reorderer.cpp | 2 + .../table/variant/variant_shredding.cpp | 83 +- .../src/storage/table/variant_column_data.cpp | 6 +- src/duckdb/ub_src_common_multi_file.cpp | 2 + .../ub_src_execution_operator_filter.cpp | 4 + src/duckdb/ub_src_execution_physical_plan.cpp | 2 + src/duckdb/ub_src_function_scalar_system.cpp | 2 + src/duckdb/ub_src_optimizer.cpp | 2 + src/duckdb/ub_src_optimizer_join_order.cpp | 10 + src/duckdb/ub_src_planner_operator.cpp | 2 + src/jni/bindings_value.cpp | 4 +- 267 files changed, 16714 insertions(+), 10821 deletions(-) create mode 100644 src/duckdb/src/common/multi_file/table_function_multi_file_list.cpp create mode 100644 src/duckdb/src/common/vector_operations/string_comparison.cpp create mode 100644 src/duckdb/src/execution/operator/filter/physical_top_key_filter.cpp create mode 100644 src/duckdb/src/execution/physical_plan/plan_top_key_filter.cpp create mode 100644 src/duckdb/src/function/scalar/system/extension_repository_url.cpp create mode 100644 src/duckdb/src/include/duckdb/common/multi_file/table_function_multi_file_list.hpp create mode 100644 src/duckdb/src/include/duckdb/common/unordered_multimap.hpp create mode 100644 src/duckdb/src/include/duckdb/common/vector_operations/string_comparison.hpp create mode 100644 src/duckdb/src/include/duckdb/execution/operator/filter/physical_top_key_filter.hpp create mode 100644 src/duckdb/src/include/duckdb/optimizer/group_by_top_key.hpp create mode 100644 src/duckdb/src/include/duckdb/optimizer/join_order/join_order_linearizer.hpp create mode 100644 src/duckdb/src/include/duckdb/optimizer/join_order/join_order_plan.hpp create mode 100644 src/duckdb/src/include/duckdb/optimizer/join_order/join_order_precedence.hpp create mode 100644 src/duckdb/src/include/duckdb/optimizer/join_order/join_order_rank.hpp create mode 100644 src/duckdb/src/include/duckdb/optimizer/join_order/linearized_plan_enumerator.hpp create mode 100644 src/duckdb/src/include/duckdb/planner/operator/logical_top_key_filter.hpp create mode 100644 src/duckdb/src/optimizer/group_by_top_key.cpp create mode 100644 src/duckdb/src/optimizer/join_order/join_order_linearizer.cpp create mode 100644 src/duckdb/src/optimizer/join_order/join_order_plan.cpp create mode 100644 src/duckdb/src/optimizer/join_order/join_order_precedence.cpp create mode 100644 src/duckdb/src/optimizer/join_order/join_order_rank.cpp create mode 100644 src/duckdb/src/optimizer/join_order/linearized_plan_enumerator.cpp create mode 100644 src/duckdb/src/planner/operator/logical_top_key_filter.cpp create mode 100644 src/duckdb/ub_src_execution_operator_filter.cpp diff --git a/CMakeLists.txt b/CMakeLists.txt index 25e834785..9d3747f0e 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -180,12 +180,12 @@ set(DUCKDB_SRC_FILES src/duckdb/src/common/vector_operations/null_operations.cpp src/duckdb/src/common/vector_operations/numeric_inplace_operators.cpp src/duckdb/src/common/vector_operations/scalar_executor.cpp + src/duckdb/src/common/vector_operations/string_comparison.cpp src/duckdb/src/common/vector_operations/vector_cast.cpp src/duckdb/src/common/vector_operations/vector_copy.cpp src/duckdb/src/common/vector_operations/vector_hash.cpp src/duckdb/src/common/vector_operations/vector_storage.cpp src/duckdb/src/execution/operator/csv_scanner/encode/csv_encoder.cpp - src/duckdb/src/execution/operator/filter/physical_filter.cpp src/duckdb/src/function/aggregate/sorted_aggregate_function.cpp src/duckdb/src/function/cast/union/from_struct.cpp src/duckdb/src/function/scalar/date/strftime.cpp @@ -420,6 +420,7 @@ set(DUCKDB_SRC_FILES src/duckdb/ub_src_execution_operator_csv_scanner_state_machine.cpp src/duckdb/ub_src_execution_operator_csv_scanner_table_function.cpp src/duckdb/ub_src_execution_operator_csv_scanner_util.cpp + src/duckdb/ub_src_execution_operator_filter.cpp src/duckdb/ub_src_execution_operator_helper.cpp src/duckdb/ub_src_execution_operator_join.cpp src/duckdb/ub_src_execution_operator_order.cpp diff --git a/src/duckdb/extension/core_functions/aggregate/algebraic/avg.cpp b/src/duckdb/extension/core_functions/aggregate/algebraic/avg.cpp index 5989e6dc7..8faceae82 100644 --- a/src/duckdb/extension/core_functions/aggregate/algebraic/avg.cpp +++ b/src/duckdb/extension/core_functions/aggregate/algebraic/avg.cpp @@ -522,7 +522,7 @@ static long double BignumSumToLongDouble(const BignumIntermediate &value) { magnitude = (magnitude << 8) | uhugeint_t(value.GetAbsoluteByte(NumericCast(i))); } if (magnitude <= uhugeint_t(NumericLimits::Maximum())) { - auto sum = hugeint_t(magnitude.upper, magnitude.lower); + auto sum = hugeint_t(static_cast(magnitude.upper), magnitude.lower); return Hugeint::Cast(value.is_negative ? -sum : sum); } } diff --git a/src/duckdb/extension/core_functions/aggregate/distributive/arg_min_max.cpp b/src/duckdb/extension/core_functions/aggregate/distributive/arg_min_max.cpp index 3408a2f6b..420a9d2ae 100644 --- a/src/duckdb/extension/core_functions/aggregate/distributive/arg_min_max.cpp +++ b/src/duckdb/extension/core_functions/aggregate/distributive/arg_min_max.cpp @@ -412,6 +412,8 @@ AggregateFunction GetGenericArgMinMaxFunction(const ArgMinMaxNullHandling null_h function.SetStatisticsCallback(AggregateFunction::PropagateInputValueStats); function.GetProperties().SetProperty(BoundAggregateExpression::NON_NULL_SELECTOR_DOMAIN_PROPERTY, Value::BOOLEAN(true)); + function.GetProperties().SetProperty(BoundAggregateExpression::ARG_STORED_AS_SORT_KEY_PROPERTY, + Value::BOOLEAN(true)); return function; } @@ -430,6 +432,8 @@ AggregateFunction GetVectorArgMinMaxFunctionInternal(const LogicalType &by_type, function.SetStatisticsCallback(AggregateFunction::PropagateInputValueStats); function.GetProperties().SetProperty(BoundAggregateExpression::NON_NULL_SELECTOR_DOMAIN_PROPERTY, Value::BOOLEAN(true)); + function.GetProperties().SetProperty(BoundAggregateExpression::ARG_STORED_AS_SORT_KEY_PROPERTY, + Value::BOOLEAN(true)); return function; #else auto function = GetGenericArgMinMaxFunction(null_handling); @@ -754,11 +758,18 @@ void ArgMinMaxNUpdate(Vector inputs[], AggregateInputData &aggr_input, idx_t inp //------------------------------------------------------------------------------ // Bind //------------------------------------------------------------------------------ +template +void SetArgStorageProperty(BoundAggregateFunction &function) { + function.GetProperties().SetProperty(BoundAggregateExpression::ARG_STORED_AS_SORT_KEY_PROPERTY, + Value::BOOLEAN(std::is_same::value)); +} + template void SpecializeArgMinMaxNFunction(BoundAggregateFunction &function) { using STATE = ArgMinMaxNState; using OP = MinMaxNOperation; + SetArgStorageProperty(function); function.SetStateSizeCallback(AggregateFunction::StateSize); function.SetStateInitCallback(AggregateFunction::StateInitialize); function.SetStateCombineCallback(AggregateFunction::StateCombine); @@ -825,6 +836,7 @@ void SpecializeArgMinMaxNullNFunction(BoundAggregateFunction &function) { using STATE = ArgMinMaxNState; using OP = MinMaxNOperation; + SetArgStorageProperty(function); function.SetStateSizeCallback(AggregateFunction::StateSize); function.SetStateInitCallback(AggregateFunction::StateInitialize); function.SetStateCombineCallback(AggregateFunction::StateCombine); diff --git a/src/duckdb/extension/core_functions/aggregate/nested/binned_histogram.cpp b/src/duckdb/extension/core_functions/aggregate/nested/binned_histogram.cpp index 65c71ce06..e152fa4f3 100644 --- a/src/duckdb/extension/core_functions/aggregate/nested/binned_histogram.cpp +++ b/src/duckdb/extension/core_functions/aggregate/nested/binned_histogram.cpp @@ -4,6 +4,7 @@ #include "duckdb/common/algorithm.hpp" #include "duckdb/common/arena_containers/arena_vector.hpp" #include "duckdb/common/smaller_binary.hpp" +#include "duckdb/common/types/sql_value_map.hpp" #include "duckdb/common/types/vector.hpp" #include "duckdb/common/vector/flat_vector.hpp" #include "duckdb/common/vector/list_vector.hpp" @@ -54,7 +55,7 @@ struct HistogramBinState { new_boundaries.push_back(OP::template ExtractValue(bin_child_data, bin_list.offset + i, aggr_input)); } // sort the bin boundaries - std::sort(new_boundaries.begin(), new_boundaries.end()); + std::sort(new_boundaries.begin(), new_boundaries.end(), SQLValueLessThan()); // ensure there are no duplicate bin boundaries for (idx_t i = 1; i < new_boundaries.size(); i++) { if (Equals::Operation(new_boundaries[i - 1], new_boundaries[i])) { @@ -92,7 +93,11 @@ struct HistogramBinFunction { target.counts = &counts; } else { // both source and target have bin boundaries - if (*target.bin_boundaries != *source.bin_boundaries) { + auto &target_bins = *target.bin_boundaries; + auto &source_bins = *source.bin_boundaries; + if (target_bins.size() != source_bins.size() || + !std::equal(target_bins.begin(), target_bins.end(), source_bins.begin(), + SQLValueEquality())) { throw NotImplementedException( "Histogram - cannot combine histograms with different bin boundaries. " "Bin boundaries must be the same for all histograms within the same group"); @@ -113,7 +118,7 @@ struct HistogramRange { template static idx_t GetBin(T value, const unsafe_arena_vector &bin_boundaries) { - auto entry = std::lower_bound(bin_boundaries.begin(), bin_boundaries.end(), value); + auto entry = std::lower_bound(bin_boundaries.begin(), bin_boundaries.end(), value, SQLValueLessThan()); return UnsafeNumericCast(entry - bin_boundaries.begin()); } }; @@ -123,8 +128,8 @@ struct HistogramExact { template static idx_t GetBin(T value, const unsafe_arena_vector &bin_boundaries) { - auto entry = std::lower_bound(bin_boundaries.begin(), bin_boundaries.end(), value); - if (entry == bin_boundaries.end() || !(*entry == value)) { + auto entry = std::lower_bound(bin_boundaries.begin(), bin_boundaries.end(), value, SQLValueLessThan()); + if (entry == bin_boundaries.end() || !SQLValueEquality()(*entry, value)) { // entry not found - return last bucket return bin_boundaries.size(); } @@ -344,6 +349,9 @@ AggregateFunction GetHistogramBinFunction(const LogicalType &type) { AggregateFunction::StateCombine, HistogramBinFinalizeFunction, nullptr, nullptr, nullptr); function.GetSignature().AddParameter("arg", type).AddParameter("bins", LogicalType::LIST(type)); + // a NULL bin list or bin entry throws in the update, different bin boundaries of one group in the combine, and a + // bin that is the key of the "other values" bucket while that bucket has entries in the finalize + function.SetFallible(); return function; } diff --git a/src/duckdb/extension/core_functions/scalar/blob/encode.cpp b/src/duckdb/extension/core_functions/scalar/blob/encode.cpp index 3fdc97c92..e45c17647 100644 --- a/src/duckdb/extension/core_functions/scalar/blob/encode.cpp +++ b/src/duckdb/extension/core_functions/scalar/blob/encode.cpp @@ -3,6 +3,7 @@ #include "duckdb/function/encoding_function.hpp" #include "duckdb/common/string_util.hpp" #include "duckdb/common/exception/conversion_exception.hpp" +#include "duckdb/storage/statistics/base_statistics.hpp" namespace duckdb { @@ -14,6 +15,13 @@ void EncodeFunction(DataChunk &args, ExpressionState &state, Vector &result) { result.Reinterpret(args.data[0]); } +unique_ptr EncodeStats(ClientContext &context, FunctionStatisticsInput &input) { + // the bytes are unchanged, so the input stats carry over to the blob + auto result = BaseStatistics::CreateEmpty(LogicalType::BLOB); + result.Merge(input.child_stats[0]); + return result.ToUnique(); +} + enum class DecodeErrorBehavior : uint8_t { STRICT = 1, // raise an error REPLACE = 2, // replace invalid characters with '?' @@ -118,6 +126,7 @@ ScalarFunctionSet EncodeFun::GetFunctions() { ScalarFunction unary_function({}, LogicalType::BLOB, EncodeFunction); unary_function.GetSignature().AddParameter("string", LogicalType::VARCHAR); + unary_function.SetStatisticsCallback(EncodeStats); // the encoding is bound to the function of the encoding in system.encodings ScalarFunction binary_function({}, LogicalType::BLOB, nullptr); diff --git a/src/duckdb/extension/core_functions/scalar/list/range.cpp b/src/duckdb/extension/core_functions/scalar/list/range.cpp index adbde5e59..455fbc397 100644 --- a/src/duckdb/extension/core_functions/scalar/list/range.cpp +++ b/src/duckdb/extension/core_functions/scalar/list/range.cpp @@ -2,6 +2,8 @@ #include "core_functions/scalar/list_functions.hpp" #include "duckdb/common/types/data_chunk.hpp" #include "duckdb/common/types/vector.hpp" +#include "duckdb/execution/expression_executor_state.hpp" +#include "duckdb/main/context.hpp" namespace duckdb { @@ -18,7 +20,8 @@ struct NumericRangeInfo { return 1; } - static uint64_t ListLength(int64_t start_value, int64_t end_value, int64_t increment_value, bool inclusive_bound) { + static uint64_t ListLength(Context &, int64_t start_value, int64_t end_value, int64_t increment_value, + bool inclusive_bound) { if (increment_value == 0) { return 0; } @@ -58,8 +61,8 @@ struct TimestampRangeInfo { static interval_t DefaultIncrement() { throw InternalException("Default increment not implemented for timestamp range"); } - static uint64_t ListLength(timestamp_t start_value, timestamp_t end_value, interval_t increment_value, - bool inclusive_bound) { + static uint64_t ListLength(Context &context, timestamp_t start_value, timestamp_t end_value, + interval_t increment_value, bool inclusive_bound) { bool is_positive = increment_value.months > 0 || increment_value.days > 0 || increment_value.micros > 0; bool is_negative = increment_value.months < 0 || increment_value.days < 0 || increment_value.micros < 0; if (!is_negative && !is_positive) { @@ -90,6 +93,10 @@ struct TimestampRangeInfo { if (total_values > NumericLimits::Maximum()) { throw InvalidInputException("Lists larger than 2^32 elements are not supported"); } + // counting the elements can take billions of steps + if (total_values % STANDARD_VECTOR_SIZE == 0) { + context.FastInterruptCheck(); + } } } else { // positive interval, start_value is going up @@ -99,6 +106,10 @@ struct TimestampRangeInfo { if (total_values > NumericLimits::Maximum()) { throw InvalidInputException("Lists larger than 2^32 elements are not supported"); } + // counting the elements can take billions of steps + if (total_values % STANDARD_VECTOR_SIZE == 0) { + context.FastInterruptCheck(); + } } } return total_values; @@ -175,12 +186,12 @@ class RangeInfoStruct { increment_value = ListIncrementValue(row_idx); } - uint64_t ListLength(idx_t row_idx) { + uint64_t ListLength(Context &context, idx_t row_idx) { typename OP::TYPE start_value; typename OP::TYPE end_value; typename OP::INCREMENT_TYPE increment_value; GetListValues(row_idx, start_value, end_value, increment_value); - return OP::ListLength(start_value, end_value, increment_value, INCLUSIVE_BOUND); + return OP::ListLength(context, start_value, end_value, increment_value, INCLUSIVE_BOUND); } private: @@ -192,9 +203,11 @@ template void ListRangeFunction(DataChunk &args, ExpressionState &state, Vector &result) { D_ASSERT(result.GetType().id() == LogicalTypeId::LIST); + auto &context = state.GetContext(); RangeInfoStruct info(args); auto args_size = args.size(); auto list_writer = FlatVector::Writer>(result, args_size); + idx_t written_since_check = 0; for (idx_t i = 0; i < args_size; i++) { if (!info.RowIsValid(i)) { list_writer.WriteNull(); @@ -202,7 +215,7 @@ void ListRangeFunction(DataChunk &args, ExpressionState &state, Vector &result) } typename OP::TYPE start_value = info.StartListValue(i); typename OP::INCREMENT_TYPE increment = info.ListIncrementValue(i); - const auto length = info.ListLength(i); + const auto length = info.ListLength(context, i); typename OP::TYPE range_value = start_value; bool seen_value = false; @@ -213,6 +226,12 @@ void ListRangeFunction(DataChunk &args, ExpressionState &state, Vector &result) child_writer.WriteValue(range_value); seen_value = true; } + // writing long lists can take billions of steps + written_since_check += length; + if (written_since_check >= STANDARD_VECTOR_SIZE) { + context.FastInterruptCheck(); + written_since_check = 0; + } } } diff --git a/src/duckdb/extension/core_functions/scalar/math/numeric.cpp b/src/duckdb/extension/core_functions/scalar/math/numeric.cpp index 2866cf271..70c984b35 100644 --- a/src/duckdb/extension/core_functions/scalar/math/numeric.cpp +++ b/src/duckdb/extension/core_functions/scalar/math/numeric.cpp @@ -628,7 +628,7 @@ ScalarFunctionSet CeilFun::GetFunctions() { ceil_function.SetResolveTypesCallback(resolve_func); ceil.AddFunction(NameXArgument(std::move(ceil_function), type)); } - ceil.SetUnaryArgProperties(ArgProperties().NonDecreasing()); + ceil.SetUnaryArgProperties(ArgProperties().NonDecreasing().RoundsToInteger(IntegerRounding::CEIL)); return ceil; } @@ -670,7 +670,7 @@ ScalarFunctionSet FloorFun::GetFunctions() { floor_function.SetResolveTypesCallback(resolve_func); floor.AddFunction(NameXArgument(std::move(floor_function), type)); } - floor.SetUnaryArgProperties(ArgProperties().NonDecreasing()); + floor.SetUnaryArgProperties(ArgProperties().NonDecreasing().RoundsToInteger(IntegerRounding::FLOOR)); return floor; } @@ -961,12 +961,14 @@ ScalarFunctionSet TruncFun::GetFunctions() { } ScalarFunction trunc_function({}, type, trunc_func); trunc_function.SetResolveTypesCallback(resolve_func); + trunc_function.SetUnaryArgProperties( + ArgProperties().NonDecreasing().RoundsToInteger(IntegerRounding::TRUNCATE)); trunc.AddFunction(NameXArgument(std::move(trunc_function), type)); ScalarFunction trunc_prec_function({}, type, trunc_prec_func, bind_prec_func); trunc_prec_function.SetResolveTypesCallback(resolve_prec_func); + trunc_prec_function.SetUnaryArgProperties(ArgProperties().NonDecreasing()); trunc.AddFunction(NameXPrecisionArguments(std::move(trunc_prec_function), type)); } - trunc.SetUnaryArgProperties(ArgProperties().NonDecreasing()); return trunc; } diff --git a/src/duckdb/extension/icu/collation/collation_collator.cpp b/src/duckdb/extension/icu/collation/collation_collator.cpp index 08173a1ef..4015a26ca 100644 --- a/src/duckdb/extension/icu/collation/collation_collator.cpp +++ b/src/duckdb/extension/icu/collation/collation_collator.cpp @@ -915,7 +915,7 @@ Collator Collator::FromLanguageTag(const string &tag) { // the "u" extension holds attributes, then keywords: a two character key followed by the subtags of its value idx_t pos = locale_end; while (pos < subtags.size()) { - auto singleton = subtags[pos++]; + const auto &singleton = subtags[pos++]; if (singleton == "x") { // the rest of the tag is for private use break; @@ -931,7 +931,7 @@ Collator Collator::FromLanguageTag(const string &tag) { // when a key is repeated, its first value counts vector keys; while (pos < end) { - auto key = subtags[pos++]; + const auto &key = subtags[pos++]; string value; while (pos < end && subtags[pos].size() != 2) { value += (value.empty() ? "" : "-") + subtags[pos++]; diff --git a/src/duckdb/extension/icu/icu-list-range.cpp b/src/duckdb/extension/icu/icu-list-range.cpp index eb7c01a27..197e3bf26 100644 --- a/src/duckdb/extension/icu/icu-list-range.cpp +++ b/src/duckdb/extension/icu/icu-list-range.cpp @@ -4,6 +4,7 @@ #include "duckdb/common/types/vector.hpp" #include "duckdb/function/function_set.hpp" #include "duckdb/function/scalar_function.hpp" +#include "duckdb/main/context.hpp" #include "include/icu-datefunc.hpp" #include "duckdb/planner/expression/bound_function_expression.hpp" #include "duckdb/main/extension/extension_loader.hpp" @@ -55,12 +56,12 @@ struct ICUListRange : public ICUDateFunc { increment_value = ListIncrementValue(row_idx); } - uint64_t ListLength(idx_t row_idx, TZCalendar &calendar) { + uint64_t ListLength(Context &context, idx_t row_idx, TZCalendar &calendar) { timestamp_tz_t start_value; timestamp_tz_t end_value; interval_t increment_value; GetListValues(row_idx, start_value, end_value, increment_value); - return ListLength(start_value, end_value, increment_value, INCLUSIVE_BOUND, calendar); + return ListLength(context, start_value, end_value, increment_value, INCLUSIVE_BOUND, calendar); } void Increment(timestamp_tz_t &input, interval_t increment, TZCalendar &calendar) { @@ -73,8 +74,8 @@ struct ICUListRange : public ICUDateFunc { VectorIterator end_value_data; VectorIterator increment_value_data; - uint64_t ListLength(timestamp_tz_t start_value, timestamp_tz_t end_value, interval_t increment_value, - bool inclusive_bound, TZCalendar &calendar) { + uint64_t ListLength(Context &context, timestamp_tz_t start_value, timestamp_tz_t end_value, + interval_t increment_value, bool inclusive_bound, TZCalendar &calendar) { bool is_positive = increment_value.months > 0 || increment_value.days > 0 || increment_value.micros > 0; bool is_negative = increment_value.months < 0 || increment_value.days < 0 || increment_value.micros < 0; if (!is_negative && !is_positive) { @@ -105,6 +106,10 @@ struct ICUListRange : public ICUDateFunc { if (total_values > NumericLimits::Maximum()) { throw InvalidInputException("Lists larger than 2^32 elements are not supported"); } + // counting the elements can take billions of steps + if (UnsafeNumericCast(total_values) % STANDARD_VECTOR_SIZE == 0) { + context.FastInterruptCheck(); + } } } else { // positive interval, start_value is going up @@ -114,6 +119,10 @@ struct ICUListRange : public ICUDateFunc { if (total_values > NumericLimits::Maximum()) { throw InvalidInputException("Lists larger than 2^32 elements are not supported"); } + // counting the elements can take billions of steps + if (UnsafeNumericCast(total_values) % STANDARD_VECTOR_SIZE == 0) { + context.FastInterruptCheck(); + } } } return total_values; @@ -129,6 +138,7 @@ struct ICUListRange : public ICUDateFunc { auto &bind_info = func_expr.BindInfo()->Cast(); TZCalendar calendar(*bind_info.calendar, bind_info.cal_setting); + auto &context = state.GetContext(); RangeInfoStruct info(args); idx_t args_size = args.size(); auto list_writer = FlatVector::Writer>(result, args_size); @@ -137,7 +147,7 @@ struct ICUListRange : public ICUDateFunc { list_writer.WriteNull(); continue; } - const auto length = info.ListLength(i, calendar); + const auto length = info.ListLength(context, i, calendar); auto list = list_writer.WriteDynamicList(); timestamp_tz_t range_value = info.StartListValue(i); @@ -147,6 +157,9 @@ struct ICUListRange : public ICUDateFunc { info.Increment(range_value, increment, calendar); } list.WriteElement().WriteValue(range_value); + if ((range_idx + 1) % STANDARD_VECTOR_SIZE == 0) { + context.FastInterruptCheck(); + } } } result.Verify(); diff --git a/src/duckdb/extension/parquet/column_reader.cpp b/src/duckdb/extension/parquet/column_reader.cpp index 20242dabc..4dc362267 100644 --- a/src/duckdb/extension/parquet/column_reader.cpp +++ b/src/duckdb/extension/parquet/column_reader.cpp @@ -418,6 +418,7 @@ void ColumnReader::InitializeRead(idx_t row_group_idx_p, idx_t row_group_num_row const duckdb_parquet::ColumnChunkList &columns, TProtocol &protocol_p) { D_ASSERT(ColumnIndex() < columns.size()); chunk = &columns[ColumnIndex()]; + page_ordinal = 0; protocol = &protocol_p; D_ASSERT(chunk); if (chunk->__isset.crypto_metadata && !reader.metadata->crypto_metadata) { @@ -504,9 +505,9 @@ bool ColumnReader::PageIsFilteredOut(PageHeader &page_hdr, optional_ptr filter, optional_ptr filter_state, idx_t rows_to_skip) { - int8_t page_ordinal = 0; while (page_rows_available == 0) { - aad_crypto_metadata.page_ordinal = page_ordinal; PrepareRead(filter, filter_state, rows_to_skip); page_ordinal++; } @@ -1372,9 +1371,6 @@ unique_ptr ColumnReader::CreateReader(const ParquetReader &reader, } return make_uniq>>(reader, schema); case LogicalTypeId::DOUBLE: - if (schema.type_info == ParquetExtraTypeInfo::DECIMAL_BYTE_ARRAY) { - return ParquetDecimalUtils::CreateReader(reader, schema); - } return make_uniq>>(reader, schema); case LogicalTypeId::TIMESTAMP: case LogicalTypeId::TIMESTAMP_TZ: diff --git a/src/duckdb/extension/parquet/column_writer.cpp b/src/duckdb/extension/parquet/column_writer.cpp index 7eef06c22..643e68799 100644 --- a/src/duckdb/extension/parquet/column_writer.cpp +++ b/src/duckdb/extension/parquet/column_writer.cpp @@ -512,11 +512,13 @@ unique_ptr ColumnWriter::CreateWriterRecursive(ClientContext &cont return make_uniq>(writer, std::move(schema), path_in_schema); case LogicalTypeId::HUGEINT: - return make_uniq>(writer, std::move(schema), - path_in_schema); + return make_uniq< + StandardColumnWriter>( + writer, std::move(schema), path_in_schema); case LogicalTypeId::UHUGEINT: - return make_uniq>(writer, std::move(schema), - path_in_schema); + return make_uniq< + StandardColumnWriter>( + writer, std::move(schema), path_in_schema); case LogicalTypeId::TIMESTAMP_NS: case LogicalTypeId::TIMESTAMP_TZ_NS: if (parquet_write_timestamp_as_int96) { @@ -631,6 +633,11 @@ hash_t Hash(ParquetUUIDTargetType val) { return Hash(const_char_ptr_cast(val.bytes), ParquetUUIDTargetType::PARQUET_UUID_SIZE); } +template <> +hash_t Hash(ParquetHugeintDecimalTargetType val) { + return Hash(const_char_ptr_cast(val.bytes), ParquetHugeintDecimalTargetType::PARQUET_SIZE); +} + template <> hash_t Hash(float_na_equal val) { if (std::isnan(val.val)) { diff --git a/src/duckdb/extension/parquet/include/column_reader.hpp b/src/duckdb/extension/parquet/include/column_reader.hpp index b1ef678f9..3df01125f 100644 --- a/src/duckdb/extension/parquet/include/column_reader.hpp +++ b/src/duckdb/extension/parquet/include/column_reader.hpp @@ -432,6 +432,7 @@ class ColumnReader { idx_t page_rows_available; idx_t group_rows_available; idx_t chunk_read_offset; + uint16_t page_ordinal = 0; //! The OffsetIndex of the column chunk and the rows of the row group that may match the filters (both owned by //! the scan state), set only when the page index can be used to skip pages of this column chunk diff --git a/src/duckdb/extension/parquet/include/parquet_decimal_utils.hpp b/src/duckdb/extension/parquet/include/parquet_decimal_utils.hpp index 2ecc01366..f03444437 100644 --- a/src/duckdb/extension/parquet/include/parquet_decimal_utils.hpp +++ b/src/duckdb/extension/parquet/include/parquet_decimal_utils.hpp @@ -56,7 +56,8 @@ class ParquetDecimalUtils { //! Converts a big-endian two's complement Parquet decimal into the BIGNUM blob of a wide decimal static string ReadWideDecimalValue(const_data_ptr_t pointer, idx_t size); - //! The number of bytes a FIXED_LEN_BYTE_ARRAY needs to hold decimals of the given width + //! The number of bytes of the FIXED_LEN_BYTE_ARRAY that decimals of the given width are written in, enough to + //! hold the width, rounded up to a multiple of 8 bytes static idx_t WideDecimalByteLength(uint32_t width); //! Writes the BIGNUM blob of a wide decimal as a big-endian two's complement value of byte_length bytes static void WriteWideDecimal(const bignum_t &value, idx_t byte_length, data_ptr_t result); @@ -65,7 +66,4 @@ class ParquetDecimalUtils { [[noreturn]] static void ThrowInvalidDecimalEncoding(); }; -template <> -double ParquetDecimalUtils::ReadDecimalValue(const_data_ptr_t pointer, idx_t size, const ParquetColumnSchema &schema); - } // namespace duckdb diff --git a/src/duckdb/extension/parquet/include/parquet_page_index.hpp b/src/duckdb/extension/parquet/include/parquet_page_index.hpp index a836f5447..f55f40b79 100644 --- a/src/duckdb/extension/parquet/include/parquet_page_index.hpp +++ b/src/duckdb/extension/parquet/include/parquet_page_index.hpp @@ -25,6 +25,7 @@ class TProtocol; } // namespace duckdb_apache namespace duckdb { +class ClientContext; class TableFilter; struct ParquetColumnSchema; struct ParquetOptions; @@ -74,9 +75,9 @@ struct ParquetPageIndexUtils { static idx_t PageRowCount(const duckdb_parquet::OffsetIndex &offset_index, idx_t page_idx, idx_t row_group_num_rows); //! Evaluates the filter against the bounds of every page: result[page] is false when the page cannot match - static void FilterPages(const ParquetColumnSchema &schema, const duckdb_parquet::ColumnIndex &column_index, - const TableFilter &filter, const ParquetOptions &parquet_options, bool can_have_nan, - vector &result); + static void FilterPages(ClientContext &context, const ParquetColumnSchema &schema, + const duckdb_parquet::ColumnIndex &column_index, const TableFilter &filter, + const ParquetOptions &parquet_options, bool can_have_nan, vector &result); //! The rows of the pages that may match, as sorted non-overlapping ranges static vector PagesToRowRanges(const duckdb_parquet::OffsetIndex &offset_index, const vector &page_may_match, idx_t row_group_num_rows); diff --git a/src/duckdb/extension/parquet/include/parquet_reader.hpp b/src/duckdb/extension/parquet/include/parquet_reader.hpp index 7962ca4b4..a3820e608 100644 --- a/src/duckdb/extension/parquet/include/parquet_reader.hpp +++ b/src/duckdb/extension/parquet/include/parquet_reader.hpp @@ -516,11 +516,10 @@ class ParquetReader : public BaseFileReader { bool TryAttachPageIndexBuffer(ThriftFileTransport &transport) const; struct BloomFilterReadPlan; BloomFilterReadPlan PlanBloomFilterReads(ClientContext &context, ThriftFileTransport &transport, - ColumnReader &column_reader, const TableFilter &filter, bool nested_filter, + ColumnReader &column_reader, const TableFilter &filter, idx_t column_chunk_idx); bool TryAttachBloomFilterReadHead(ClientContext &context, ParquetReaderScanState &state, - ColumnReader &column_reader, const TableFilter &filter, bool nested_filter, - idx_t column_chunk_idx); + ColumnReader &column_reader, const TableFilter &filter, idx_t column_chunk_idx); //! Moves the scan to the next rows of the row group that may match according to the page index, skipping the //! rows in between in every column reader; returns the number of rows to scan next (0 if none are left) idx_t SkipToPageIndexRows(ParquetReaderScanState &state); diff --git a/src/duckdb/extension/parquet/include/writer/parquet_write_operators.hpp b/src/duckdb/extension/parquet/include/writer/parquet_write_operators.hpp index 7197f3524..6af031469 100644 --- a/src/duckdb/extension/parquet/include/writer/parquet_write_operators.hpp +++ b/src/duckdb/extension/parquet/include/writer/parquet_write_operators.hpp @@ -92,6 +92,12 @@ struct BaseParquetOperator { return 1; } + //! Whether bloom filters are written for the columns of this operator + template + static constexpr bool WritesBloomFilter() { + return true; + } + template static optional GetExtraBloomFilterHash(const SRC &, const TGT &) { return nullopt; @@ -413,58 +419,77 @@ struct ParquetUUIDOperator : public BaseParquetOperator { } }; -struct ParquetTimeTZOperator : public BaseParquetOperator { +//! Writes HUGEINT (sign-extended) and UHUGEINT (zero-extended) as the big-endian two's complement bytes of a +//! DECIMAL(39,0), see ParquetHugeintDecimalTargetType for the length +struct ParquetHugeintDecimalOperator : public BaseParquetOperator { template static TGT Operation(SRC input) { - return Time::NormalizeTimeTZ(input).value; + TGT result; + const auto upper = static_cast(input.upper); + const bool negative = std::is_signed::value && (upper >> 63) != 0; + const idx_t offset = ParquetHugeintDecimalTargetType::SIGN_EXTENSION_SIZE; + memset(result.bytes, negative ? 0xFF : 0x00, offset); + for (idx_t i = 0; i < sizeof(uint64_t); i++) { + const auto shift_count = (sizeof(uint64_t) - i - 1) * 8; + result.bytes[offset + i] = (upper >> shift_count) & 0xFF; + result.bytes[offset + sizeof(uint64_t) + i] = (input.lower >> shift_count) & 0xFF; + } + return result; } template - static unique_ptr InitializeStats() { - return make_uniq>(); + static void WriteToStream(const TGT &target_value, WriteStream &ser) { + ser.WriteData(target_value.bytes, ParquetHugeintDecimalTargetType::PARQUET_SIZE); } template - static void HandleStats(ColumnWriterStatistics *stats, TGT target_value) { - auto &numeric_stats = stats->Cast>(); - if (LessThan::Operation(target_value, numeric_stats.min)) { - numeric_stats.min = target_value; - } - if (GreaterThan::Operation(target_value, numeric_stats.max)) { - numeric_stats.max = target_value; - } + static constexpr idx_t WriteSize(const TGT &target_value) { + return ParquetHugeintDecimalTargetType::PARQUET_SIZE; } -}; -struct ParquetHugeintOperator : public BaseParquetOperator { template - static TGT Operation(SRC input) { - return Hugeint::Cast(input); + static uint64_t XXHash64(const TGT &target_value) { + return duckdb_zstd::XXH64(target_value.bytes, ParquetHugeintDecimalTargetType::PARQUET_SIZE, 0); + } + + //! No bloom filters, because DuckDB versions that read this column as a DOUBLE would probe the filter with the hash + //! of a DOUBLE, which is never in it, and skip row groups that hold the value + template + static constexpr bool WritesBloomFilter() { + return false; } template static unique_ptr InitializeStats() { - return make_uniq(); + return make_uniq(); } template - static void HandleStats(ColumnWriterStatistics *stats, TGT target_value) { + static void HandleStats(ColumnWriterStatistics *stats_p, TGT target_value) { + stats_p->Cast().Update(target_value); } }; -struct ParquetUhugeintOperator : public BaseParquetOperator { +struct ParquetTimeTZOperator : public BaseParquetOperator { template static TGT Operation(SRC input) { - return Uhugeint::Cast(input); + return Time::NormalizeTimeTZ(input).value; } template static unique_ptr InitializeStats() { - return make_uniq(); + return make_uniq>(); } template static void HandleStats(ColumnWriterStatistics *stats, TGT target_value) { + auto &numeric_stats = stats->Cast>(); + if (LessThan::Operation(target_value, numeric_stats.min)) { + numeric_stats.min = target_value; + } + if (GreaterThan::Operation(target_value, numeric_stats.max)) { + numeric_stats.max = target_value; + } } }; diff --git a/src/duckdb/extension/parquet/include/writer/parquet_write_stats.hpp b/src/duckdb/extension/parquet/include/writer/parquet_write_stats.hpp index ad474e325..b23f95454 100644 --- a/src/duckdb/extension/parquet/include/writer/parquet_write_stats.hpp +++ b/src/duckdb/extension/parquet/include/writer/parquet_write_stats.hpp @@ -351,6 +351,84 @@ class UUIDStatisticsState : public ColumnWriterStatistics { } }; +//! HUGEINT / UHUGEINT are written as DECIMAL(39,0), the narrowest decimal that holds the full range of both, as a +//! big-endian two's complement FIXED_LEN_BYTE_ARRAY, the same form as a wide decimal of that width +struct ParquetHugeintDecimalTargetType { + //! The decimal width that holds every HUGEINT and UHUGEINT value + static constexpr const uint32_t DECIMAL_WIDTH = 39; + //! The number of sign extension bytes in front of the 16 bytes of the integer + static constexpr const idx_t SIGN_EXTENSION_SIZE = 8; + //! The length of the FIXED_LEN_BYTE_ARRAY. 39 digits need 17 bytes, but the length is deliberately not minimal. + //! DuckDB 1.x reads a decimal of more than 38 digits as a DOUBLE with a decoder that is only correct when the + //! length is a multiple of 8 bytes (it misreads the trailing partial chunk, without an error). The Parquet + //! format only requires the length to be large enough for the precision, so the values are sign-extended to 24 + //! bytes, which those versions read as the (rounded) DOUBLE they got when these types were written as DOUBLE + static constexpr const idx_t PARQUET_SIZE = SIGN_EXTENSION_SIZE + 16; + data_t bytes[PARQUET_SIZE]; + + //! Numeric comparison, where the bytes order like the values once the sign bit is flipped + static int Compare(const ParquetHugeintDecimalTargetType &lhs, const ParquetHugeintDecimalTargetType &rhs) { + const auto lhs_sign = lhs.bytes[0] ^ 0x80; + const auto rhs_sign = rhs.bytes[0] ^ 0x80; + if (lhs_sign != rhs_sign) { + return lhs_sign < rhs_sign ? -1 : 1; + } + return memcmp(lhs.bytes + 1, rhs.bytes + 1, PARQUET_SIZE - 1); + } +}; + +class HugeintDecimalStatisticsState : public ColumnWriterStatistics { +public: + bool has_stats = false; + ParquetHugeintDecimalTargetType min; + ParquetHugeintDecimalTargetType max; + +public: + void Update(const ParquetHugeintDecimalTargetType &value) { + if (!has_stats || ParquetHugeintDecimalTargetType::Compare(value, min) < 0) { + min = value; + } + if (!has_stats || ParquetHugeintDecimalTargetType::Compare(value, max) > 0) { + max = value; + } + has_stats = true; + } + + bool HasStats() override { + return has_stats; + } + + string GetMin() override { + return GetMinValue(); + } + string GetMax() override { + return GetMaxValue(); + } + string GetMinValue() override { + return HasStats() ? string(char_ptr_cast(min.bytes), ParquetHugeintDecimalTargetType::PARQUET_SIZE) : string(); + } + string GetMaxValue() override { + return HasStats() ? string(char_ptr_cast(max.bytes), ParquetHugeintDecimalTargetType::PARQUET_SIZE) : string(); + } + + void Merge(const ColumnWriterStatistics &other_p) override { + auto &other = other_p.Cast(); + if (!other.has_stats) { + return; + } + Update(other.min); + Update(other.max); + } + int CompareMin(const ColumnWriterStatistics &other_p) const override { + auto &other = other_p.Cast(); + return ParquetHugeintDecimalTargetType::Compare(min, other.min); + } + int CompareMax(const ColumnWriterStatistics &other_p) const override { + auto &other = other_p.Cast(); + return ParquetHugeintDecimalTargetType::Compare(max, other.max); + } +}; + class GeoStatisticsState final : public ColumnWriterStatistics { public: explicit GeoStatisticsState(GeometryModel geometry_model) : has_stats(false), geometry_model(geometry_model) { diff --git a/src/duckdb/extension/parquet/include/writer/templated_column_writer.hpp b/src/duckdb/extension/parquet/include/writer/templated_column_writer.hpp index e9845bd81..2dec4683f 100644 --- a/src/duckdb/extension/parquet/include/writer/templated_column_writer.hpp +++ b/src/duckdb/extension/parquet/include/writer/templated_column_writer.hpp @@ -460,7 +460,8 @@ class StandardColumnWriter : public PrimitiveColumnWriter { } bool SupportsBloomFilterFallback() const override { - return !std::is_same::value && !std::is_same::value; + return !std::is_same::value && !std::is_same::value && + OP::template WritesBloomFilter(); } bool HasDictionary(PrimitiveColumnWriterState &state_p) override { @@ -504,7 +505,7 @@ class StandardColumnWriter : public PrimitiveColumnWriter { D_ASSERT(state.encoding == duckdb_parquet::Encoding::RLE_DICTIONARY || state.encoding == duckdb_parquet::Encoding::PLAIN_DICTIONARY); - if (writer.EnableBloomFilters()) { + if (writer.EnableBloomFilters() && OP::template WritesBloomFilter()) { auto bloom_filter_entries = state.dictionary.GetSize() * OP::template BloomFilterEntriesPerValue(); state.bloom_filter = diff --git a/src/duckdb/extension/parquet/parquet_extension.cpp b/src/duckdb/extension/parquet/parquet_extension.cpp index 6be29b46a..96dc6223e 100644 --- a/src/duckdb/extension/parquet/parquet_extension.cpp +++ b/src/duckdb/extension/parquet/parquet_extension.cpp @@ -1031,9 +1031,10 @@ static vector> ParquetWriteSelect(CopyToSelectInput &inpu result.push_back(std::move(cast_expr)); any_change = true; } - // If this is an EXPORT DATABASE statement, we dont want to write "lossy" types, instead cast them to VARCHAR + // If this is an EXPORT DATABASE statement, HUGEINT / UHUGEINT are cast to VARCHAR. A COPY writes them as + // DECIMAL(39,0), which is exact, but DuckDB versions without wide decimals read that back as a lossy DOUBLE else if (input.copy_to_type == CopyToType::EXPORT_DATABASE && TypeVisitor::Contains(type, IsTypeLossy)) { - // Replace all lossy types with VARCHAR + // Replace these types with VARCHAR auto new_type = TypeVisitor::VisitReplace( type, [](const LogicalType &ty) -> LogicalType { return IsTypeLossy(ty) ? LogicalType::VARCHAR : ty; }); @@ -1086,8 +1087,7 @@ static unique_ptr ParquetCopyFromBind(ClientContext &context, Copy static void LoadInternal(ExtensionLoader &loader) { auto &db_instance = loader.GetDatabaseInstance(); - auto &fs = db_instance.GetFileSystem(); - fs.RegisterCompressionFilesystem(make_uniq()); + VirtualFileSystem::Get(db_instance).RegisterCompressionFilesystem(make_uniq()); auto scan_fun = MultiFileReader::CreateFunctionSet(ParquetScanFunction::GetMultiFileFunction("read_parquet")); scan_fun.SetName("read_parquet"); diff --git a/src/duckdb/extension/parquet/parquet_page_index.cpp b/src/duckdb/extension/parquet/parquet_page_index.cpp index 55ff1324e..48e736936 100644 --- a/src/duckdb/extension/parquet/parquet_page_index.cpp +++ b/src/duckdb/extension/parquet/parquet_page_index.cpp @@ -116,7 +116,7 @@ idx_t ParquetPageIndexUtils::PageRowCount(const duckdb_parquet::OffsetIndex &off return end - begin; } -void ParquetPageIndexUtils::FilterPages(const ParquetColumnSchema &schema, +void ParquetPageIndexUtils::FilterPages(ClientContext &context, const ParquetColumnSchema &schema, const duckdb_parquet::ColumnIndex &column_index, const TableFilter &filter, const ParquetOptions &parquet_options, bool can_have_nan, vector &result) { @@ -151,7 +151,7 @@ void ParquetPageIndexUtils::FilterPages(const ParquetColumnSchema &schema, stats->Set(StatsInfo::CANNOT_HAVE_NULL_VALUES); } } - auto prune_result = expr_filter.CheckStatistics(*stats); + auto prune_result = expr_filter.CheckStatistics(context, *stats); if (prune_result == FilterPropagateResult::FILTER_ALWAYS_FALSE || prune_result == FilterPropagateResult::FILTER_FALSE_OR_NULL) { result[page_idx] = false; diff --git a/src/duckdb/extension/parquet/parquet_reader.cpp b/src/duckdb/extension/parquet/parquet_reader.cpp index 893f490b0..67f3f1da0 100644 --- a/src/duckdb/extension/parquet/parquet_reader.cpp +++ b/src/duckdb/extension/parquet/parquet_reader.cpp @@ -587,15 +587,7 @@ LogicalType ParquetReader::DeriveLogicalType(const SchemaElement &s_ele, const P throw IOException("Invalid DECIMAL precision %d and scale %d", s_ele.precision, s_ele.scale); } schema.type_scale = NumericCast(s_ele.scale); - if (s_ele.precision > Decimal::MAX_WIDTH_INT128) { - // precisions above 38 become wide (BIGNUM-backed) decimals, other physical types fall back to DOUBLE - schema.type_info = ParquetExtraTypeInfo::DECIMAL_BYTE_ARRAY; - if (s_ele.type == Type::BYTE_ARRAY || s_ele.type == Type::FIXED_LEN_BYTE_ARRAY) { - return LogicalType::DECIMAL(NumericCast(s_ele.precision), - NumericCast(s_ele.scale)); - } - return LogicalType::DOUBLE; - } + // precisions above 38 become wide (BIGNUM-backed) decimals, whichever physical type holds the values switch (s_ele.type) { case Type::BYTE_ARRAY: case Type::FIXED_LEN_BYTE_ARRAY: @@ -2021,19 +2013,19 @@ void ParquetReader::PrepareRowGroupBuffer(ClientContext &context, ParquetReaderS auto &filter = *filter_entry; auto prune_result = CheckRowGroupFilterStatistics(context, state, column_reader, filter); - // check the bloom filter if present - auto bloom_source = TryGetBloomFilterSource(column_reader); + // check the bloom filter if present and the statistics do not already decide the row group + auto bloom_source = prune_result == FilterPropagateResult::NO_PRUNING_POSSIBLE + ? TryGetBloomFilterSource(column_reader) + : nullptr; if (bloom_source) { optional_ptr bloom_reader = bloom_source; optional_ptr bloom_filter = &filter; unique_ptr leaf_filter; - auto check_bloom_filter = prune_result == FilterPropagateResult::NO_PRUNING_POSSIBLE; if (bloom_source->Type().IsNested()) { if (!TryGetBloomFilterLeaf(*bloom_source, filter, bloom_reader, leaf_filter)) { bloom_reader = nullptr; } else { bloom_filter = leaf_filter.get(); - check_bloom_filter = prune_result != FilterPropagateResult::FILTER_ALWAYS_FALSE; } } if (bloom_reader && parquet_options.RepairsInvalidUTF8() && @@ -2045,14 +2037,14 @@ void ParquetReader::PrepareRowGroupBuffer(ClientContext &context, ParquetReaderS auto hash_strategy = bloom_reader ? ParquetStatisticsUtils::GetBloomFilterHashStrategy( bloom_reader->Schema(), interval_bloom_filter_version) : nullopt; - if (check_bloom_filter && bloom_reader && bloom_filter && + if (bloom_reader && bloom_filter && bloom_reader->Schema().schema_type == ParquetColumnSchemaType::COLUMN && bloom_reader->ColumnIndex() < group.columns.size() && hash_strategy) { auto &bloom_meta_data = group.columns[bloom_reader->ColumnIndex()].meta_data; if (bloom_meta_data.__isset.bloom_filter_offset && bloom_meta_data.bloom_filter_offset > 0 && ParquetStatisticsUtils::HasBloomFilterConstants(*bloom_filter, *hash_strategy)) { TryAttachBloomFilterReadHead(context, state, column_reader, filter, - bloom_source->Type().IsNested(), bloom_reader->ColumnIndex()); + bloom_reader->ColumnIndex()); } if (ParquetStatisticsUtils::BloomFilterExcludes( *bloom_filter, group.columns[bloom_reader->ColumnIndex()].meta_data, @@ -2130,7 +2122,7 @@ struct ParquetReader::BloomFilterReadPlan { ParquetReader::BloomFilterReadPlan ParquetReader::PlanBloomFilterReads(ClientContext &context, ThriftFileTransport &transport, ColumnReader &column_reader, - const TableFilter &filter, bool nested_filter, idx_t column_chunk_idx) { + const TableFilter &filter, idx_t column_chunk_idx) { struct BloomFilterRange { idx_t offset; idx_t length; @@ -2151,8 +2143,7 @@ ParquetReader::PlanBloomFilterReads(ClientContext &context, ThriftFileTransport continue; } auto prune_result = CheckRowGroupFilterStatistics(context, group_index, column_reader, filter); - if (nested_filter ? prune_result == FilterPropagateResult::FILTER_ALWAYS_FALSE - : prune_result != FilterPropagateResult::NO_PRUNING_POSSIBLE) { + if (prune_result != FilterPropagateResult::NO_PRUNING_POSSIBLE) { continue; } const auto offset = NumericCast(meta_data.bloom_filter_offset); @@ -2224,7 +2215,7 @@ ParquetReader::PlanBloomFilterReads(ClientContext &context, ThriftFileTransport bool ParquetReader::TryAttachBloomFilterReadHead(ClientContext &context, ParquetReaderScanState &state, ColumnReader &column_reader, const TableFilter &filter, - bool nested_filter, idx_t column_chunk_idx) { + idx_t column_chunk_idx) { if (!state.prefetch_mode || parquet_options.encryption_config) { return false; } @@ -2242,8 +2233,7 @@ bool ParquetReader::TryAttachBloomFilterReadHead(ClientContext &context, Parquet lock_guard guard(bloom_filter_read_heads_lock); auto entry = bloom_filter_read_heads.find(column_chunk_idx); if (entry == bloom_filter_read_heads.end()) { - auto plan = - PlanBloomFilterReads(context, transport, column_reader, filter, nested_filter, column_chunk_idx); + auto plan = PlanBloomFilterReads(context, transport, column_reader, filter, column_chunk_idx); fetch_heads = std::move(plan.fetch_heads); entry = bloom_filter_read_heads.emplace(column_chunk_idx, std::move(plan.row_group_heads)).first; } @@ -2389,7 +2379,7 @@ void ParquetReader::PreparePageIndexInternal(ClientContext &context, ParquetRead if (column_chunk.__isset.meta_data && column_chunk.meta_data.__isset.statistics) { can_have_nan = ParquetStatisticsUtils::CanHaveNaN(column_chunk.meta_data.statistics, can_have_nan); } - ParquetPageIndexUtils::FilterPages(column_reader.Schema(), column_index, filter_column.filter.get(), + ParquetPageIndexUtils::FilterPages(context, column_reader.Schema(), column_index, filter_column.filter.get(), parquet_options, can_have_nan, page_may_match[i]); for (auto may_match : page_may_match[i]) { any_page_pruned = any_page_pruned || !may_match; diff --git a/src/duckdb/extension/parquet/parquet_statistics.cpp b/src/duckdb/extension/parquet/parquet_statistics.cpp index 6af317a3b..8a5e8a79a 100644 --- a/src/duckdb/extension/parquet/parquet_statistics.cpp +++ b/src/duckdb/extension/parquet/parquet_statistics.cpp @@ -165,6 +165,11 @@ Value ParquetStatisticsUtils::ConvertValue(const LogicalType &type, const Parque //! Statistics values that do not fit in the width of the decimal are ignored template static Value ParquetDecimalStatsValue(T value, uint32_t width, uint32_t scale) { + if (width > Decimal::MAX_WIDTH_INT128) { + // a wide decimal (a BIGNUM blob) backed by an integer column, which every integer fits in + auto blob = DecimalHelper::FromInteger(hugeint_t(value)); + return Value::DECIMAL(bignum_t(string_t(blob)), width, scale); + } const auto max_value = Hugeint::POWERS_OF_TEN[width]; const auto hugeint_value = hugeint_t(value); if (hugeint_value >= max_value || hugeint_value <= -max_value) { @@ -226,10 +231,6 @@ Value ParquetStatisticsUtils::ConvertValueInternal(const LogicalType &type, cons return Value::FLOAT(val); } case LogicalTypeId::DOUBLE: { - if (schema_ele.type_info == ParquetExtraTypeInfo::DECIMAL_BYTE_ARRAY) { - // decimals cast to double - return Value::DOUBLE(ParquetDecimalUtils::ReadDecimalValue(stats_data, stats.size(), schema_ele)); - } if (stats.size() != sizeof(double)) { throw InvalidInputException("Incorrect stats size for type DOUBLE"); } @@ -1041,6 +1042,10 @@ static optional ValueXXH64(const Value &constant, const ParquetColumnS return ParquetIntervalUtils::TryHashNormalized(interval); } case LogicalTypeId::DECIMAL: + if (constant.type().InternalType() == PhysicalType::VARCHAR) { + // wide decimals (BIGNUM blobs) are not hashed, whichever physical type holds them + return nullopt; + } if (schema.parquet_type == duckdb_parquet::Type::INT32) { return ValueXH64FixedWidth(constant); } else if (schema.parquet_type == duckdb_parquet::Type::INT64) { @@ -1223,6 +1228,10 @@ ParquetStatisticsUtils::GetBloomFilterHashStrategy(const ParquetColumnSchema &sc } return nullopt; case LogicalTypeId::DECIMAL: + if (schema.type.InternalType() == PhysicalType::VARCHAR) { + // wide decimals (BIGNUM blobs) are not probed, also not when an integer column holds them + return nullopt; + } // We currently only support decimal bloom filters backed by 32-bit or 64-bit integers. if (schema.parquet_type == duckdb_parquet::Type::INT32 || schema.parquet_type == duckdb_parquet::Type::INT64) { return ParquetBloomFilterHashStrategy::STANDARD; diff --git a/src/duckdb/extension/parquet/parquet_writer.cpp b/src/duckdb/extension/parquet/parquet_writer.cpp index 884bece93..425d2a388 100644 --- a/src/duckdb/extension/parquet/parquet_writer.cpp +++ b/src/duckdb/extension/parquet/parquet_writer.cpp @@ -8,6 +8,7 @@ #include "parquet_crypto.hpp" #include "parquet_decimal_utils.hpp" +#include "writer/parquet_write_stats.hpp" #include "parquet_shredding.hpp" #include "parquet_timestamp.hpp" #include "resizable_buffer.hpp" @@ -155,7 +156,8 @@ bool ParquetWriter::TryGetParquetType(const LogicalType &duckdb_type, optional_p break; case LogicalTypeId::UHUGEINT: case LogicalTypeId::HUGEINT: - parquet_type = Type::DOUBLE; + // written as DECIMAL(39,0), which holds the full range of both types + parquet_type = Type::FIXED_LEN_BYTE_ARRAY; break; case LogicalTypeId::ENUM: case LogicalTypeId::BLOB: @@ -360,6 +362,14 @@ void ParquetWriter::SetSchemaProperties(const LogicalType &duckdb_type, duckdb_p schema_ele.__isset.logicalType = true; schema_ele.logicalType.__isset.UUID = true; break; + case LogicalTypeId::HUGEINT: + case LogicalTypeId::UHUGEINT: + // the full range of HUGEINT / UHUGEINT needs 39 digits, so the column is declared as a DECIMAL(39,0) + SetSchemaProperties(LogicalType::DECIMAL(ParquetHugeintDecimalTargetType::DECIMAL_WIDTH, 0), schema_ele, + allow_geometry, context, write_timestamp_as_int96, timestamp_is_adjusted_to_utc); + // with a length that is longer than the width needs, see ParquetHugeintDecimalTargetType + schema_ele.type_length = NumericCast(ParquetHugeintDecimalTargetType::PARQUET_SIZE); + break; case LogicalTypeId::DECIMAL: if (DecimalType::GetWidth(duckdb_type) > idx_t(NumericLimits::Maximum())) { throw NotImplementedException("Parquet DECIMAL precision is a 32-bit integer, %s cannot be written", @@ -524,7 +534,6 @@ struct ColumnStatsUnifier { bool max_is_exact = true; idx_t column_size_bytes = 0; bool can_have_nan = false; - bool has_nan = false; idx_t nan_count = 0; unique_ptr geo_stats; @@ -1274,10 +1283,12 @@ static unique_ptr GetBaseStatsUnifier(const LogicalType &typ return make_uniq>(); case LogicalTypeId::FLOAT: return make_uniq>(); - case LogicalTypeId::HUGEINT: - case LogicalTypeId::UHUGEINT: case LogicalTypeId::DOUBLE: return make_uniq>(); + case LogicalTypeId::HUGEINT: + case LogicalTypeId::UHUGEINT: + // written as DECIMAL(39,0) + return make_uniq(ParquetHugeintDecimalTargetType::DECIMAL_WIDTH, 0); case LogicalTypeId::DECIMAL: { auto width = DecimalType::GetWidth(type); auto scale = DecimalType::GetScale(type); @@ -1376,22 +1387,12 @@ void ParquetWriter::FlushColumnStats(idx_t col_idx, duckdb_parquet::ColumnChunk // push the stats of this column into the unifier auto &stats_unifier = stats_accumulator->stats_unifiers[col_idx]; - bool has_nan = false; if (writer_stats) { stats_unifier->can_have_nan = writer_stats->CanHaveNaN(); - has_nan = writer_stats->HasNaN(); - // this is called once per row group: accumulate, so NaNs in earlier row groups are not lost - stats_unifier->has_nan = stats_unifier->has_nan || has_nan; stats_unifier->nan_count += writer_stats->GetNaNCount(); } if (column.meta_data.__isset.statistics) { - if (has_nan && writer_stats->HasStats()) { - // if we have NaN values we have not written the min/max to the Parquet file - // BUT we can return them as part of RETURN STATS by fetching them from the stats directly - stats_unifier->UnifyMinMax(writer_stats->GetMin(), writer_stats->GetMax()); - stats_unifier->min_is_exact = stats_unifier->min_is_exact && writer_stats->MinIsExact(); - stats_unifier->max_is_exact = stats_unifier->max_is_exact && writer_stats->MaxIsExact(); - } else if (column.meta_data.statistics.__isset.min_value && column.meta_data.statistics.__isset.max_value) { + if (column.meta_data.statistics.__isset.min_value && column.meta_data.statistics.__isset.max_value) { stats_unifier->UnifyMinMax(column.meta_data.statistics.min_value, column.meta_data.statistics.max_value); stats_unifier->min_is_exact = stats_unifier->min_is_exact && column.meta_data.statistics.__isset.is_min_value_exact && @@ -1455,7 +1456,7 @@ void ParquetWriter::GatherWrittenStatistics() { column_stats["null_count"] = Value::UBIGINT(stats_unifier->null_count); } if (stats_unifier->can_have_nan) { - column_stats["has_nan"] = Value::BOOLEAN(stats_unifier->has_nan); + column_stats["has_nan"] = Value::BOOLEAN(stats_unifier->nan_count != 0); column_stats["nan_count"] = Value::UBIGINT(stats_unifier->nan_count); } if (stats_unifier->geo_stats) { diff --git a/src/duckdb/extension/parquet/reader/decimal_column_reader.cpp b/src/duckdb/extension/parquet/reader/decimal_column_reader.cpp index 4962ee148..b2cd2ea00 100644 --- a/src/duckdb/extension/parquet/reader/decimal_column_reader.cpp +++ b/src/duckdb/extension/parquet/reader/decimal_column_reader.cpp @@ -32,8 +32,6 @@ static unique_ptr CreateDecimalReaderInternal(const ParquetReader return make_uniq>(reader, schema); case PhysicalType::INT128: return make_uniq>(reader, schema); - case PhysicalType::DOUBLE: - return make_uniq>(reader, schema); case PhysicalType::VARCHAR: // wide decimal stored as a BIGNUM blob return make_uniq(reader, schema); @@ -42,35 +40,6 @@ static unique_ptr CreateDecimalReaderInternal(const ParquetReader } } -template <> -double ParquetDecimalUtils::ReadDecimalValue(const_data_ptr_t pointer, idx_t size, - const ParquetColumnSchema &schema_ele) { - double res = 0; - if (size == 0) { - // empty byte array - value is zero, and there is no sign byte to read - return res; - } - bool positive = (*pointer & 0x80) == 0; - for (idx_t i = 0; i < size; i += sizeof(uint64_t)) { - // the trailing chunk can hold fewer than 8 bytes - scale by the bytes actually consumed - auto byte_size = MinValue(sizeof(uint64_t), size - i); - uint64_t input = 0; - for (idx_t k = 0; k < byte_size; k++) { - auto byte = pointer[i + k]; - input = (input << 8) | static_cast(positive ? byte : byte ^ 0xFF); - } - res = std::ldexp(res, static_cast(8 * byte_size)); - res += static_cast(input); - } - if (!positive) { - res += 1; - res /= pow(10, schema_ele.type_scale); - return -res; - } - res /= pow(10, schema_ele.type_scale); - return res; -} - unique_ptr ParquetDecimalUtils::CreateReader(const ParquetReader &reader, const ParquetColumnSchema &schema) { if (schema.parquet_type == Type::FIXED_LEN_BYTE_ARRAY) { @@ -87,7 +56,12 @@ string ParquetDecimalUtils::ReadWideDecimalValue(const_data_ptr_t pointer, idx_t idx_t ParquetDecimalUtils::WideDecimalByteLength(uint32_t width) { // a decimal of "width" digits needs log2(10^width) bits plus a sign bit - return static_cast(std::ceil((static_cast(width) * 3.3219280948873626 + 1) / 8.0)); + const auto required_bytes = + static_cast(std::ceil((static_cast(width) * 3.3219280948873626 + 1) / 8.0)); + // The length is rounded up to a multiple of 8 bytes, which the Parquet format allows (the length only has to be + // large enough for the precision). DuckDB 1.x reads a decimal of more than 38 digits as a DOUBLE with a decoder + // that misreads the trailing partial 8-byte chunk of any other length, without an error + return AlignValue(required_bytes, 8); } void ParquetDecimalUtils::WriteWideDecimal(const bignum_t &value, idx_t byte_length, data_ptr_t result) { diff --git a/src/duckdb/extension/parquet/reader/variant/parquet_variant_shredding.cpp b/src/duckdb/extension/parquet/reader/variant/parquet_variant_shredding.cpp index cc30f65eb..67514c6de 100644 --- a/src/duckdb/extension/parquet/reader/variant/parquet_variant_shredding.cpp +++ b/src/duckdb/extension/parquet/reader/variant/parquet_variant_shredding.cpp @@ -281,7 +281,7 @@ bool TypedValid(const ShreddedGroupView &view, idx_t index) { //! A root that resolves to a (variant) NULL / missing is a genuine SQL NULL row (matches the unshredded path) bool IsRowNull(const ParquetVariantNode &root) { - return root.IsNull() || root.GetTypeId() == VariantLogicalType::VARIANT_NULL; + return root.IsNull() || root.GetTypeId() == LogicalTypeId::SQLNULL; } //! Set the shredded struct validity for the SQL NULL rows (used when there is no leftover to build, so the diff --git a/src/duckdb/extension/parquet/writer/primitive_column_writer.cpp b/src/duckdb/extension/parquet/writer/primitive_column_writer.cpp index 7a10a0c45..1359886c8 100644 --- a/src/duckdb/extension/parquet/writer/primitive_column_writer.cpp +++ b/src/duckdb/extension/parquet/writer/primitive_column_writer.cpp @@ -429,36 +429,33 @@ void PrimitiveColumnWriter::SetParquetStatistics(PrimitiveColumnWriterState &sta column_chunk.meta_data.statistics.__isset.nan_count = true; } - // if we have NaN values - don't write the min/max here - if (!state.stats_state->HasNaN()) { - // set min/max/min_value/max_value - // this code is not going to win any beauty contests, but well - auto min = state.stats_state->GetMin(); - if (!min.empty()) { - column_chunk.meta_data.statistics.min = min; - column_chunk.meta_data.statistics.__isset.min = true; - column_chunk.meta_data.__isset.statistics = true; - } - auto max = state.stats_state->GetMax(); - if (!max.empty()) { - column_chunk.meta_data.statistics.max = max; - column_chunk.meta_data.statistics.__isset.max = true; - column_chunk.meta_data.__isset.statistics = true; - } + // set min/max/min_value/max_value - NaN values are excluded from these, and only counted in the nan_count + // this code is not going to win any beauty contests, but well + auto min = state.stats_state->GetMin(); + if (!min.empty()) { + column_chunk.meta_data.statistics.min = min; + column_chunk.meta_data.statistics.__isset.min = true; + column_chunk.meta_data.__isset.statistics = true; + } + auto max = state.stats_state->GetMax(); + if (!max.empty()) { + column_chunk.meta_data.statistics.max = max; + column_chunk.meta_data.statistics.__isset.max = true; + column_chunk.meta_data.__isset.statistics = true; + } - if (state.stats_state->HasStats()) { - column_chunk.meta_data.statistics.min_value = state.stats_state->GetMinValue(); - column_chunk.meta_data.statistics.__isset.min_value = true; - column_chunk.meta_data.__isset.statistics = true; - column_chunk.meta_data.statistics.is_min_value_exact = state.stats_state->MinIsExact(); - column_chunk.meta_data.statistics.__isset.is_min_value_exact = true; - - column_chunk.meta_data.statistics.max_value = state.stats_state->GetMaxValue(); - column_chunk.meta_data.statistics.__isset.max_value = true; - column_chunk.meta_data.__isset.statistics = true; - column_chunk.meta_data.statistics.is_max_value_exact = state.stats_state->MaxIsExact(); - column_chunk.meta_data.statistics.__isset.is_max_value_exact = true; - } + if (state.stats_state->HasStats()) { + column_chunk.meta_data.statistics.min_value = state.stats_state->GetMinValue(); + column_chunk.meta_data.statistics.__isset.min_value = true; + column_chunk.meta_data.__isset.statistics = true; + column_chunk.meta_data.statistics.is_min_value_exact = state.stats_state->MinIsExact(); + column_chunk.meta_data.statistics.__isset.is_min_value_exact = true; + + column_chunk.meta_data.statistics.max_value = state.stats_state->GetMaxValue(); + column_chunk.meta_data.statistics.__isset.max_value = true; + column_chunk.meta_data.__isset.statistics = true; + column_chunk.meta_data.statistics.is_max_value_exact = state.stats_state->MaxIsExact(); + column_chunk.meta_data.statistics.__isset.is_max_value_exact = true; } if (HasDictionary(state)) { column_chunk.meta_data.statistics.distinct_count = UnsafeNumericCast(DictionarySize(state)); diff --git a/src/duckdb/generated_extension_loader_package_build.cpp b/src/duckdb/generated_extension_loader_package_build.cpp index 2ed0c2c61..d0f27a8df 100644 --- a/src/duckdb/generated_extension_loader_package_build.cpp +++ b/src/duckdb/generated_extension_loader_package_build.cpp @@ -45,7 +45,7 @@ int32_t duckdb_extension_core_functions_describe(duckdb_extension_descriptor *de descriptor->version = 1; descriptor->name = "core_functions"; descriptor->extension_version = EXT_VERSION_CORE_FUNCTIONS; - descriptor->api_version = "v2.1.0-alpha57538"; + descriptor->api_version = "ca7a503a52"; descriptor->entry_cpp = (void (*)(void))core_functions_duckdb_cpp_init; return 0; } @@ -78,7 +78,7 @@ int32_t duckdb_extension_parquet_describe(duckdb_extension_descriptor *descripto descriptor->version = 1; descriptor->name = "parquet"; descriptor->extension_version = EXT_VERSION_PARQUET; - descriptor->api_version = "v2.1.0-alpha57538"; + descriptor->api_version = "ca7a503a52"; descriptor->entry_cpp = (void (*)(void))parquet_duckdb_cpp_init; return 0; } @@ -111,7 +111,7 @@ int32_t duckdb_extension_icu_describe(duckdb_extension_descriptor *descriptor) { descriptor->version = 1; descriptor->name = "icu"; descriptor->extension_version = EXT_VERSION_ICU; - descriptor->api_version = "v2.1.0-alpha57538"; + descriptor->api_version = "ca7a503a52"; descriptor->entry_cpp = (void (*)(void))icu_duckdb_cpp_init; return 0; } @@ -144,7 +144,7 @@ int32_t duckdb_extension_json_describe(duckdb_extension_descriptor *descriptor) descriptor->version = 1; descriptor->name = "json"; descriptor->extension_version = EXT_VERSION_JSON; - descriptor->api_version = "v2.1.0-alpha57538"; + descriptor->api_version = "ca7a503a52"; descriptor->entry_cpp = (void (*)(void))json_duckdb_cpp_init; return 0; } diff --git a/src/duckdb/src/common/enum_util.cpp b/src/duckdb/src/common/enum_util.cpp index 2f2c0b1f8..442a0f269 100644 --- a/src/duckdb/src/common/enum_util.cpp +++ b/src/duckdb/src/common/enum_util.cpp @@ -104,6 +104,7 @@ #include "duckdb/common/operator/decimal_cast_operators.hpp" #include "duckdb/common/printer.hpp" #include "duckdb/common/sorting/sort_key.hpp" +#include "duckdb/common/sorting/topn_heap.hpp" #include "duckdb/common/types.hpp" #include "duckdb/common/types/column/column_data_collection_segment.hpp" #include "duckdb/common/types/column/column_data_scan_states.hpp" @@ -168,6 +169,7 @@ #include "duckdb/main/extension.hpp" #include "duckdb/main/extension_helper.hpp" #include "duckdb/main/extension_install_info.hpp" +#include "duckdb/main/extension_repository_manager.hpp" #include "duckdb/main/http/http_retry_budget.hpp" #include "duckdb/main/http/http_util.hpp" #include "duckdb/main/os_util.hpp" @@ -1416,19 +1418,20 @@ const StringUtil::EnumStringLiteral *GetColumnDataRepresentationValues() { static constexpr StringUtil::EnumStringLiteral values[] { { static_cast(ColumnDataRepresentation::FLAT), "FLAT" }, { static_cast(ColumnDataRepresentation::CONSTANT), "CONSTANT" }, - { static_cast(ColumnDataRepresentation::DICTIONARY), "DICTIONARY" } + { static_cast(ColumnDataRepresentation::DICTIONARY), "DICTIONARY" }, + { static_cast(ColumnDataRepresentation::LARGE_FLAT), "LARGE_FLAT" } }; return values; } template<> const char* EnumUtil::ToChars(ColumnDataRepresentation value) { - return StringUtil::EnumToString(GetColumnDataRepresentationValues(), 3, "ColumnDataRepresentation", static_cast(value)); + return StringUtil::EnumToString(GetColumnDataRepresentationValues(), 4, "ColumnDataRepresentation", static_cast(value)); } template<> ColumnDataRepresentation EnumUtil::FromString(const char *value) { - return static_cast(StringUtil::StringToEnum(GetColumnDataRepresentationValues(), 3, "ColumnDataRepresentation", value)); + return static_cast(StringUtil::StringToEnum(GetColumnDataRepresentationValues(), 4, "ColumnDataRepresentation", value)); } const StringUtil::EnumStringLiteral *GetColumnDataScanPropertiesValues() { @@ -2638,6 +2641,24 @@ ExtensionRepositoryAccess EnumUtil::FromString(const return static_cast(StringUtil::StringToEnum(GetExtensionRepositoryAccessValues(), 4, "ExtensionRepositoryAccess", value)); } +const StringUtil::EnumStringLiteral *GetExtensionRepositoryHostCallerValues() { + static constexpr StringUtil::EnumStringLiteral values[] { + { static_cast(ExtensionRepositoryHostCaller::CREATE_STATEMENT), "CREATE_STATEMENT" }, + { static_cast(ExtensionRepositoryHostCaller::LOOKUP), "LOOKUP" } + }; + return values; +} + +template<> +const char* EnumUtil::ToChars(ExtensionRepositoryHostCaller value) { + return StringUtil::EnumToString(GetExtensionRepositoryHostCallerValues(), 2, "ExtensionRepositoryHostCaller", static_cast(value)); +} + +template<> +ExtensionRepositoryHostCaller EnumUtil::FromString(const char *value) { + return static_cast(StringUtil::StringToEnum(GetExtensionRepositoryHostCallerValues(), 2, "ExtensionRepositoryHostCaller", value)); +} + const StringUtil::EnumStringLiteral *GetExtensionRepositoryTypeValues() { static constexpr StringUtil::EnumStringLiteral values[] { { static_cast(ExtensionRepositoryType::CORE), "CORE" }, @@ -2668,6 +2689,7 @@ const StringUtil::EnumStringLiteral *GetExtensionUpdateResultTagValues() { { static_cast(ExtensionUpdateResultTag::REPOSITORY_NOT_FOUND), "REPOSITORY_NOT_FOUND" }, { static_cast(ExtensionUpdateResultTag::REPOSITORY_NOT_TRUSTED), "REPOSITORY_NOT_TRUSTED" }, { static_cast(ExtensionUpdateResultTag::REPOSITORY_UNREADABLE), "REPOSITORY_UNREADABLE" }, + { static_cast(ExtensionUpdateResultTag::UPDATE_FAILED), "UPDATE_FAILED" }, { static_cast(ExtensionUpdateResultTag::REDOWNLOADED), "REDOWNLOADED" }, { static_cast(ExtensionUpdateResultTag::UPDATED), "UPDATED" } }; @@ -2676,12 +2698,12 @@ const StringUtil::EnumStringLiteral *GetExtensionUpdateResultTagValues() { template<> const char* EnumUtil::ToChars(ExtensionUpdateResultTag value) { - return StringUtil::EnumToString(GetExtensionUpdateResultTagValues(), 11, "ExtensionUpdateResultTag", static_cast(value)); + return StringUtil::EnumToString(GetExtensionUpdateResultTagValues(), 12, "ExtensionUpdateResultTag", static_cast(value)); } template<> ExtensionUpdateResultTag EnumUtil::FromString(const char *value) { - return static_cast(StringUtil::StringToEnum(GetExtensionUpdateResultTagValues(), 11, "ExtensionUpdateResultTag", value)); + return static_cast(StringUtil::StringToEnum(GetExtensionUpdateResultTagValues(), 12, "ExtensionUpdateResultTag", value)); } const StringUtil::EnumStringLiteral *GetExternalFileCacheRequestSizingValues() { @@ -3507,6 +3529,26 @@ InsertColumnOrder EnumUtil::FromString(const char *value) { return static_cast(StringUtil::StringToEnum(GetInsertColumnOrderValues(), 2, "InsertColumnOrder", value)); } +const StringUtil::EnumStringLiteral *GetIntegerRoundingValues() { + static constexpr StringUtil::EnumStringLiteral values[] { + { static_cast(IntegerRounding::UNKNOWN), "UNKNOWN" }, + { static_cast(IntegerRounding::FLOOR), "FLOOR" }, + { static_cast(IntegerRounding::CEIL), "CEIL" }, + { static_cast(IntegerRounding::TRUNCATE), "TRUNCATE" } + }; + return values; +} + +template<> +const char* EnumUtil::ToChars(IntegerRounding value) { + return StringUtil::EnumToString(GetIntegerRoundingValues(), 4, "IntegerRounding", static_cast(value)); +} + +template<> +IntegerRounding EnumUtil::FromString(const char *value) { + return static_cast(StringUtil::StringToEnum(GetIntegerRoundingValues(), 4, "IntegerRounding", value)); +} + const StringUtil::EnumStringLiteral *GetInterruptModeValues() { static constexpr StringUtil::EnumStringLiteral values[] { { static_cast(InterruptMode::NO_INTERRUPTS), "NO_INTERRUPTS" }, @@ -3550,6 +3592,7 @@ const StringUtil::EnumStringLiteral *GetJoinOrderOperatorTypeValues() { { static_cast(JoinOrderOperatorType::LEFT), "LEFT" }, { static_cast(JoinOrderOperatorType::SEMI), "SEMI" }, { static_cast(JoinOrderOperatorType::ANTI), "ANTI" }, + { static_cast(JoinOrderOperatorType::MARK), "MARK" }, { static_cast(JoinOrderOperatorType::CROSS_PRODUCT), "CROSS_PRODUCT" } }; return values; @@ -3557,12 +3600,12 @@ const StringUtil::EnumStringLiteral *GetJoinOrderOperatorTypeValues() { template<> const char* EnumUtil::ToChars(JoinOrderOperatorType value) { - return StringUtil::EnumToString(GetJoinOrderOperatorTypeValues(), 5, "JoinOrderOperatorType", static_cast(value)); + return StringUtil::EnumToString(GetJoinOrderOperatorTypeValues(), 6, "JoinOrderOperatorType", static_cast(value)); } template<> JoinOrderOperatorType EnumUtil::FromString(const char *value) { - return static_cast(StringUtil::StringToEnum(GetJoinOrderOperatorTypeValues(), 5, "JoinOrderOperatorType", value)); + return static_cast(StringUtil::StringToEnum(GetJoinOrderOperatorTypeValues(), 6, "JoinOrderOperatorType", value)); } const StringUtil::EnumStringLiteral *GetJoinRefTypeValues() { @@ -3913,6 +3956,7 @@ const StringUtil::EnumStringLiteral *GetLogicalOperatorTypeValues() { { static_cast(LogicalOperatorType::LOGICAL_PIVOT), "LOGICAL_PIVOT" }, { static_cast(LogicalOperatorType::LOGICAL_COPY_DATABASE), "LOGICAL_COPY_DATABASE" }, { static_cast(LogicalOperatorType::LOGICAL_SECURE_VIEW), "LOGICAL_SECURE_VIEW" }, + { static_cast(LogicalOperatorType::LOGICAL_TOP_KEY_FILTER), "LOGICAL_TOP_KEY_FILTER" }, { static_cast(LogicalOperatorType::LOGICAL_GET), "LOGICAL_GET" }, { static_cast(LogicalOperatorType::LOGICAL_CHUNK_GET), "LOGICAL_CHUNK_GET" }, { static_cast(LogicalOperatorType::LOGICAL_DELIM_GET), "LOGICAL_DELIM_GET" }, @@ -3971,12 +4015,12 @@ const StringUtil::EnumStringLiteral *GetLogicalOperatorTypeValues() { template<> const char* EnumUtil::ToChars(LogicalOperatorType value) { - return StringUtil::EnumToString(GetLogicalOperatorTypeValues(), 67, "LogicalOperatorType", static_cast(value)); + return StringUtil::EnumToString(GetLogicalOperatorTypeValues(), 68, "LogicalOperatorType", static_cast(value)); } template<> LogicalOperatorType EnumUtil::FromString(const char *value) { - return static_cast(StringUtil::StringToEnum(GetLogicalOperatorTypeValues(), 67, "LogicalOperatorType", value)); + return static_cast(StringUtil::StringToEnum(GetLogicalOperatorTypeValues(), 68, "LogicalOperatorType", value)); } const StringUtil::EnumStringLiteral *GetLogicalPlanVerificationIssueCodeValues() { @@ -4776,19 +4820,20 @@ const StringUtil::EnumStringLiteral *GetOptimizerTypeValues() { { static_cast(OptimizerType::WINDOW_FUSION), "WINDOW_FUSION" }, { static_cast(OptimizerType::SET_OPERATION_AGGREGATE), "SET_OPERATION_AGGREGATE" }, { static_cast(OptimizerType::JOIN_TO_SEMI_JOIN), "JOIN_TO_SEMI_JOIN" }, - { static_cast(OptimizerType::MARK_JOIN_SIMPLIFIER), "MARK_JOIN_SIMPLIFIER" } + { static_cast(OptimizerType::MARK_JOIN_SIMPLIFIER), "MARK_JOIN_SIMPLIFIER" }, + { static_cast(OptimizerType::GROUP_BY_TOP_KEY), "GROUP_BY_TOP_KEY" } }; return values; } template<> const char* EnumUtil::ToChars(OptimizerType value) { - return StringUtil::EnumToString(GetOptimizerTypeValues(), 59, "OptimizerType", static_cast(value)); + return StringUtil::EnumToString(GetOptimizerTypeValues(), 60, "OptimizerType", static_cast(value)); } template<> OptimizerType EnumUtil::FromString(const char *value) { - return static_cast(StringUtil::StringToEnum(GetOptimizerTypeValues(), 59, "OptimizerType", value)); + return static_cast(StringUtil::StringToEnum(GetOptimizerTypeValues(), 60, "OptimizerType", value)); } const StringUtil::EnumStringLiteral *GetOrderByColumnTypeValues() { @@ -5125,6 +5170,7 @@ const StringUtil::EnumStringLiteral *GetPhysicalOperatorTypeValues() { { static_cast(PhysicalOperatorType::PARTITIONED_AGGREGATE), "PARTITIONED_AGGREGATE" }, { static_cast(PhysicalOperatorType::LIMITED_DISTINCT), "LIMITED_DISTINCT" }, { static_cast(PhysicalOperatorType::FILTER), "FILTER" }, + { static_cast(PhysicalOperatorType::TOP_KEY_FILTER), "TOP_KEY_FILTER" }, { static_cast(PhysicalOperatorType::PROJECTION), "PROJECTION" }, { static_cast(PhysicalOperatorType::COPY_TO_FILE), "COPY_TO_FILE" }, { static_cast(PhysicalOperatorType::BATCH_COPY_TO_FILE), "BATCH_COPY_TO_FILE" }, @@ -5206,12 +5252,12 @@ const StringUtil::EnumStringLiteral *GetPhysicalOperatorTypeValues() { template<> const char* EnumUtil::ToChars(PhysicalOperatorType value) { - return StringUtil::EnumToString(GetPhysicalOperatorTypeValues(), 89, "PhysicalOperatorType", static_cast(value)); + return StringUtil::EnumToString(GetPhysicalOperatorTypeValues(), 90, "PhysicalOperatorType", static_cast(value)); } template<> PhysicalOperatorType EnumUtil::FromString(const char *value) { - return static_cast(StringUtil::StringToEnum(GetPhysicalOperatorTypeValues(), 89, "PhysicalOperatorType", value)); + return static_cast(StringUtil::StringToEnum(GetPhysicalOperatorTypeValues(), 90, "PhysicalOperatorType", value)); } const StringUtil::EnumStringLiteral *GetPhysicalTableScanExecutionStrategyValues() { @@ -7327,6 +7373,42 @@ TimestampCastResult EnumUtil::FromString(const char *value) return static_cast(StringUtil::StringToEnum(GetTimestampCastResultValues(), 5, "TimestampCastResult", value)); } +const StringUtil::EnumStringLiteral *GetTopNBoundaryRowOrderValues() { + static constexpr StringUtil::EnumStringLiteral values[] { + { static_cast(TopNBoundaryRowOrder::ANY), "ANY" }, + { static_cast(TopNBoundaryRowOrder::INPUT_ORDER), "INPUT_ORDER" } + }; + return values; +} + +template<> +const char* EnumUtil::ToChars(TopNBoundaryRowOrder value) { + return StringUtil::EnumToString(GetTopNBoundaryRowOrderValues(), 2, "TopNBoundaryRowOrder", static_cast(value)); +} + +template<> +TopNBoundaryRowOrder EnumUtil::FromString(const char *value) { + return static_cast(StringUtil::StringToEnum(GetTopNBoundaryRowOrderValues(), 2, "TopNBoundaryRowOrder", value)); +} + +const StringUtil::EnumStringLiteral *GetTopNBoundaryTiesValues() { + static constexpr StringUtil::EnumStringLiteral values[] { + { static_cast(TopNBoundaryTies::EXCLUDE), "EXCLUDE" }, + { static_cast(TopNBoundaryTies::INCLUDE), "INCLUDE" } + }; + return values; +} + +template<> +const char* EnumUtil::ToChars(TopNBoundaryTies value) { + return StringUtil::EnumToString(GetTopNBoundaryTiesValues(), 2, "TopNBoundaryTies", static_cast(value)); +} + +template<> +TopNBoundaryTies EnumUtil::FromString(const char *value) { + return static_cast(StringUtil::StringToEnum(GetTopNBoundaryTiesValues(), 2, "TopNBoundaryTies", value)); +} + const StringUtil::EnumStringLiteral *GetTransactionInvalidationPolicyValues() { static constexpr StringUtil::EnumStringLiteral values[] { { static_cast(TransactionInvalidationPolicy::STANDARD_POLICY), "STANDARD_POLICY" }, diff --git a/src/duckdb/src/common/enums/logical_operator_type.cpp b/src/duckdb/src/common/enums/logical_operator_type.cpp index 197e678ce..d31b14f34 100644 --- a/src/duckdb/src/common/enums/logical_operator_type.cpp +++ b/src/duckdb/src/common/enums/logical_operator_type.cpp @@ -44,6 +44,8 @@ string LogicalOperatorToString(LogicalOperatorType type) { return "ORDER_BY"; case LogicalOperatorType::LOGICAL_TOP_N: return "TOP_N"; + case LogicalOperatorType::LOGICAL_TOP_KEY_FILTER: + return "TOP_KEY_FILTER"; case LogicalOperatorType::LOGICAL_SAMPLE: return "SAMPLE"; case LogicalOperatorType::LOGICAL_COPY_TO_FILE: diff --git a/src/duckdb/src/common/enums/optimizer_type.cpp b/src/duckdb/src/common/enums/optimizer_type.cpp index ca79ea23f..56d00c6c0 100644 --- a/src/duckdb/src/common/enums/optimizer_type.cpp +++ b/src/duckdb/src/common/enums/optimizer_type.cpp @@ -71,6 +71,7 @@ static const DefaultOptimizerType internal_optimizer_types[] = { {"redundant_distinct", OptimizerType::REDUNDANT_DISTINCT}, {"set_operation_aggregate", OptimizerType::SET_OPERATION_AGGREGATE}, {"join_to_semi_join", OptimizerType::JOIN_TO_SEMI_JOIN}, + {"group_by_top_key", OptimizerType::GROUP_BY_TOP_KEY}, {nullptr, OptimizerType::INVALID}}; string OptimizerTypeToString(OptimizerType type) { diff --git a/src/duckdb/src/common/enums/physical_operator_type.cpp b/src/duckdb/src/common/enums/physical_operator_type.cpp index 5180e64d8..469803cd6 100644 --- a/src/duckdb/src/common/enums/physical_operator_type.cpp +++ b/src/duckdb/src/common/enums/physical_operator_type.cpp @@ -47,6 +47,8 @@ string PhysicalOperatorToString(PhysicalOperatorType type) { return "LIMITED_DISTINCT"; case PhysicalOperatorType::FILTER: return "FILTER"; + case PhysicalOperatorType::TOP_KEY_FILTER: + return "TOP_KEY_FILTER"; case PhysicalOperatorType::PROJECTION: return "PROJECTION"; case PhysicalOperatorType::COPY_TO_FILE: diff --git a/src/duckdb/src/common/file_system.cpp b/src/duckdb/src/common/file_system.cpp index 83b5da215..ddc350927 100644 --- a/src/duckdb/src/common/file_system.cpp +++ b/src/duckdb/src/common/file_system.cpp @@ -726,43 +726,6 @@ unique_ptr FileSystem::GlobFilesExtended(const string &path, cons throw NotImplementedException("%s: GlobFilesExtended is not implemented!", GetName()); } -void FileSystem::RegisterSubSystem(unique_ptr sub_fs) { - throw NotImplementedException("%s: Can't register a sub system on a non-virtual file system", GetName()); -} - -void FileSystem::UnregisterSubSystem(const string &name) { - throw NotImplementedException("%s: Can't unregister a sub system on a non-virtual file system", GetName()); -} - -void FileSystem::RegisterCompressionFilesystem(unique_ptr fs) { - throw NotImplementedException("%s: Can't register a compression filesystem on a non-virtual file system", - GetName()); -} - -unique_ptr FileSystem::ExtractSubSystem(const string &name) { - throw NotImplementedException("%s: Can't extract a sub system on a non-virtual file system", GetName()); -} - -void FileSystem::SetDisabledFileSystems(const vector &names) { - throw NotImplementedException("%s: Can't disable file systems on a non-virtual file system", GetName()); -} - -vector FileSystem::GetDisabledFileSystems() { - return vector(); -} - -bool FileSystem::SubSystemIsDisabled(const string &name) { - throw NotImplementedException("%s: Non-virtual file system does not have subsystems", GetName()); -} - -bool FileSystem::IsDisabledForPath(const string &path) { - throw NotImplementedException("%s: Non-virtual file system does not have subsystems", GetName()); -} - -vector FileSystem::ListSubSystems() { - throw NotImplementedException("%s: Can't list sub systems on a non-virtual file system", GetName()); -} - bool FileSystem::CanHandleFile(const string &fpath) { throw NotImplementedException("%s: CanHandleFile is not implemented!", GetName()); } diff --git a/src/duckdb/src/common/multi_file/multi_file_list.cpp b/src/duckdb/src/common/multi_file/multi_file_list.cpp index 69c23cf8e..90862cfa8 100644 --- a/src/duckdb/src/common/multi_file/multi_file_list.cpp +++ b/src/duckdb/src/common/multi_file/multi_file_list.cpp @@ -374,85 +374,4 @@ bool LazyMultiFileList::ExpandNextPathInternal() const { return true; } -//===--------------------------------------------------------------------===// -// GlobMultiFileList -//===--------------------------------------------------------------------===// -static vector PathsToFiles(vector paths) { - vector result; - result.reserve(paths.size()); - for (auto &path : paths) { - result.emplace_back(std::move(path)); - } - return result; -} - -GlobMultiFileList::GlobMultiFileList(ClientContext &context_p, vector globs_p, FileGlobInput glob_input_p) - : GlobMultiFileList(context_p, PathsToFiles(std::move(globs_p)), std::move(glob_input_p)) { -} - -GlobMultiFileList::GlobMultiFileList(ClientContext &context_p, vector globs_p, FileGlobInput glob_input_p) - : LazyMultiFileList(&context_p.GetContext()), context(context_p), globs(std::move(globs_p)), - glob_input(std::move(glob_input_p)), current_glob(0) { -} - -vector GlobMultiFileList::GetDisplayFileList(optional_idx max_files) const { - // for globs we display the actual globs in the ToString() - instead of expanding to the files read - vector result; - for (auto &glob : globs) { - if (max_files.IsValid() && result.size() >= max_files.GetIndex()) { - break; - } - result.emplace_back(glob); - } - return result; -} - -bool GlobMultiFileList::ExpandNextPath() const { - if (current_glob >= globs.size()) { - return false; - } - auto ¤t_entry = globs[current_glob]; - if (current_entry.extended_info) { - // the file was specified together with the options to open it with - use it as-is - expanded_files.push_back(current_entry); - current_glob++; - return true; - } - if (current_glob >= file_lists.size()) { - file_lists.resize(current_glob + 1); - } - if (!file_lists[current_glob]) { - // glob is not yet started for this file - start it and initiate the scan over this file - auto &fs = FileSystem::GetFileSystem(context); - auto glob_result = fs.GlobFileList(current_entry.path, glob_input); - scan_state = MultiFileListScanData(); - glob_result->InitializeScan(scan_state); - file_lists[current_glob] = std::move(glob_result); - } - // get the next batch of files we can fetch through the glob - auto &glob_list = *file_lists[current_glob]; - scan_state.scan_type = MultiFileListScanType::ALWAYS_FETCH; - OpenFileInfo file; - if (!glob_list.Scan(scan_state, file)) { - // no more files available in this glob - move to the next glob - current_glob++; - return true; - } - // we found a file as part of this glob - add it to the result - vector glob_files; - glob_files.push_back(std::move(file)); - - // now continue scanning files that are already available (i.e. that don't require extra I/O operations to fetch) - scan_state.scan_type = MultiFileListScanType::FETCH_IF_AVAILABLE; - while (glob_list.Scan(scan_state, file)) { - glob_files.push_back(std::move(file)); - } - - // sort the files and add them to the list of files - std::sort(glob_files.begin(), glob_files.end()); - expanded_files.insert(expanded_files.end(), glob_files.begin(), glob_files.end()); - - return true; -} - } // namespace duckdb diff --git a/src/duckdb/src/common/multi_file/multi_file_reader.cpp b/src/duckdb/src/common/multi_file/multi_file_reader.cpp index 155fcf755..532421c43 100644 --- a/src/duckdb/src/common/multi_file/multi_file_reader.cpp +++ b/src/duckdb/src/common/multi_file/multi_file_reader.cpp @@ -10,6 +10,7 @@ #include "duckdb/common/types/value.hpp" #include "duckdb/function/function_set.hpp" #include "duckdb/function/table_function.hpp" +#include "duckdb/common/multi_file/table_function_multi_file_list.hpp" #include "duckdb/main/config.hpp" #include "duckdb/common/multi_file/multi_file_column_mapper.hpp" #include "duckdb/planner/expression/bound_reference_expression.hpp" @@ -215,9 +216,27 @@ vector MultiFileReader::ParseFileList(const Value &input) { return files; } +//! A file list that expands the globs with the glob table function +static unique_ptr CreateGlobFileList(ClientContext &context, Value globs, + const FileGlobInput &glob_input) { + vector inputs {std::move(globs)}; + named_argument_map_t named_parameters; + named_parameters["full_file_info"] = Value::BOOLEAN(true); + named_parameters["allow_empty"] = Value::BOOLEAN(glob_input.AllowsEmpty()); + if (glob_input.behavior == FileGlobOptions::FALLBACK_GLOB) { + named_parameters["fallback_extension"] = Value(glob_input.extension); + } + return make_uniq(context, Identifier("glob"), std::move(inputs), + std::move(named_parameters)); +} + shared_ptr MultiFileReader::CreateFileList(ClientContext &context, const vector &paths, const FileGlobInput &glob_input) { - auto res = make_uniq(context, paths, glob_input); + vector globs; + for (auto &path : paths) { + globs.emplace_back(path); + } + auto res = CreateGlobFileList(context, Value::LIST(LogicalType::VARCHAR, std::move(globs)), glob_input); if (res->GetExpandResult() == FileExpandResult::NO_FILES && !glob_input.AllowsEmpty()) { throw IOException("%s needs at least one file to read", function_name); } @@ -242,7 +261,12 @@ shared_ptr MultiFileReader::CreateFileList(ClientContext &context } return CreateFileList(context, paths, glob_input); } - auto res = make_uniq(context, std::move(files), glob_input); + // glob lists the files with open options as-is - a VARIANT lets every file have its own options + vector entries; + for (auto &file : files) { + entries.push_back(file.ToValue().CastAs(context, LogicalType::VARIANT())); + } + auto res = CreateGlobFileList(context, Value::LIST(LogicalType::VARIANT(), std::move(entries)), glob_input); if (res->GetExpandResult() == FileExpandResult::NO_FILES && !glob_input.AllowsEmpty()) { throw IOException("%s needs at least one file to read", function_name); } diff --git a/src/duckdb/src/common/multi_file/table_function_multi_file_list.cpp b/src/duckdb/src/common/multi_file/table_function_multi_file_list.cpp new file mode 100644 index 000000000..98f79dd5b --- /dev/null +++ b/src/duckdb/src/common/multi_file/table_function_multi_file_list.cpp @@ -0,0 +1,194 @@ +#include "duckdb/common/multi_file/table_function_multi_file_list.hpp" + +#include "duckdb/catalog/catalog.hpp" +#include "duckdb/catalog/catalog_entry/table_function_catalog_entry.hpp" +#include "duckdb/common/types/variant.hpp" +#include "duckdb/common/vector/map_vector.hpp" +#include "duckdb/function/scalar/variant_utils.hpp" +#include "duckdb/function/function_set.hpp" +#include "duckdb/main/client_context.hpp" +#include "duckdb/parallel/async_result.hpp" +#include "duckdb/parser/tableref/table_function_ref.hpp" + +namespace duckdb { + +static bool IsOptionsColumn(const LogicalType &type) { + return type.id() == LogicalTypeId::MAP && MapType::KeyType(type).id() == LogicalTypeId::VARCHAR; +} + +static vector GetInputFiles(const vector &inputs, const Identifier &function_name) { + vector result; + if (inputs.empty() || inputs[0].IsNull()) { + return result; + } + auto &input = inputs[0]; + if (input.type().id() == LogicalTypeId::LIST) { + for (auto &entry : ListValue::GetChildren(input)) { + if (entry.IsNull()) { + return vector(); + } + result.push_back(OpenFileInfo::FromValue(entry, function_name)); + } + return result; + } + auto type = input.type().id(); + if (type == LogicalTypeId::VARCHAR || type == LogicalTypeId::STRUCT || type == LogicalTypeId::VARIANT) { + result.push_back(OpenFileInfo::FromValue(input, function_name)); + } + return result; +} + +TableFunctionMultiFileList::TableFunctionMultiFileList(ClientContext &context_p, const Identifier &function_name, + vector inputs, named_argument_map_t named_parameters) + : LazyMultiFileList(&context_p.GetContext()), context(context_p) { + // resolved fully qualified in the system catalog, so a macro of the same name in the search path is never used + auto &catalog = Catalog::GetSystemCatalog(context); + auto &entry = catalog.GetEntry( + context, QualifiedName(catalog.GetName(), Identifier::DefaultSchema(), function_name)); + vector input_types; + for (auto &input : inputs) { + input_types.push_back(input.type()); + } + function = *entry.functions.GetFunctionByArguments(context, input_types); + if (!function.bind || !function.function || function.init_local) { + // functions with a local state need an execution context, which a file list does not have + throw BinderException("Table function %s cannot provide a file list", function.name); + } + auto &signature = function.GetSignature(); + for (idx_t i = 0; i < inputs.size() && i < signature.GetPositionalParameterCount(); i++) { + auto ¶meter_type = signature.GetParameter(i).GetType(); + if (parameter_type.id() != LogicalTypeId::ANY && parameter_type.id() != LogicalTypeId::LIST && + inputs[i].type() != parameter_type) { + inputs[i] = inputs[i].DefaultCastAs(parameter_type); + } + } + signature.FillNamedDefaults(context, named_parameters); + input_files = GetInputFiles(inputs, function.name); + + vector input_table_types; + vector input_table_names; + TableFunctionRef empty_ref; + BoundTableFunction bound_function(function); + TableFunctionBindInput bind_input(inputs, named_parameters, input_table_types, input_table_names, + function.function_info.get(), nullptr, bound_function, empty_ref); + vector names; + bind_data = function.bind(context, bind_input, return_types, names); + + auto file_type = return_types.empty() ? LogicalTypeId::INVALID : return_types[0].id(); + if (file_type != LogicalTypeId::VARCHAR && file_type != LogicalTypeId::STRUCT && + file_type != LogicalTypeId::VARIANT) { + throw BinderException("Table function %s cannot provide a file list - its first column must be a VARCHAR " + "path or a file struct, not %s", + function.name, return_types.empty() ? "nothing" : return_types[0].ToString()); + } +} + +TableFunctionMultiFileList::~TableFunctionMultiFileList() { +} + +vector TableFunctionMultiFileList::GetDisplayFileList(optional_idx max_files) const { + if (input_files.empty()) { + return LazyMultiFileList::GetDisplayFileList(max_files); + } + vector result; + for (auto &file : input_files) { + if (max_files.IsValid() && result.size() >= max_files.GetIndex()) { + break; + } + result.push_back(file); + } + return result; +} + +void TableFunctionMultiFileList::InitializeFunction() const { + if (initialized) { + return; + } + vector column_ids; + for (idx_t col_idx = 0; col_idx < return_types.size(); col_idx++) { + column_ids.push_back(col_idx); + } + vector projection_ids; + TableFunctionInitInput init_input(bind_data.get(), column_ids, projection_ids, nullptr); + if (function.init_global) { + global_state = function.init_global(context, init_input); + } + chunk.Initialize(Allocator::Get(context), return_types); + initialized = true; +} + +void TableFunctionMultiFileList::ReadFiles(DataChunk &output) const { + auto start = expanded_files.size(); + auto &files = output.data[0]; + if (files.GetType().id() == LogicalTypeId::VARCHAR) { + for (auto entry : files.Values()) { + if (!entry.IsValid()) { + throw InvalidInputException("Table function %s produced a NULL file", function.name); + } + expanded_files.emplace_back(entry.GetValue().GetString()); + } + } else { + for (idx_t row_idx = 0; row_idx < output.size(); row_idx++) { + expanded_files.push_back(OpenFileInfo::FromValue(files.GetValue(row_idx), function.name)); + } + } + if (output.ColumnCount() < 2 || !IsOptionsColumn(output.data[1].GetType())) { + return; + } + // the options to open the files with + auto &options = output.data[1]; + auto unpack_variant = MapType::ValueType(options.GetType()).id() == LogicalTypeId::VARIANT; + auto list_entries = options.Values(); + auto &values = MapVector::GetValues(options); + auto key_values = MapVector::GetKeys(options).Values(); + // variants are decoded from their unified format, which is only built once + RecursiveUnifiedVectorFormat variant_format; + unique_ptr variant_data; + if (unpack_variant) { + Vector::RecursiveToUnifiedFormat(values, variant_format); + variant_data = make_uniq(variant_format); + } + for (auto entry : list_entries) { + if (!entry.IsValid()) { + continue; + } + auto &file = expanded_files[start + entry.GetIndex()]; + if (!file.extended_info) { + file.extended_info = make_shared_ptr(); + } + auto list_entry = entry.GetValue(); + file.extended_info->options.reserve(file.extended_info->options.size() + list_entry.length); + for (idx_t child_idx = list_entry.offset; child_idx < list_entry.offset + list_entry.length; child_idx++) { + Value value; + if (variant_data) { + if (!variant_data->RowIsValid(child_idx)) { + continue; + } + value = VariantUtils::ConvertVariantToValue(*variant_data, child_idx, 0); + } else { + value = values.GetValue(child_idx); + } + if (value.IsNull()) { + continue; + } + file.extended_info->options[key_values[child_idx].GetValue().GetString()] = std::move(value); + } + } +} + +bool TableFunctionMultiFileList::ExpandNextPath() const { + InitializeFunction(); + TableFunctionInput input(bind_data.get(), nullptr, global_state.get()); + // the function is run synchronously, outside of a pipeline + input.async_result = AsyncResultType::IMPLICIT; + input.results_execution_mode = AsyncResultsExecutionMode::SYNCHRONOUS; + chunk.Reset(); + function.function(context, input, chunk); + if (chunk.size() == 0) { + return false; + } + ReadFiles(chunk); + return true; +} + +} // namespace duckdb diff --git a/src/duckdb/src/common/open_file_info.cpp b/src/duckdb/src/common/open_file_info.cpp index f34338232..eaaf32803 100644 --- a/src/duckdb/src/common/open_file_info.cpp +++ b/src/duckdb/src/common/open_file_info.cpp @@ -57,7 +57,7 @@ OpenFileInfo OpenFileInfo::FromValue(const Value &input, const Identifier &funct } Value OpenFileInfo::ToValue() const { - if (!extended_info || extended_info->options.empty()) { + if (!extended_info) { return Value(path); } // the options are kept unordered - sort them, so the same file always becomes the same value diff --git a/src/duckdb/src/common/opener_file_system.cpp b/src/duckdb/src/common/opener_file_system.cpp index 617947828..7baec37f4 100644 --- a/src/duckdb/src/common/opener_file_system.cpp +++ b/src/duckdb/src/common/opener_file_system.cpp @@ -5,13 +5,10 @@ #include "duckdb/common/memory_mapped_file.hpp" #include "duckdb/main/database.hpp" #include "duckdb/main/config.hpp" +#include "duckdb/storage/external_file_cache/caching_file_system_wrapper.hpp" namespace duckdb { -void OpenerFileSystem::RegisterCompressionFilesystem(unique_ptr fs) { - GetFileSystem().RegisterCompressionFilesystem(std::move(fs)); -} - unique_ptr OpenerFileSystem::MemoryMapFile(const OpenFileInfo &path, FileOpenFlags flags, const MMapOptions &options, optional_ptr opener) { @@ -20,14 +17,30 @@ unique_ptr OpenerFileSystem::MemoryMapFile(const OpenFileInfo if (IsDuckDBExtensionName(path.path)) { VerifyCanAccessExtension(path.path, flags); } - return GetFileSystem().MemoryMapFile(path, flags, options, GetOpener()); + return FindFileSystem(path.path).MemoryMapFile(path, flags, options, GetOpener()); } unique_ptr OpenerFileSystem::GlobFilesExtended(const string &path, const FileGlobInput &input, optional_ptr opener) { VerifyNoOpener(opener); VerifyCanAccessFile(path); - return GetFileSystem().Glob(path, input, GetOpener()); + return FindFileSystem(path).Glob(path, input, GetOpener()); +} + +unique_ptr OpenerFileSystem::OpenCachedFile(const OpenFileInfo &file, const FileOpenFlags &flags) { + // the cache holds the file as stored, the file system applies the compression on top of it + auto raw_flags = flags; + raw_flags.SetCompression(FileCompressionType::UNCOMPRESSED); + raw_flags.SetCachingMode(CachingMode::NO_CACHING); + + // the caching file system is kept alive by the handles it hands out + auto caching_file_system = + make_shared_ptr(FindFileSystem(file.path), GetOpener(), flags.GetCachingMode()); + auto handle = caching_file_system->OpenFile(file, raw_flags, GetOpener()); + if (!handle) { + return nullptr; + } + return GetFileSystem().WrapOpenedFile(std::move(handle), file, flags, GetOpener()); } void OpenerFileSystem::VerifyNoOpener(optional_ptr opener) { diff --git a/src/duckdb/src/common/process_util.cpp b/src/duckdb/src/common/process_util.cpp index c4fe10987..543700238 100644 --- a/src/duckdb/src/common/process_util.cpp +++ b/src/duckdb/src/common/process_util.cpp @@ -120,7 +120,7 @@ string ProcessUtil::GetProcessDescription(int64_t pid) { auto proc_exe_link = StringUtil::Format("/proc/%d/exe", pid); auto readlink_n = readlink(proc_exe_link.c_str(), exe_target, PATH_MAX); if (readlink_n > 0) { - process_name = exe_target; + process_name.assign(exe_target, static_cast(readlink_n)); } } diff --git a/src/duckdb/src/common/row_operations/row_matcher.cpp b/src/duckdb/src/common/row_operations/row_matcher.cpp index 610df0dd5..089dc2e4a 100644 --- a/src/duckdb/src/common/row_operations/row_matcher.cpp +++ b/src/duckdb/src/common/row_operations/row_matcher.cpp @@ -6,6 +6,7 @@ #include "duckdb/common/exception.hpp" #include "duckdb/common/smaller_binary.hpp" #include "duckdb/common/types/row/tuple_data_collection.hpp" +#include "duckdb/common/vector_operations/string_comparison.hpp" namespace duckdb { @@ -70,9 +71,15 @@ static idx_t TemplatedMatchLoop(const TupleDataVectorFormat &lhs_format, Selecti } template -static idx_t TemplatedMatch(Vector &, const TupleDataVectorFormat &lhs_format, SelectionVector &sel, const idx_t count, - const TupleDataLayout &rhs_layout, Vector &rhs_row_locations, const idx_t col_idx, - const vector &, SelectionVector *no_match_sel, idx_t &no_match_count) { +static idx_t TemplatedMatch(Vector &lhs, const TupleDataVectorFormat &lhs_format, SelectionVector &sel, + const idx_t count, const TupleDataLayout &rhs_layout, Vector &rhs_row_locations, + const idx_t col_idx, const vector &child_functions, + SelectionVector *no_match_sel, idx_t &no_match_count) { + if constexpr (std::is_same_v && StringComparison::IsOrdering()) { + using WIDE_OP = StringOrderingOperator; + return TemplatedMatch(lhs, lhs_format, sel, count, rhs_layout, rhs_row_locations, + col_idx, child_functions, no_match_sel, no_match_count); + } #if DUCKDB_SMALLER_BINARY(row_matcher_validity) return TemplatedMatchLoop(lhs_format, sel, count, rhs_layout, rhs_row_locations, col_idx, no_match_sel, no_match_count); diff --git a/src/duckdb/src/common/sort/topn_heap.cpp b/src/duckdb/src/common/sort/topn_heap.cpp index 9b88229d5..305035c56 100644 --- a/src/duckdb/src/common/sort/topn_heap.cpp +++ b/src/duckdb/src/common/sort/topn_heap.cpp @@ -1,8 +1,146 @@ #include "duckdb/common/sorting/topn_heap.hpp" +#include "duckdb/common/vector_operations/vector_operations.hpp" +#include "duckdb/execution/expression_executor.hpp" #include "duckdb/storage/buffer_manager.hpp" namespace duckdb { +//===--------------------------------------------------------------------===// +// TopNBoundarySelector +//===--------------------------------------------------------------------===// +TopNBoundarySelector::TopNBoundarySelector(ClientContext &context, Allocator &allocator, + const vector &orders_p, + const vector> ¬_distinct_from_p) + : orders(orders_p), true_sel(STANDARD_VECTOR_SIZE), false_sel(STANDARD_VECTOR_SIZE), + new_remaining_sel(STANDARD_VECTOR_SIZE) { + D_ASSERT(not_distinct_from_p.size() == orders.size()); + vector key_types; + for (auto &order : orders) { + key_types.push_back(order.expression->GetReturnType()); + not_distinct_from.push_back( + make_uniq(context, *not_distinct_from_p[not_distinct_from.size()])); + modifiers.emplace_back(order.type, order.null_order); + } + compare_chunk.Initialize(allocator, key_types); + boundary_values.Initialize(allocator, key_types); + auto boundary_compare_types = key_types; + boundary_compare_types.insert(boundary_compare_types.end(), key_types.begin(), key_types.end()); + boundary_compare_chunk.InitializeEmpty(boundary_compare_types); +} + +void TopNBoundarySelector::Decode(const string &sort_key, DataChunk &target) const { + target.Reset(); + CreateSortKeyHelpers::DecodeSortKey(string_t(sort_key), target, 0, modifiers); + for (auto &col : target.data) { + col.SetVectorType(VectorType::CONSTANT_VECTOR); + } +} + +bool TopNBoundarySelector::Refresh(TopNBoundaryValue &global_boundary) { + // An older local boundary remains valid if refreshing it would block. + const auto boundary_updated = global_boundary.TryGetBoundaryValue(boundary_val); + if (boundary_val.empty()) { + // no boundary value (yet) + return false; + } + if (boundary_updated) { + // new boundary value - decode + Decode(boundary_val, boundary_values); + } + return true; +} + +//! Selects the rows whose left value sorts strictly before the right value in the given order +static idx_t SelectBefore(const BoundOrderByNode &order, Vector &left, Vector &right, SelectionVector &sel, idx_t count, + SelectionVector &true_sel, SelectionVector &false_sel) { + if (order.null_order == OrderByNullType::NULLS_LAST) { + if (order.type == OrderType::ASCENDING) { + return VectorOperations::DistinctLessThan(left, right, &sel, count, &true_sel, &false_sel); + } + return VectorOperations::DistinctGreaterThanNullsFirst(left, right, &sel, count, &true_sel, &false_sel); + } + D_ASSERT(order.null_order == OrderByNullType::NULLS_FIRST); + if (order.type == OrderType::ASCENDING) { + return VectorOperations::DistinctLessThanNullsFirst(left, right, &sel, count, &true_sel, &false_sel); + } + return VectorOperations::DistinctGreaterThan(left, right, &sel, count, &true_sel, &false_sel); +} + +idx_t TopNBoundarySelector::Select(DataChunk &keys, DataChunk &bound, optional_ptr sel, + idx_t count, TopNBoundaryTies ties, TopNBoundaryRowOrder row_order, + SelectionVector &result) { + const auto key_count = orders.size(); + const auto row_count = keys.size(); + bound.SetChildCardinality(row_count); + for (idx_t i = 0; i < key_count; i++) { + boundary_compare_chunk.data[i].Reference(keys.data[i]); + boundary_compare_chunk.data[key_count + i].Reference(bound.data[i]); + } + boundary_compare_chunk.CheckCardinality(row_count); + + idx_t final_count = 0; + // the number of runs of rows that were appended to the result: each run is in the order of the input + idx_t appended_runs = 0; + SelectionVector remaining_sel(nullptr); + if (sel) { + remaining_sel.Initialize(*sel); + } + idx_t remaining_count = count; + for (idx_t i = 0; i < key_count && remaining_count > 0; i++) { + auto &order = orders[i]; + if (remaining_sel.data()) { + compare_chunk.data[i].Slice(keys.data[i], remaining_sel, remaining_count); + } else { + compare_chunk.data[i].Reference(keys.data[i]); + } + const auto is_last = i + 1 == key_count; + if (is_last && ties == TopNBoundaryTies::INCLUDE) { + // before or equal to the boundary: the rows that the boundary does not sort before + const auto after_count = SelectBefore(order, bound.data[i], compare_chunk.data[i], remaining_sel, + remaining_count, false_sel, true_sel); + const auto pass_count = remaining_count - after_count; + if (pass_count > 0) { + memcpy(result.data() + final_count, true_sel.data(), pass_count * sizeof(sel_t)); + final_count += pass_count; + appended_runs++; + } + break; + } + const auto true_count = SelectBefore(order, compare_chunk.data[i], bound.data[i], remaining_sel, + remaining_count, true_sel, false_sel); + if (true_count > 0) { + memcpy(result.data() + final_count, true_sel.data(), true_count * sizeof(sel_t)); + final_count += true_count; + appended_runs++; + } + const auto false_count = remaining_count - true_count; + if (is_last || false_count == 0) { + break; + } + // the rows that are equal to the boundary on this key continue with the next key + remaining_count = not_distinct_from[i]->SelectExpression(boundary_compare_chunk, &new_remaining_sel, nullptr, + &false_sel, false_count); + remaining_sel.Initialize(new_remaining_sel); + } + if (row_order == TopNBoundaryRowOrder::INPUT_ORDER && appended_runs > 1) { + // the rows were selected key by key: restore the order of the input + if (!selected_rows) { + selected_rows = make_unsafe_uniq_array(STANDARD_VECTOR_SIZE); + } + memset(selected_rows.get(), 0, row_count * sizeof(bool)); + for (idx_t i = 0; i < final_count; i++) { + selected_rows[result.get_index(i)] = true; + } + idx_t result_idx = 0; + for (idx_t row_idx = 0; row_idx < row_count; row_idx++) { + result.set_index(result_idx, row_idx); + result_idx += selected_rows[row_idx]; + } + D_ASSERT(result_idx == final_count); + } + return final_count; +} + //===--------------------------------------------------------------------===// // TopOneFunc //===--------------------------------------------------------------------===// @@ -154,16 +292,13 @@ TopNHeap::TopNHeap(ClientContext &context, Allocator &allocator, const vector sort_types; for (auto &order : orders) { auto &expr = order.expression; sort_types.push_back(expr->GetReturnType()); executor.AddExpression(*expr); - not_distinct_from.push_back( - make_uniq(executor.GetContext(), *not_distinct_from_p[not_distinct_from.size()])); modifiers.emplace_back(order.type, order.null_order); } vector sort_keys_type {LogicalType::BLOB}; @@ -178,11 +313,7 @@ TopNHeap::TopNHeap(ClientContext &context, Allocator &allocator, const vector(context, allocator, orders, not_distinct_from_p); } } @@ -304,77 +435,17 @@ void TopNHeap::AddLargeHeap(DataChunk &input, const Vector &sort_keys_vec) { } bool TopNHeap::CheckBoundaryValues(DataChunk &sort_chunk, DataChunk &payload, TopNBoundaryValue &global_boundary) { - // An older local boundary remains valid if refreshing it would block. - const auto boundary_updated = global_boundary.TryGetBoundaryValue(boundary_val); - if (boundary_val.empty()) { + D_ASSERT(boundary_selector); + if (!boundary_selector->Refresh(global_boundary)) { // no boundary value (yet) - don't do anything return true; } - if (boundary_updated) { - // new boundary value - decode - boundary_values.Reset(); - CreateSortKeyHelpers::DecodeSortKey(string_t(boundary_val), boundary_values, 0, modifiers); - for (auto &col : boundary_values.data) { - col.SetVectorType(VectorType::CONSTANT_VECTOR); - } - } - boundary_values.SetChildCardinality(sort_chunk.size()); - for (idx_t i = 0; i < orders.size(); i++) { - boundary_compare_chunk.data[i].Reference(sort_chunk.data[i]); - boundary_compare_chunk.data[orders.size() + i].Reference(boundary_values.data[i]); - } - boundary_compare_chunk.CheckCardinality(sort_chunk.size()); - // we have boundary values - // from these boundary values, determine which values we should insert (if any) - idx_t final_count = 0; - - SelectionVector remaining_sel(nullptr); - idx_t remaining_count = sort_chunk.size(); - for (idx_t i = 0; i < orders.size() && remaining_count > 0; i++) { - if (remaining_sel.data()) { - compare_chunk.data[i].Slice(sort_chunk.data[i], remaining_sel, remaining_count); - } else { - compare_chunk.data[i].Reference(sort_chunk.data[i]); - } - bool is_last = i + 1 == orders.size(); - idx_t true_count; - if (orders[i].null_order == OrderByNullType::NULLS_LAST) { - if (orders[i].type == OrderType::ASCENDING) { - true_count = VectorOperations::DistinctLessThan(compare_chunk.data[i], boundary_values.data[i], - &remaining_sel, remaining_count, &true_sel, &false_sel); - } else { - true_count = VectorOperations::DistinctGreaterThanNullsFirst(compare_chunk.data[i], - boundary_values.data[i], &remaining_sel, - remaining_count, &true_sel, &false_sel); - } - } else { - D_ASSERT(orders[i].null_order == OrderByNullType::NULLS_FIRST); - if (orders[i].type == OrderType::ASCENDING) { - true_count = VectorOperations::DistinctLessThanNullsFirst(compare_chunk.data[i], - boundary_values.data[i], &remaining_sel, - remaining_count, &true_sel, &false_sel); - } else { - true_count = - VectorOperations::DistinctGreaterThan(compare_chunk.data[i], boundary_values.data[i], - &remaining_sel, remaining_count, &true_sel, &false_sel); - } - } - - if (true_count > 0) { - memcpy(final_sel.data() + final_count, true_sel.data(), true_count * sizeof(sel_t)); - final_count += true_count; - } - idx_t false_count = remaining_count - true_count; - if (!is_last && false_count > 0) { - // check what we should continue to check - remaining_count = not_distinct_from[i]->SelectExpression(boundary_compare_chunk, &new_remaining_sel, - nullptr, &false_sel, false_count); - remaining_sel.Initialize(new_remaining_sel); - } else { - break; - } - } + // from these boundary values, determine which values we should insert (if any): the rows strictly before the + // boundary (the heap holds the boundary row itself), in any order + const auto final_count = + boundary_selector->Select(sort_chunk, boundary_selector->BoundaryValues(), nullptr, sort_chunk.size(), + TopNBoundaryTies::EXCLUDE, TopNBoundaryRowOrder::ANY, final_sel); if (final_count == 0) { return false; } diff --git a/src/duckdb/src/common/types/column/column_data_collection.cpp b/src/duckdb/src/common/types/column/column_data_collection.cpp index 92cc89331..fcc9c5dd4 100644 --- a/src/duckdb/src/common/types/column/column_data_collection.cpp +++ b/src/duckdb/src/common/types/column/column_data_collection.cpp @@ -441,18 +441,21 @@ static void TemplatedColumnDataCopy(ColumnDataMetaData &meta_data, const Unified while (remaining > 0) { EnsureVectorDataAllocated(meta_data, current_index, OP::TypeSize()); auto ¤t_segment = segment.GetVectorData(current_index); - idx_t append_count = MinValue(STANDARD_VECTOR_SIZE - current_segment.count, remaining); + const auto capacity = ColumnDataCollectionSegment::GetVectorCapacity(current_segment); + D_ASSERT(current_segment.count <= capacity); + idx_t append_count = MinValue(capacity - current_segment.count, remaining); auto base_ptr = segment.allocator->GetDataPointer(append_state.current_chunk_state, current_segment.block_id, current_segment.offset); - auto validity_data = ColumnDataCollectionSegment::GetValidityPointerForWriting(base_ptr, OP::TypeSize()); + auto validity_data = + ColumnDataCollectionSegment::GetValidityPointerForWriting(base_ptr, OP::TypeSize(), capacity); - ValidityMask result_validity(validity_data, STANDARD_VECTOR_SIZE); + ValidityMask result_validity(validity_data, capacity); if (current_segment.count == 0) { // first time appending to this vector // all data here is still uninitialized // initialize the validity mask to set all to valid - result_validity.SetAllValid(STANDARD_VECTOR_SIZE); + result_validity.SetAllValid(capacity); } if (source_data.validity.CannotHaveNull()) { // Fast path: all valid @@ -743,9 +746,12 @@ void ColumnDataCopy(ColumnDataMetaData &meta_data, const UnifiedVector auto block_size = meta_data.segment.allocator->GetBufferManager().GetBlockSize(); while (remaining > 0) { EnsureVectorDataAllocated(meta_data, current_index, sizeof(string_t)); - // how many values fit in the current string vector - const auto vector_remaining = - MinValue(STANDARD_VECTOR_SIZE - segment.GetVectorData(current_index).count, remaining); + // how many values fit in the current string vector, which keeps the standard layout (16-bit swizzle offsets) + const idx_t current_count = segment.GetVectorData(current_index).count; + D_ASSERT(ColumnDataCollectionSegment::GetVectorCapacity(segment.GetVectorData(current_index)) == + STANDARD_VECTOR_SIZE); + D_ASSERT(current_count <= STANDARD_VECTOR_SIZE); + const auto vector_remaining = MinValue(STANDARD_VECTOR_SIZE - current_count, remaining); idx_t append_count = 0; idx_t heap_size = 0; @@ -819,7 +825,9 @@ void ColumnDataCopy(ColumnDataMetaData &meta_data, const UnifiedVector D_ASSERT(base_heap_ptr == segment.allocator->GetDataPointer(append_state.current_chunk_state, child_segment.block_id, child_segment.offset)); #endif - current_segment.swizzle_data.emplace_back(child_index, base_heap_ptr, current_segment.count, append_count); + current_segment.swizzle_data.emplace_back(child_index, base_heap_ptr, + UnsafeNumericCast(current_segment.count), + UnsafeNumericCast(append_count)); } current_segment.count += append_count; @@ -837,6 +845,60 @@ void ColumnDataCopy(ColumnDataMetaData &meta_data, const UnifiedVector } } +//! Block capacities are 32-bit +static constexpr idx_t MAXIMUM_LARGE_LIST_CHILD_SIZE = NumericLimits::Maximum(); + +//! Store a list child longer than a vector, appended into an empty child chain of a buffer-managed collection, as a +//! single LARGE_FLAT entry, so scans read it without copying. Returns false if the child must be appended as a chain of +//! vector-sized entries +static bool TryAppendLargeListChild(ColumnDataMetaData &meta_data, Vector &source, Vector &child_vector, + const ConsecutiveChildListInfo &info, idx_t offset, idx_t copy_count) { + auto &segment = meta_data.segment; + if (segment.allocator->GetType() == ColumnDataAllocatorType::IN_MEMORY_ALLOCATOR) { + // in-memory blocks round their capacity up to a power of two, a child-sized block could double its footprint + return false; + } + const auto length = info.child_list_info.length; + if (meta_data.GetVectorMetaData().child_index.IsValid() || length <= STANDARD_VECTOR_SIZE) { + return false; + } + auto &child_type = child_vector.GetType(); + const auto internal_type = child_type.InternalType(); + if (!TypeIsConstantSize(internal_type)) { + return false; + } + const auto type_size = GetTypeIdSize(internal_type); + if (ColumnDataCollectionSegment::GetDataSize(type_size, length) + ValidityMask::ValidityMaskSize(length) > + MAXIMUM_LARGE_LIST_CHILD_SIZE) { + return false; + } + + auto &chunk_state = meta_data.state.current_chunk_state; + auto child_index = segment.AllocateLargeVector(type_size, length, meta_data.chunk_data, &chunk_state); + meta_data.GetVectorMetaData().child_index = segment.AddChildIndex(child_index); + auto &child_vdata = segment.GetVectorData(child_index); + auto base_ptr = segment.allocator->GetDataPointer(chunk_state, child_vdata.block_id, child_vdata.offset); + + Vector target(child_type, base_ptr, length); + if (info.needs_slicing) { + SelectionVector sel(length); + ListVector::GetConsecutiveChildSelVector(source, sel, offset, copy_count); + VectorOperations::Copy(child_vector, target, sel, length, 0, 0, length); + } else { + const auto child_offset = info.child_list_info.offset; + VectorOperations::Copy(child_vector, target, *FlatVector::IncrementalSelectionVector(), child_offset + length, + child_offset, 0, length); + } + auto validity_data = ColumnDataCollectionSegment::GetValidityPointerForWriting(base_ptr, type_size, length); + auto &target_validity = FlatVector::Validity(target); + if (target_validity.CanHaveNull()) { + memcpy(validity_data, target_validity.GetData(), ValidityMask::ValidityMaskSize(length)); + } else { + ValidityMask(validity_data, length).SetAllValid(length); + } + return true; +} + template <> void ColumnDataCopy(ColumnDataMetaData &meta_data, const UnifiedVectorFormat &source_data, Vector &source, idx_t offset, idx_t copy_count) { @@ -844,45 +906,47 @@ void ColumnDataCopy(ColumnDataMetaData &meta_data, const UnifiedVe auto &child_vector = ListVector::GetChildMutable(source); auto &child_type = child_vector.GetType(); - - if (!meta_data.GetVectorMetaData().child_index.IsValid()) { - auto child_index = segment.AllocateVector(child_type, meta_data.chunk_data, meta_data.state); - meta_data.GetVectorMetaData().child_index = meta_data.segment.AddChildIndex(child_index); - } - - auto &child_function = meta_data.copy_function.child_functions[0]; - auto child_index = segment.GetChildIndex(meta_data.GetVectorMetaData().child_index); + auto info = ListVector::GetConsecutiveChildListInfo(source, offset, copy_count); // figure out the current list size by traversing the set of child entries idx_t current_list_size = 0; - auto current_child_index = child_index; - while (current_child_index.IsValid()) { - auto &child_vdata = segment.GetVectorData(current_child_index); - current_list_size += child_vdata.count; - current_child_index = child_vdata.next_data; + if (meta_data.GetVectorMetaData().child_index.IsValid()) { + auto current_child_index = segment.GetChildIndex(meta_data.GetVectorMetaData().child_index); + while (current_child_index.IsValid()) { + auto &child_vdata = segment.GetVectorData(current_child_index); + current_list_size += child_vdata.count; + current_child_index = child_vdata.next_data; + } } - // set the child vector - UnifiedVectorFormat child_vector_data; - ColumnDataMetaData child_meta_data(child_function, meta_data, child_index); - auto info = ListVector::GetConsecutiveChildListInfo(source, offset, copy_count); + if (!TryAppendLargeListChild(meta_data, source, child_vector, info, offset, copy_count)) { + if (!meta_data.GetVectorMetaData().child_index.IsValid()) { + auto child_index = segment.AllocateVector(child_type, meta_data.chunk_data, meta_data.state); + meta_data.GetVectorMetaData().child_index = meta_data.segment.AddChildIndex(child_index); + } + auto &child_function = meta_data.copy_function.child_functions[0]; + auto child_index = segment.GetChildIndex(meta_data.GetVectorMetaData().child_index); - if (info.needs_slicing) { - SelectionVector sel(info.child_list_info.length); - ListVector::GetConsecutiveChildSelVector(source, sel, offset, copy_count); + // set the child vector + UnifiedVectorFormat child_vector_data; + ColumnDataMetaData child_meta_data(child_function, meta_data, child_index); + if (info.needs_slicing) { + SelectionVector sel(info.child_list_info.length); + ListVector::GetConsecutiveChildSelVector(source, sel, offset, copy_count); - auto sliced_child_vector = Vector(child_vector, sel, info.child_list_info.length); - sliced_child_vector.Flatten(); - info.child_list_info.offset = 0; + auto sliced_child_vector = Vector(child_vector, sel, info.child_list_info.length); + sliced_child_vector.Flatten(); + info.child_list_info.offset = 0; - sliced_child_vector.ToUnifiedFormat(child_vector_data); - child_function.function(child_meta_data, child_vector_data, sliced_child_vector, info.child_list_info.offset, - info.child_list_info.length); + sliced_child_vector.ToUnifiedFormat(child_vector_data); + child_function.function(child_meta_data, child_vector_data, sliced_child_vector, + info.child_list_info.offset, info.child_list_info.length); - } else { - child_vector.ToUnifiedFormat(child_vector_data); - child_function.function(child_meta_data, child_vector_data, child_vector, info.child_list_info.offset, - info.child_list_info.length); + } else { + child_vector.ToUnifiedFormat(child_vector_data); + child_function.function(child_meta_data, child_vector_data, child_vector, info.child_list_info.offset, + info.child_list_info.length); + } } // now copy the list entries @@ -1092,7 +1156,7 @@ static void AppendConstantEntry(ColumnDataMetaData &meta_data, const UnifiedVect auto &vdata = meta_data.GetVectorMetaData(); vdata.constant = constant; vdata.representation = ColumnDataRepresentation::CONSTANT; - vdata.count = UnsafeNumericCast(copy_count); + vdata.count = UnsafeNumericCast(copy_count); // account the metadata bytes that hold the value segment.constant_metadata_size += sizeof(ColumnDataConstantValue); segment.total_allocated += sizeof(ColumnDataConstantValue); @@ -1125,7 +1189,7 @@ static bool TryExtendConstantEntry(ColumnDataMetaData &meta_data, const UnifiedV } } } - vdata.count += UnsafeNumericCast(copy_count); + vdata.count += UnsafeNumericCast(copy_count); return true; } @@ -1285,7 +1349,7 @@ static bool TryAppendDictionaryEntry(ColumnDataMetaData &meta_data, const Unifie vdata.representation = ColumnDataRepresentation::DICTIONARY; vdata.dictionary_slot = slot; WriteDictionaryCodes(meta_data, source_data, offset, copy_count, 0); - meta_data.GetVectorMetaData().count = UnsafeNumericCast(copy_count); + meta_data.GetVectorMetaData().count = UnsafeNumericCast(copy_count); return true; } @@ -1306,7 +1370,7 @@ static bool TryExtendDictionaryEntry(ColumnDataMetaData &meta_data, const Unifie } D_ASSERT(vdata.count + copy_count <= STANDARD_VECTOR_SIZE); WriteDictionaryCodes(meta_data, source_data, offset, copy_count, vdata.count); - vdata.count += UnsafeNumericCast(copy_count); + vdata.count += UnsafeNumericCast(copy_count); return true; } diff --git a/src/duckdb/src/common/types/column/column_data_collection_segment.cpp b/src/duckdb/src/common/types/column/column_data_collection_segment.cpp index 148d3766e..019e44195 100644 --- a/src/duckdb/src/common/types/column/column_data_collection_segment.cpp +++ b/src/duckdb/src/common/types/column/column_data_collection_segment.cpp @@ -31,16 +31,18 @@ void ColumnDataCollectionSegment::Reset() { heap->GetAllocator().Reset(); } -idx_t ColumnDataCollectionSegment::GetDataSize(idx_t type_size) { - return AlignValue(type_size * STANDARD_VECTOR_SIZE); +idx_t ColumnDataCollectionSegment::GetDataSize(idx_t type_size, idx_t capacity) { + return AlignValue(type_size * capacity); } -validity_t *ColumnDataCollectionSegment::GetValidityPointerForWriting(data_ptr_t base_ptr, idx_t type_size) { - return reinterpret_cast(base_ptr + GetDataSize(type_size)); +validity_t *ColumnDataCollectionSegment::GetValidityPointerForWriting(data_ptr_t base_ptr, idx_t type_size, + idx_t capacity) { + return reinterpret_cast(base_ptr + GetDataSize(type_size, capacity)); } -validity_t *ColumnDataCollectionSegment::GetValidityPointer(data_ptr_t base_ptr, idx_t type_size, idx_t count) { - auto validity_mask = reinterpret_cast(base_ptr + GetDataSize(type_size)); +validity_t *ColumnDataCollectionSegment::GetValidityPointer(data_ptr_t base_ptr, idx_t type_size, idx_t count, + idx_t capacity) { + auto validity_mask = reinterpret_cast(base_ptr + GetDataSize(type_size, capacity)); // Optimized check to see if all entries are valid for (idx_t i = 0; i < (count / ValidityMask::BITS_PER_VALUE); i++) { @@ -96,6 +98,30 @@ VectorDataIndex ColumnDataCollectionSegment::AllocateVectorInternal(const Logica return result; } +VectorDataIndex ColumnDataCollectionSegment::AllocateLargeVector(idx_t type_size, idx_t count, + ChunkMetaData &chunk_meta, + ChunkManagementState *chunk_state) { + D_ASSERT(count > STANDARD_VECTOR_SIZE); + VectorMetaData meta_data; + // the capacity equals the count, so appends continue on a new entry + meta_data.count = NumericCast(count); + meta_data.representation = ColumnDataRepresentation::LARGE_FLAT; + + VectorDataIndex index(vector_data.size()); + vector_data.push_back(std::move(meta_data)); + AllocateVectorStorage(index, GetDataSize(type_size, count) + ValidityMask::ValidityMaskSize(count), chunk_meta, + chunk_state); + return index; +} + +idx_t ColumnDataCollectionSegment::GetVectorCapacity(const VectorMetaData &vdata) { + if (vdata.representation == ColumnDataRepresentation::LARGE_FLAT) { + // allocated for exactly its rows + return vdata.count; + } + return STANDARD_VECTOR_SIZE; +} + VectorDataIndex ColumnDataCollectionSegment::AllocateVector(const LogicalType &type, ChunkMetaData &chunk_meta, ChunkManagementState *chunk_state, VectorDataIndex prev_index, bool defer_allocation) { @@ -321,14 +347,15 @@ idx_t ColumnDataCollectionSegment::ReadVectorInternal(ChunkManagementState &stat auto &vdata = GetVectorData(vector_index); D_ASSERT(vdata.is_allocated); - auto base_ptr = allocator->GetDataPointer(state, vdata.block_id, vdata.offset); - auto validity_data = GetValidityPointer(base_ptr, type_size, vdata.count); if (!vdata.next_data.IsValid() && state.properties != ColumnDataScanProperties::DISALLOW_ZERO_COPY) { // no next data, we can do a zero-copy read of this vector + const auto capacity = GetVectorCapacity(vdata); + auto base_ptr = allocator->GetDataPointer(state, vdata.block_id, vdata.offset); + auto validity_data = GetValidityPointer(base_ptr, type_size, vdata.count, capacity); if (TypeHasData(result.GetType())) { FlatVector::SetData(result, base_ptr, count_t(vdata.count)); } - FlatVector::ValidityMutable(result).Initialize(validity_data, STANDARD_VECTOR_SIZE); + FlatVector::ValidityMutable(result).Initialize(validity_data, capacity); FlatVector::SetSize(result, count_t(vdata.count)); return vdata.count; } @@ -352,12 +379,13 @@ idx_t ColumnDataCollectionSegment::ReadVectorInternal(ChunkManagementState &stat idx_t current_offset = 0; while (next_index.IsValid()) { auto ¤t_vdata = GetVectorData(next_index); - base_ptr = allocator->GetDataPointer(state, current_vdata.block_id, current_vdata.offset); - validity_data = GetValidityPointer(base_ptr, type_size, current_vdata.count); + const auto current_capacity = GetVectorCapacity(current_vdata); + auto base_ptr = allocator->GetDataPointer(state, current_vdata.block_id, current_vdata.offset); + auto validity_data = GetValidityPointer(base_ptr, type_size, current_vdata.count, current_capacity); if (type_size > 0) { memcpy(target_data + current_offset * type_size, base_ptr, current_vdata.count * type_size); } - ValidityMask current_validity(validity_data, STANDARD_VECTOR_SIZE); + ValidityMask current_validity(validity_data, current_capacity); target_validity.SliceInPlace(current_validity, current_offset, 0, current_vdata.count); current_offset += current_vdata.count; next_index = current_vdata.next_data; @@ -375,7 +403,8 @@ idx_t ColumnDataCollectionSegment::ReadVector(ChunkManagementState &state, Vecto FlatVector::SetSize(result, 0); return 0; } - if (vdata.representation != ColumnDataRepresentation::FLAT) { + if (vdata.representation == ColumnDataRepresentation::CONSTANT || + vdata.representation == ColumnDataRepresentation::DICTIONARY) { return ReadCompactVector(state, vector_index, result); } auto vcount = ReadVectorInternal(state, vector_index, result); diff --git a/src/duckdb/src/common/types/time.cpp b/src/duckdb/src/common/types/time.cpp index 26732d3fd..82a4cd9bc 100644 --- a/src/duckdb/src/common/types/time.cpp +++ b/src/duckdb/src/common/types/time.cpp @@ -132,6 +132,9 @@ bool Time::TryConvertInternal(const char *buf, idx_t len, idx_t &pos, dtime_t &r } micros = 0; + if (nanos) { + *nanos = 0; + } if (pos < len && buf[pos] == '.') { pos++; // we expect some microseconds @@ -140,11 +143,21 @@ bool Time::TryConvertInternal(const char *buf, idx_t len, idx_t &pos, dtime_t &r // do we expect nanoseconds? mult *= Interval::NANOS_PER_MICRO; } + int32_t round_digit = -1; + bool round_nonzero = false; for (; pos < len && StringUtil::CharacterIsDigit(buf[pos]); pos++, mult /= 10) { if (mult > 0) { micros += (buf[pos] - '0') * mult; + } else if (round_digit < 0) { + round_digit = buf[pos] - '0'; + } else if (buf[pos] != '0') { + round_nonzero = true; } } + // round half to even, so that a tie does not always round up + if (round_digit >= 5 && (round_digit > 5 || round_nonzero || micros % 2 != 0)) { + micros++; + } if (nanos) { *nanos = UnsafeNumericCast(micros % Interval::NANOS_PER_MICRO); micros /= Interval::NANOS_PER_MICRO; diff --git a/src/duckdb/src/common/types/variant/parquet_variant_encoding.cpp b/src/duckdb/src/common/types/variant/parquet_variant_encoding.cpp index 6fc4f4e4f..70bad44db 100644 --- a/src/duckdb/src/common/types/variant/parquet_variant_encoding.cpp +++ b/src/duckdb/src/common/types/variant/parquet_variant_encoding.cpp @@ -130,49 +130,30 @@ static void CreateMetadata(UnifiedVariantVectorData &variant, Vector &metadata, namespace { -static unordered_set GetVariantType(const LogicalType &type) { - if (type.id() == LogicalTypeId::ANY) { - return {}; - } +static unordered_set GetVariantType(const LogicalType &type) { switch (type.id()) { + case LogicalTypeId::ANY: + return {}; case LogicalTypeId::STRUCT: - return {VariantLogicalType::OBJECT}; case LogicalTypeId::LIST: - return {VariantLogicalType::ARRAY}; case LogicalTypeId::BOOLEAN: - return {VariantLogicalType::BOOL_TRUE, VariantLogicalType::BOOL_FALSE}; case LogicalTypeId::TINYINT: - return {VariantLogicalType::INT8}; case LogicalTypeId::SMALLINT: - return {VariantLogicalType::INT16}; case LogicalTypeId::INTEGER: - return {VariantLogicalType::INT32}; case LogicalTypeId::BIGINT: - return {VariantLogicalType::INT64}; case LogicalTypeId::FLOAT: - return {VariantLogicalType::FLOAT}; case LogicalTypeId::DOUBLE: - return {VariantLogicalType::DOUBLE}; case LogicalTypeId::DECIMAL: - return {VariantLogicalType::DECIMAL}; case LogicalTypeId::DATE: - return {VariantLogicalType::DATE}; case LogicalTypeId::TIME: - return {VariantLogicalType::TIME_MICROS}; case LogicalTypeId::TIMESTAMP_TZ: - return {VariantLogicalType::TIMESTAMP_MICROS_TZ}; case LogicalTypeId::TIMESTAMP_TZ_NS: - return {VariantLogicalType::TIMESTAMP_NANOS_TZ}; case LogicalTypeId::TIMESTAMP: - return {VariantLogicalType::TIMESTAMP_MICROS}; case LogicalTypeId::TIMESTAMP_NS: - return {VariantLogicalType::TIMESTAMP_NANOS}; case LogicalTypeId::BLOB: - return {VariantLogicalType::BLOB}; case LogicalTypeId::VARCHAR: - return {VariantLogicalType::VARCHAR}; case LogicalTypeId::UUID: - return {VariantLogicalType::UUID}; + return {type.id()}; default: throw BinderException("Type '%s' can't be translated to a VARIANT type", type.ToString()); } @@ -185,12 +166,12 @@ struct ParquetVariantShreddingState : public VariantShreddingState { } public: - const unordered_set &GetVariantTypes() override { + const unordered_set &GetVariantTypes() override { return variant_types; } private: - unordered_set variant_types; + unordered_set variant_types; }; struct ParquetVariantShredding : public VariantShredding { diff --git a/src/duckdb/src/common/types/variant/parquet_variant_iterator.cpp b/src/duckdb/src/common/types/variant/parquet_variant_iterator.cpp index 1221aab06..32e8c5990 100644 --- a/src/duckdb/src/common/types/variant/parquet_variant_iterator.cpp +++ b/src/duckdb/src/common/types/variant/parquet_variant_iterator.cpp @@ -475,7 +475,24 @@ ParquetVariantNode ParquetVariantIterator::BinaryRoot() const { //===--------------------------------------------------------------------===// // ParquetVariantNode //===--------------------------------------------------------------------===// -VariantLogicalType ParquetVariantNode::GetTypeId() const { +LogicalTypeId ParquetVariantNode::GetTypeId() const { + return VariantTypeToLogicalTypeId(GetVariantType()); +} + +LogicalType ParquetVariantNode::GetType() const { + auto type_id = GetTypeId(); + if (type_id == LogicalTypeId::DECIMAL) { + auto properties = GetDecimalProperties(); + return LogicalType::DECIMAL(properties.width, properties.scale); + } + return VariantDefaultType(type_id); +} + +bool ParquetVariantNode::GetBool() const { + return GetVariantType() == VariantLogicalType::BOOL_TRUE; +} + +VariantLogicalType ParquetVariantNode::GetVariantType() const { switch (kind) { case Kind::NULL_VALUE: return VariantLogicalType::VARIANT_NULL; diff --git a/src/duckdb/src/common/types/variant/variant.cpp b/src/duckdb/src/common/types/variant/variant.cpp index ca8acff79..366e24b2f 100644 --- a/src/duckdb/src/common/types/variant/variant.cpp +++ b/src/duckdb/src/common/types/variant/variant.cpp @@ -2,6 +2,8 @@ #include "duckdb/common/vector/variant_vector.hpp" #include "duckdb/common/types/variant.hpp" #include "duckdb/common/types/vector.hpp" +#include "duckdb/common/enum_util.hpp" +#include "duckdb/common/exception.hpp" namespace duckdb { @@ -18,6 +20,219 @@ VariantVectorData::VariantVectorData(Vector &variant) keys_data = FlatVector::GetDataMutable(keys); } +LogicalTypeId VariantTypeToLogicalTypeId(VariantLogicalType type) { + switch (type) { + case VariantLogicalType::BOOL_TRUE: + case VariantLogicalType::BOOL_FALSE: + return LogicalTypeId::BOOLEAN; + case VariantLogicalType::VARIANT_NULL: + return LogicalTypeId::SQLNULL; + case VariantLogicalType::INT8: + return LogicalTypeId::TINYINT; + case VariantLogicalType::INT16: + return LogicalTypeId::SMALLINT; + case VariantLogicalType::INT32: + return LogicalTypeId::INTEGER; + case VariantLogicalType::INT64: + return LogicalTypeId::BIGINT; + case VariantLogicalType::INT128: + return LogicalTypeId::HUGEINT; + case VariantLogicalType::UINT8: + return LogicalTypeId::UTINYINT; + case VariantLogicalType::UINT16: + return LogicalTypeId::USMALLINT; + case VariantLogicalType::UINT32: + return LogicalTypeId::UINTEGER; + case VariantLogicalType::UINT64: + return LogicalTypeId::UBIGINT; + case VariantLogicalType::UINT128: + return LogicalTypeId::UHUGEINT; + case VariantLogicalType::FLOAT: + return LogicalTypeId::FLOAT; + case VariantLogicalType::DOUBLE: + return LogicalTypeId::DOUBLE; + case VariantLogicalType::DECIMAL: + return LogicalTypeId::DECIMAL; + case VariantLogicalType::VARCHAR: + return LogicalTypeId::VARCHAR; + case VariantLogicalType::BLOB: + return LogicalTypeId::BLOB; + case VariantLogicalType::UUID: + return LogicalTypeId::UUID; + case VariantLogicalType::DATE: + return LogicalTypeId::DATE; + case VariantLogicalType::TIME_MICROS: + return LogicalTypeId::TIME; + case VariantLogicalType::TIME_NANOS: + return LogicalTypeId::TIME_NS; + case VariantLogicalType::TIMESTAMP_SEC: + return LogicalTypeId::TIMESTAMP_SEC; + case VariantLogicalType::TIMESTAMP_MILIS: + return LogicalTypeId::TIMESTAMP_MS; + case VariantLogicalType::TIMESTAMP_MICROS: + return LogicalTypeId::TIMESTAMP; + case VariantLogicalType::TIMESTAMP_NANOS: + return LogicalTypeId::TIMESTAMP_NS; + case VariantLogicalType::TIME_MICROS_TZ: + return LogicalTypeId::TIME_TZ; + case VariantLogicalType::TIMESTAMP_MICROS_TZ: + return LogicalTypeId::TIMESTAMP_TZ; + case VariantLogicalType::TIMESTAMP_NANOS_TZ: + return LogicalTypeId::TIMESTAMP_TZ_NS; + case VariantLogicalType::INTERVAL: + return LogicalTypeId::INTERVAL; + case VariantLogicalType::OBJECT: + return LogicalTypeId::STRUCT; + case VariantLogicalType::ARRAY: + return LogicalTypeId::LIST; + case VariantLogicalType::BIGNUM: + return LogicalTypeId::BIGNUM; + case VariantLogicalType::BITSTRING: + return LogicalTypeId::BIT; + case VariantLogicalType::GEOMETRY: + return LogicalTypeId::GEOMETRY; + case VariantLogicalType::GEOGRAPHY: + return LogicalTypeId::GEOGRAPHY; + default: + throw InternalException("Unrecognized VariantLogicalType %d", static_cast(type)); + } +} + +bool TryVariantTypeFromLogicalTypeId(LogicalTypeId id, VariantLogicalType &result, bool bool_value) { + switch (id) { + case LogicalTypeId::BOOLEAN: + result = bool_value ? VariantLogicalType::BOOL_TRUE : VariantLogicalType::BOOL_FALSE; + return true; + case LogicalTypeId::SQLNULL: + result = VariantLogicalType::VARIANT_NULL; + return true; + case LogicalTypeId::TINYINT: + result = VariantLogicalType::INT8; + return true; + case LogicalTypeId::SMALLINT: + result = VariantLogicalType::INT16; + return true; + case LogicalTypeId::INTEGER: + result = VariantLogicalType::INT32; + return true; + case LogicalTypeId::BIGINT: + result = VariantLogicalType::INT64; + return true; + case LogicalTypeId::HUGEINT: + result = VariantLogicalType::INT128; + return true; + case LogicalTypeId::UTINYINT: + result = VariantLogicalType::UINT8; + return true; + case LogicalTypeId::USMALLINT: + result = VariantLogicalType::UINT16; + return true; + case LogicalTypeId::UINTEGER: + result = VariantLogicalType::UINT32; + return true; + case LogicalTypeId::UBIGINT: + result = VariantLogicalType::UINT64; + return true; + case LogicalTypeId::UHUGEINT: + result = VariantLogicalType::UINT128; + return true; + case LogicalTypeId::FLOAT: + result = VariantLogicalType::FLOAT; + return true; + case LogicalTypeId::DOUBLE: + result = VariantLogicalType::DOUBLE; + return true; + case LogicalTypeId::DECIMAL: + result = VariantLogicalType::DECIMAL; + return true; + case LogicalTypeId::VARCHAR: + result = VariantLogicalType::VARCHAR; + return true; + case LogicalTypeId::BLOB: + result = VariantLogicalType::BLOB; + return true; + case LogicalTypeId::UUID: + result = VariantLogicalType::UUID; + return true; + case LogicalTypeId::DATE: + result = VariantLogicalType::DATE; + return true; + case LogicalTypeId::TIME: + result = VariantLogicalType::TIME_MICROS; + return true; + case LogicalTypeId::TIME_NS: + result = VariantLogicalType::TIME_NANOS; + return true; + case LogicalTypeId::TIMESTAMP_SEC: + result = VariantLogicalType::TIMESTAMP_SEC; + return true; + case LogicalTypeId::TIMESTAMP_MS: + result = VariantLogicalType::TIMESTAMP_MILIS; + return true; + case LogicalTypeId::TIMESTAMP: + result = VariantLogicalType::TIMESTAMP_MICROS; + return true; + case LogicalTypeId::TIMESTAMP_NS: + result = VariantLogicalType::TIMESTAMP_NANOS; + return true; + case LogicalTypeId::TIME_TZ: + result = VariantLogicalType::TIME_MICROS_TZ; + return true; + case LogicalTypeId::TIMESTAMP_TZ: + result = VariantLogicalType::TIMESTAMP_MICROS_TZ; + return true; + case LogicalTypeId::TIMESTAMP_TZ_NS: + result = VariantLogicalType::TIMESTAMP_NANOS_TZ; + return true; + case LogicalTypeId::INTERVAL: + result = VariantLogicalType::INTERVAL; + return true; + case LogicalTypeId::STRUCT: + result = VariantLogicalType::OBJECT; + return true; + case LogicalTypeId::LIST: + result = VariantLogicalType::ARRAY; + return true; + case LogicalTypeId::BIGNUM: + result = VariantLogicalType::BIGNUM; + return true; + case LogicalTypeId::BIT: + result = VariantLogicalType::BITSTRING; + return true; + case LogicalTypeId::GEOMETRY: + result = VariantLogicalType::GEOMETRY; + return true; + case LogicalTypeId::GEOGRAPHY: + result = VariantLogicalType::GEOGRAPHY; + return true; + default: + return false; + } +} + +LogicalType VariantDefaultType(LogicalTypeId id) { + switch (id) { + case LogicalTypeId::STRUCT: + return LogicalType::STRUCT(child_list_t()); + case LogicalTypeId::LIST: + return LogicalType::LIST(LogicalType::VARIANT()); + case LogicalTypeId::GEOMETRY: + return LogicalType::GEOMETRY(); + case LogicalTypeId::GEOGRAPHY: + return LogicalType::GEOGRAPHY(); + default: + return LogicalType(id); + } +} + +VariantLogicalType VariantTypeFromLogicalTypeId(LogicalTypeId id, bool bool_value) { + VariantLogicalType result; + if (!TryVariantTypeFromLogicalTypeId(id, result, bool_value)) { + throw InternalException("LogicalTypeId %s cannot be stored in a VARIANT", EnumUtil::ToString(id)); + } + return result; +} + UnifiedVariantVectorData::UnifiedVariantVectorData(const RecursiveUnifiedVectorFormat &variant) : variant(variant), keys(UnifiedVariantVector::GetKeys(variant)), keys_entry(UnifiedVariantVector::GetKeysEntry(variant)), children(UnifiedVariantVector::GetChildren(variant)), diff --git a/src/duckdb/src/common/types/variant/variant_comparison.cpp b/src/duckdb/src/common/types/variant/variant_comparison.cpp index 5b7330bd6..5ed0d24d1 100644 --- a/src/duckdb/src/common/types/variant/variant_comparison.cpp +++ b/src/duckdb/src/common/types/variant/variant_comparison.cpp @@ -75,86 +75,85 @@ VariantNumberKey IntegerNumberKey(T value) { } } // namespace -VariantComparisonType GetVariantComparisonType(VariantLogicalType type) { +VariantComparisonType GetVariantComparisonType(LogicalTypeId type) { switch (type) { - case VariantLogicalType::VARIANT_NULL: + case LogicalTypeId::SQLNULL: return VariantComparisonType::NULL_VALUE; - case VariantLogicalType::BOOL_TRUE: - case VariantLogicalType::BOOL_FALSE: + case LogicalTypeId::BOOLEAN: return VariantComparisonType::BOOLEAN; // all integers, decimals and bignums fold into a single NUMBER rank (compared by numeric value) - case VariantLogicalType::INT8: - case VariantLogicalType::INT16: - case VariantLogicalType::INT32: - case VariantLogicalType::INT64: - case VariantLogicalType::INT128: - case VariantLogicalType::UINT8: - case VariantLogicalType::UINT16: - case VariantLogicalType::UINT32: - case VariantLogicalType::UINT64: - case VariantLogicalType::UINT128: - case VariantLogicalType::DECIMAL: - case VariantLogicalType::BIGNUM: + case LogicalTypeId::TINYINT: + case LogicalTypeId::SMALLINT: + case LogicalTypeId::INTEGER: + case LogicalTypeId::BIGINT: + case LogicalTypeId::HUGEINT: + case LogicalTypeId::UTINYINT: + case LogicalTypeId::USMALLINT: + case LogicalTypeId::UINTEGER: + case LogicalTypeId::UBIGINT: + case LogicalTypeId::UHUGEINT: + case LogicalTypeId::DECIMAL: + case LogicalTypeId::BIGNUM: return VariantComparisonType::NUMBER; // FLOAT and DOUBLE fold into a single REAL rank - case VariantLogicalType::FLOAT: - case VariantLogicalType::DOUBLE: + case LogicalTypeId::FLOAT: + case LogicalTypeId::DOUBLE: return VariantComparisonType::REAL; - case VariantLogicalType::VARCHAR: + case LogicalTypeId::VARCHAR: return VariantComparisonType::VARCHAR; - case VariantLogicalType::BLOB: + case LogicalTypeId::BLOB: return VariantComparisonType::BLOB; - case VariantLogicalType::UUID: + case LogicalTypeId::UUID: return VariantComparisonType::UUID; // DATE folds into the TIMESTAMP rank (a date compares as midnight of that day), together with all // non-tz TIMESTAMP precisions (SEC / MILIS / MICROS / NANOS) - case VariantLogicalType::DATE: - case VariantLogicalType::TIMESTAMP_SEC: - case VariantLogicalType::TIMESTAMP_MILIS: - case VariantLogicalType::TIMESTAMP_MICROS: - case VariantLogicalType::TIMESTAMP_NANOS: + case LogicalTypeId::DATE: + case LogicalTypeId::TIMESTAMP_SEC: + case LogicalTypeId::TIMESTAMP_MS: + case LogicalTypeId::TIMESTAMP: + case LogicalTypeId::TIMESTAMP_NS: return VariantComparisonType::TIMESTAMP; // TIMESTAMP WITH TIME ZONE precisions fold into a single TIMESTAMP_TZ rank - case VariantLogicalType::TIMESTAMP_MICROS_TZ: - case VariantLogicalType::TIMESTAMP_NANOS_TZ: + case LogicalTypeId::TIMESTAMP_TZ: + case LogicalTypeId::TIMESTAMP_TZ_NS: return VariantComparisonType::TIMESTAMP_TZ; // TIME precisions fold into a single TIME rank - case VariantLogicalType::TIME_MICROS: - case VariantLogicalType::TIME_NANOS: + case LogicalTypeId::TIME: + case LogicalTypeId::TIME_NS: return VariantComparisonType::TIME; - case VariantLogicalType::TIME_MICROS_TZ: + case LogicalTypeId::TIME_TZ: return VariantComparisonType::TIME_TZ; - case VariantLogicalType::INTERVAL: + case LogicalTypeId::INTERVAL: return VariantComparisonType::INTERVAL; - case VariantLogicalType::BITSTRING: + case LogicalTypeId::BIT: return VariantComparisonType::BITSTRING; - case VariantLogicalType::GEOMETRY: + case LogicalTypeId::GEOMETRY: return VariantComparisonType::GEOMETRY; - case VariantLogicalType::GEOGRAPHY: + case LogicalTypeId::GEOGRAPHY: return VariantComparisonType::GEOGRAPHY; - case VariantLogicalType::ARRAY: + case LogicalTypeId::LIST: return VariantComparisonType::ARRAY; - case VariantLogicalType::OBJECT: + case LogicalTypeId::STRUCT: return VariantComparisonType::OBJECT; default: throw NotImplementedException("Variant type %s is not supported", EnumUtil::ToString(type)); } } -double VariantGetRealValue(VariantLogicalType type_id, const VariantNode &node) { +double VariantGetRealValue(LogicalTypeId type_id, const VariantNode &node) { switch (type_id) { - case VariantLogicalType::FLOAT: + case LogicalTypeId::FLOAT: // fold FLOAT into the REAL rank by widening to double (lossless) return static_cast(node.GetData()); - case VariantLogicalType::DOUBLE: + case LogicalTypeId::DOUBLE: return node.GetData(); default: throw InternalException("VariantGetRealValue called on non-REAL type"); } } -VariantNumberKey VariantGetNumberKey(VariantLogicalType type_id, const VariantNode &node) { +VariantNumberKey VariantGetNumberKey(LogicalTypeId type_id, const VariantNode &node) { switch (type_id) { - case VariantLogicalType::DECIMAL: { + case LogicalTypeId::DECIMAL: { const auto decimal_data = node.GetDecimal(); hugeint_t unscaled; switch (decimal_data.GetPhysicalType()) { @@ -183,7 +182,7 @@ VariantNumberKey VariantGetNumberKey(VariantLogicalType type_id, const VariantNo const auto magnitude = HugeintMagnitude(unscaled, negative); return BuildNumberKey(negative, magnitude, decimal_data.scale); } - case VariantLogicalType::BIGNUM: { + case LogicalTypeId::BIGNUM: { const auto bignum_blob = node.GetString(); const auto decimal_string = Bignum::BignumToVarchar(bignum_t(bignum_blob)); const bool negative = !decimal_string.empty() && decimal_string[0] == '-'; @@ -191,67 +190,67 @@ VariantNumberKey VariantGetNumberKey(VariantLogicalType type_id, const VariantNo return BuildNumberKey(negative, decimal_string.data() + offset, decimal_string.size() - offset, 0); } // integer types - use the native width for the magnitude, only widening to 128-bit when necessary - case VariantLogicalType::INT8: + case LogicalTypeId::TINYINT: return IntegerNumberKey(Load(node.GetDataPointer())); - case VariantLogicalType::INT16: + case LogicalTypeId::SMALLINT: return IntegerNumberKey(Load(node.GetDataPointer())); - case VariantLogicalType::INT32: + case LogicalTypeId::INTEGER: return IntegerNumberKey(Load(node.GetDataPointer())); - case VariantLogicalType::INT64: + case LogicalTypeId::BIGINT: return IntegerNumberKey(Load(node.GetDataPointer())); - case VariantLogicalType::UINT8: + case LogicalTypeId::UTINYINT: return IntegerNumberKey(Load(node.GetDataPointer())); - case VariantLogicalType::UINT16: + case LogicalTypeId::USMALLINT: return IntegerNumberKey(Load(node.GetDataPointer())); - case VariantLogicalType::UINT32: + case LogicalTypeId::UINTEGER: return IntegerNumberKey(Load(node.GetDataPointer())); - case VariantLogicalType::UINT64: + case LogicalTypeId::UBIGINT: return IntegerNumberKey(Load(node.GetDataPointer())); - case VariantLogicalType::INT128: { + case LogicalTypeId::HUGEINT: { bool negative; const auto magnitude = HugeintMagnitude(Load(node.GetDataPointer()), negative); return BuildNumberKey(negative, magnitude, 0); } - case VariantLogicalType::UINT128: + case LogicalTypeId::UHUGEINT: return BuildNumberKey(false, Load(node.GetDataPointer()), 0); default: throw InternalException("VariantGetNumberKey called on non-number type %s", EnumUtil::ToString(type_id)); } } -hugeint_t VariantGetTimestampValue(VariantLogicalType type_id, const VariantNode &node) { +hugeint_t VariantGetTimestampValue(LogicalTypeId type_id, const VariantNode &node) { switch (type_id) { - case VariantLogicalType::DATE: + case LogicalTypeId::DATE: return hugeint_t(node.GetData()) * hugeint_t(NANOS_PER_DAY); - case VariantLogicalType::TIMESTAMP_SEC: + case LogicalTypeId::TIMESTAMP_SEC: return hugeint_t(node.GetData()) * hugeint_t(NANOS_PER_SEC); - case VariantLogicalType::TIMESTAMP_MILIS: + case LogicalTypeId::TIMESTAMP_MS: return hugeint_t(node.GetData()) * hugeint_t(NANOS_PER_MILLI); - case VariantLogicalType::TIMESTAMP_MICROS: + case LogicalTypeId::TIMESTAMP: return hugeint_t(node.GetData()) * hugeint_t(NANOS_PER_MICRO); - case VariantLogicalType::TIMESTAMP_NANOS: + case LogicalTypeId::TIMESTAMP_NS: return hugeint_t(node.GetData()); default: throw InternalException("VariantGetTimestampValue called on non-TIMESTAMP type"); } } -hugeint_t VariantGetTimestampTZValue(VariantLogicalType type_id, const VariantNode &node) { +hugeint_t VariantGetTimestampTZValue(LogicalTypeId type_id, const VariantNode &node) { switch (type_id) { - case VariantLogicalType::TIMESTAMP_MICROS_TZ: + case LogicalTypeId::TIMESTAMP_TZ: return hugeint_t(node.GetData()) * hugeint_t(NANOS_PER_MICRO); - case VariantLogicalType::TIMESTAMP_NANOS_TZ: + case LogicalTypeId::TIMESTAMP_TZ_NS: return hugeint_t(node.GetData()); default: throw InternalException("VariantGetTimestampTZValue called on non-TIMESTAMP_TZ type"); } } -int64_t VariantGetTimeValue(VariantLogicalType type_id, const VariantNode &node) { +int64_t VariantGetTimeValue(LogicalTypeId type_id, const VariantNode &node) { switch (type_id) { - case VariantLogicalType::TIME_MICROS: + case LogicalTypeId::TIME: return node.GetData() * NANOS_PER_MICRO; - case VariantLogicalType::TIME_NANOS: + case LogicalTypeId::TIME_NS: return node.GetData(); default: throw InternalException("VariantGetTimeValue called on non-TIME type"); diff --git a/src/duckdb/src/common/types/variant/variant_iterator.cpp b/src/duckdb/src/common/types/variant/variant_iterator.cpp index a8ed7355b..4546b5ca5 100644 --- a/src/duckdb/src/common/types/variant/variant_iterator.cpp +++ b/src/duckdb/src/common/types/variant/variant_iterator.cpp @@ -76,80 +76,11 @@ bool ShreddedIsValid(const ShreddedVariantIterator &node, idx_t index) { //! except for BOOLEAN (which is BOOL_TRUE or BOOL_FALSE per value) and the layers that are never read //! as a scalar value (LIST/ARRAY/STRUCT), which are handled structurally by the iterator. VariantLogicalType ResolveShreddedTypeId(const LogicalType &type, bool &resolved) { - resolved = true; - switch (type.id()) { - case LogicalTypeId::TINYINT: - return VariantLogicalType::INT8; - case LogicalTypeId::SMALLINT: - return VariantLogicalType::INT16; - case LogicalTypeId::INTEGER: - return VariantLogicalType::INT32; - case LogicalTypeId::BIGINT: - return VariantLogicalType::INT64; - case LogicalTypeId::HUGEINT: - return VariantLogicalType::INT128; - case LogicalTypeId::UTINYINT: - return VariantLogicalType::UINT8; - case LogicalTypeId::USMALLINT: - return VariantLogicalType::UINT16; - case LogicalTypeId::UINTEGER: - return VariantLogicalType::UINT32; - case LogicalTypeId::UBIGINT: - return VariantLogicalType::UINT64; - case LogicalTypeId::UHUGEINT: - return VariantLogicalType::UINT128; - case LogicalTypeId::FLOAT: - return VariantLogicalType::FLOAT; - case LogicalTypeId::DOUBLE: - return VariantLogicalType::DOUBLE; - case LogicalTypeId::DECIMAL: - return VariantLogicalType::DECIMAL; - case LogicalTypeId::VARCHAR: - return VariantLogicalType::VARCHAR; - case LogicalTypeId::BLOB: - return VariantLogicalType::BLOB; - case LogicalTypeId::UUID: - return VariantLogicalType::UUID; - case LogicalTypeId::DATE: - return VariantLogicalType::DATE; - case LogicalTypeId::TIME: - return VariantLogicalType::TIME_MICROS; - case LogicalTypeId::TIME_NS: - return VariantLogicalType::TIME_NANOS; - case LogicalTypeId::TIME_TZ: - return VariantLogicalType::TIME_MICROS_TZ; - case LogicalTypeId::TIMESTAMP_SEC: - return VariantLogicalType::TIMESTAMP_SEC; - case LogicalTypeId::TIMESTAMP_MS: - return VariantLogicalType::TIMESTAMP_MILIS; - case LogicalTypeId::TIMESTAMP: - return VariantLogicalType::TIMESTAMP_MICROS; - case LogicalTypeId::TIMESTAMP_NS: - return VariantLogicalType::TIMESTAMP_NANOS; - case LogicalTypeId::TIMESTAMP_TZ: - return VariantLogicalType::TIMESTAMP_MICROS_TZ; - case LogicalTypeId::TIMESTAMP_TZ_NS: - return VariantLogicalType::TIMESTAMP_NANOS_TZ; - case LogicalTypeId::INTERVAL: - return VariantLogicalType::INTERVAL; - case LogicalTypeId::BIGNUM: - return VariantLogicalType::BIGNUM; - case LogicalTypeId::BIT: - return VariantLogicalType::BITSTRING; - case LogicalTypeId::GEOMETRY: - return VariantLogicalType::GEOMETRY; - case LogicalTypeId::GEOGRAPHY: - return VariantLogicalType::GEOGRAPHY; - case LogicalTypeId::STRUCT: - return VariantLogicalType::OBJECT; - case LogicalTypeId::LIST: - return VariantLogicalType::ARRAY; - case LogicalTypeId::BOOLEAN: - // BOOLEAN resolves to BOOL_TRUE / BOOL_FALSE per value - default: - resolved = false; - return VariantLogicalType::VARIANT_NULL; - } + //! BOOLEAN resolves to BOOL_TRUE / BOOL_FALSE per value + auto variant_type = VariantLogicalType::VARIANT_NULL; + resolved = type.id() != LogicalTypeId::BOOLEAN && type.id() != LogicalTypeId::SQLNULL && + TryVariantTypeFromLogicalTypeId(type.id(), variant_type); + return resolved ? variant_type : VariantLogicalType::VARIANT_NULL; } } // namespace @@ -395,7 +326,24 @@ static VariantLogicalType ShreddedTypeId(const ShreddedVariantIterator &content, return content.type_id; } -VariantLogicalType VariantNode::GetTypeId() const { +LogicalTypeId VariantNode::GetTypeId() const { + return VariantTypeToLogicalTypeId(GetVariantType()); +} + +LogicalType VariantNode::GetType() const { + auto type_id = GetTypeId(); + if (type_id == LogicalTypeId::DECIMAL) { + auto properties = GetDecimalProperties(); + return LogicalType::DECIMAL(properties.width, properties.scale); + } + return VariantDefaultType(type_id); +} + +bool VariantNode::GetBool() const { + return GetVariantType() == VariantLogicalType::BOOL_TRUE; +} + +VariantLogicalType VariantNode::GetVariantType() const { switch (kind) { case Kind::NULL_VALUE: return VariantLogicalType::VARIANT_NULL; diff --git a/src/duckdb/src/common/vector_operations/comparison_operators.cpp b/src/duckdb/src/common/vector_operations/comparison_operators.cpp index e4fc3c313..b8ebb1998 100644 --- a/src/duckdb/src/common/vector_operations/comparison_operators.cpp +++ b/src/duckdb/src/common/vector_operations/comparison_operators.cpp @@ -13,7 +13,7 @@ #include "duckdb/common/vector/list_vector.hpp" #include "duckdb/common/vector/struct_vector.hpp" #include "duckdb/common/vector/vector_iterator.hpp" -#include "duckdb/common/vector_operations/binary_executor.hpp" +#include "duckdb/common/vector_operations/string_comparison.hpp" #include "duckdb/common/vector_operations/vector_operations.hpp" #include "duckdb/common/likely.hpp" @@ -72,7 +72,7 @@ static bool TryPrimitiveComparisonExecute(const Vector &left, const Vector &righ BinaryExecutor::Execute(left, right, result); return true; case PhysicalType::VARCHAR: - BinaryExecutor::Execute(left, right, result); + StringComparison::Execute(left, right, result); return true; default: return false; diff --git a/src/duckdb/src/common/vector_operations/string_comparison.cpp b/src/duckdb/src/common/vector_operations/string_comparison.cpp new file mode 100644 index 000000000..d061c82d6 --- /dev/null +++ b/src/duckdb/src/common/vector_operations/string_comparison.cpp @@ -0,0 +1,97 @@ +#include "duckdb/common/vector_operations/string_comparison.hpp" +#include "duckdb/common/vector/vector_iterator.hpp" + +namespace duckdb { + +namespace { + +struct StringComparisonSample { + idx_t inlined = 0; + idx_t shared_prefix = 0; + idx_t different_suffix = 0; + + void Add(const string_t &left, const string_t &right) { +#ifndef DUCKDB_DEBUG_NO_INLINE + inlined += left.IsInlined() && right.IsInlined(); + if (left.GetPrefixIntegerComparable() == right.GetPrefixIntegerComparable()) { + shared_prefix++; + different_suffix += Load(const_data_ptr_cast(left.GetData()) + string_t::PREFIX_BYTES) != + Load(const_data_ptr_cast(right.GetData()) + string_t::PREFIX_BYTES); + } +#endif + } +}; + +template +StringComparisonMode SampleStringComparison(idx_t count, SAMPLE &&sample) { +#ifdef DUCKDB_DEBUG_NO_INLINE + return StringComparisonMode::GENERIC; +#else + if (count < 128) { + return StringComparisonMode::INLINED; + } + StringComparisonSample stats; + for (idx_t i = 0; i < 8; i++) { + // Scatter the samples to avoid aliasing with power-of-two input periods. + const auto row = ((i * 257 + 37) % 2048) * count / 2048; + sample(row, stats); + } + // Samples predict profitability; every kernel must handle arbitrary unsampled values. + if (stats.inlined >= 7) { + return StringComparisonMode::INLINED; + } + if (stats.shared_prefix && stats.different_suffix * 2 >= stats.shared_prefix) { + return StringComparisonMode::PREFIX; + } + return StringComparisonMode::GENERIC; +#endif +} + +} // namespace + +bool StringComparison::HasInlinedConstant(const Vector &left, const Vector &right) { + for (auto &input : {std::cref(left), std::cref(right)}) { + auto &constant = input.get(); + if (constant.GetVectorType() == VectorType::CONSTANT_VECTOR && !ConstantVector::IsNull(constant) && + ConstantVector::GetData(constant)->IsInlined()) { + return true; + } + } + return false; +} + +StringComparisonMode StringComparison::SelectMode(const Vector &left, const Vector &right, idx_t count) { +#ifdef DUCKDB_DEBUG_NO_INLINE + return StringComparisonMode::GENERIC; +#else + if (count < 128 || + (left.GetVectorType() == VectorType::CONSTANT_VECTOR && right.GetVectorType() == VectorType::CONSTANT_VECTOR)) { + return StringComparisonMode::INLINED; + } + auto left_values = left.Values(); + auto right_values = right.Values(); + return SampleStringComparison(count, [&](idx_t row, StringComparisonSample &stats) { + auto l = left_values[row]; + auto r = right_values[row]; + if (l.IsValid() && r.IsValid()) { + stats.Add(l.GetValue(), r.GetValue()); + } + }); +#endif +} + +StringComparisonMode StringComparison::SelectMode(const UnifiedVectorFormat &input, const string_t &constant, + const SelectionVector &sel, idx_t count) { + if (input.sel->data() == ConstantVector::ZERO_VECTOR) { + return StringComparisonMode::INLINED; + } + auto data = UnifiedVectorFormat::GetData(input); + return SampleStringComparison(count, [&](idx_t row, StringComparisonSample &stats) { + const auto idx = input.sel->get_index(sel.get_index(row)); + if (input.validity.RowIsValid(idx)) { + stats.Add(data[idx], constant); + } + }); +} + +} // namespace duckdb diff --git a/src/duckdb/src/common/virtual_file_system.cpp b/src/duckdb/src/common/virtual_file_system.cpp index 0ae15ed54..9c1176e0b 100644 --- a/src/duckdb/src/common/virtual_file_system.cpp +++ b/src/duckdb/src/common/virtual_file_system.cpp @@ -9,7 +9,6 @@ #include "duckdb/common/pipe_file_system.hpp" #include "duckdb/common/string_util.hpp" #include "duckdb/main/client_context.hpp" -#include "duckdb/storage/external_file_cache/caching_file_system_wrapper.hpp" #include "duckdb/common/multi_file/multi_file_list.hpp" #include "duckdb/common/mutex.hpp" #include "duckdb/main/database.hpp" @@ -115,28 +114,16 @@ VirtualFileSystem::VirtualFileSystem() : VirtualFileSystem(make_uniq &&inner) - : owned_local_file_system(inner->IsLocalFileSystem() ? nullptr : make_uniq()), - file_system_registry(make_shared_ptr(std::move(inner))) { + : file_system_registry(make_shared_ptr(std::move(inner))) { VirtualFileSystem::RegisterCompressionFilesystem(make_uniq()); } VirtualFileSystem::~VirtualFileSystem() { } -unique_ptr VirtualFileSystem::MemoryMapFile(const OpenFileInfo &path, FileOpenFlags flags, - const MMapOptions &options, - optional_ptr opener) { - auto registry = file_system_registry.atomic_load(); - auto &internal_filesystem = FindFileSystem(registry, path.path, opener); - return internal_filesystem.MemoryMapFile(path, flags, options, opener); -} - FileSystem &VirtualFileSystem::GetDefaultFileSystem() { - auto &fs = *file_system_registry->default_fs->file_system; - if (SubSystemIsDisabled(fs.GetName())) { - throw PermissionException("File system %s has been disabled by configuration", fs.GetName()); - } - return fs; + auto registry = file_system_registry.atomic_load(); + return *registry->default_fs->file_system; } //! The part of a path whose extension names its compression: a URL's path without its host, query or fragment, or a @@ -169,14 +156,6 @@ static FileCompressionType CompressionFromExtension(const string &lower_path) { return FileCompressionType::UNCOMPRESSED; } -FileSystem &VirtualFileSystem::GetLocalFileSystem() { - auto &fs = *file_system_registry->default_fs->file_system; - if (fs.IsLocalFileSystem()) { - return fs; - } - return *owned_local_file_system; -} - optional_ptr VirtualFileSystem::FindCompressionFileSystem(FileSystemRegistry ®istry, const FileCompressionType &compression, const string &filepath, bool for_writing) { @@ -230,31 +209,26 @@ optional_ptr VirtualFileSystem::FindCompressionFileSystem(FileSystem resolved.ToString(), hint); } -unique_ptr VirtualFileSystem::OpenFileExtended(const OpenFileInfo &file, FileOpenFlags flags, - optional_ptr opener) { +unique_ptr VirtualFileSystem::OpenFile(const OpenFileInfo &file, FileOpenFlags flags, + optional_ptr opener) { const FileCompressionType compression = flags.Compression(); // open the base file handle in UNCOMPRESSED mode flags.SetCompression(FileCompressionType::UNCOMPRESSED); auto registry = file_system_registry.atomic_load(); auto &internal_filesystem = FindFileSystem(registry, file.path, opener); - - // File handle gets created. - unique_ptr file_handle = nullptr; - - // Handle caching logic. - if (flags.GetCachingMode() != CachingMode::NO_CACHING) { - auto caching_filesystem = - make_shared_ptr(internal_filesystem, opener, flags.GetCachingMode()); - // caching filesystem's lifecycle is extended inside of caching file handle. - file_handle = caching_filesystem->OpenFile(file, flags, opener); - } else { - file_handle = internal_filesystem.OpenFile(file, flags, opener); - } + auto file_handle = internal_filesystem.OpenFile(file, flags, opener); if (!file_handle) { return nullptr; } + flags.SetCompression(compression); + return WrapOpenedFile(std::move(file_handle), file, flags, opener); +} +unique_ptr VirtualFileSystem::WrapOpenedFile(unique_ptr file_handle, const OpenFileInfo &file, + const FileOpenFlags &flags, optional_ptr opener) { + const auto &compression = flags.Compression(); + auto registry = file_system_registry.atomic_load(); try { // Evaluate and apply compression option then. QueryContext context; @@ -285,126 +259,6 @@ unique_ptr VirtualFileSystem::OpenFileExtended(const OpenFileInfo &f return file_handle; } -void VirtualFileSystem::Read(FileHandle &handle, void *buffer, int64_t nr_bytes, idx_t location) { - handle.file_system.Read(handle, buffer, nr_bytes, location); -} - -void VirtualFileSystem::Write(FileHandle &handle, void *buffer, int64_t nr_bytes, idx_t location) { - handle.file_system.Write(handle, buffer, nr_bytes, location); -} - -int64_t VirtualFileSystem::Read(FileHandle &handle, void *buffer, int64_t nr_bytes) { - return handle.file_system.Read(handle, buffer, nr_bytes); -} - -int64_t VirtualFileSystem::Write(FileHandle &handle, void *buffer, int64_t nr_bytes) { - return handle.file_system.Write(handle, buffer, nr_bytes); -} - -int64_t VirtualFileSystem::GetFileSize(FileHandle &handle) { - return handle.file_system.GetFileSize(handle); -} -timestamp_t VirtualFileSystem::GetLastModifiedTime(FileHandle &handle) { - return handle.file_system.GetLastModifiedTime(handle); -} -string VirtualFileSystem::GetVersionTag(FileHandle &handle) { - return handle.file_system.GetVersionTag(handle); -} -FileType VirtualFileSystem::GetFileType(FileHandle &handle) { - return handle.file_system.GetFileType(handle); -} -FileMetadata VirtualFileSystem::Stats(FileHandle &handle) { - return handle.file_system.Stats(handle); -} - -optional VirtualFileSystem::GetStatsIfExists(const OpenFileInfo &file, optional_ptr opener) { - return FindFileSystem(file.path, opener).GetStatsIfExists(file, opener); -} - -void VirtualFileSystem::Truncate(FileHandle &handle, int64_t new_size) { - handle.file_system.Truncate(handle, new_size); -} - -void VirtualFileSystem::FileSync(FileHandle &handle) { - handle.file_system.FileSync(handle); -} - -// need to look up correct fs for this -bool VirtualFileSystem::DirectoryExists(const string &directory, optional_ptr opener) { - return FindFileSystem(directory, opener).DirectoryExists(directory, opener); -} -void VirtualFileSystem::CreateDirectory(const string &directory, optional_ptr opener) { - CreateDirectoryExtended(directory, {CreateDirectoryMode::SINGLE}, opener); -} - -bool VirtualFileSystem::CreateDirectoryExtended(const string &directory, const CreateDirectoryOptions &options, - optional_ptr opener) { - return FindFileSystem(directory, opener).CreateDirectoryExtended(directory, options, opener); -} - -void VirtualFileSystem::CreateDirectoriesRecursive(const string &path, optional_ptr opener) { - CreateDirectoryExtended(path, {CreateDirectoryMode::RECURSIVE}, opener); -} - -void VirtualFileSystem::RemoveDirectory(const string &directory, optional_ptr opener) { - RemoveDirectoryExtended(directory, {RemoveDirectoryMode::RECURSIVE}, opener); -} - -bool VirtualFileSystem::RemoveDirectoryExtended(const string &directory, const RemoveDirectoryOptions &options, - optional_ptr opener) { - return FindFileSystem(directory, opener).RemoveDirectoryExtended(directory, options, opener); -} - -bool VirtualFileSystem::ListFilesExtended(const string &directory, - const std::function &callback, - optional_ptr opener) { - return FindFileSystem(directory, opener).ListFiles(directory, callback, opener); -} - -void VirtualFileSystem::MoveFile(const string &source, const string &target, optional_ptr opener) { - FindFileSystem(source, opener).MoveFile(source, target, opener); -} - -bool VirtualFileSystem::FileExists(const string &filename, optional_ptr opener) { - return FindFileSystem(filename, opener).FileExists(filename, opener); -} - -bool VirtualFileSystem::IsPipe(const string &filename, optional_ptr opener) { - return FindFileSystem(filename, opener).IsPipe(filename, opener); -} - -void VirtualFileSystem::RemoveFile(const string &filename, optional_ptr opener) { - FindFileSystem(filename, opener).RemoveFile(filename, opener); -} - -bool VirtualFileSystem::TryRemoveFile(const string &filename, optional_ptr opener) { - return FindFileSystem(filename, opener).TryRemoveFile(filename, opener); -} - -void VirtualFileSystem::RemoveFiles(const vector &filenames, optional_ptr opener) { - reference_map_t> files_by_fs; - for (const auto &filename : filenames) { - auto &fs = FindFileSystem(filename, opener); - files_by_fs[fs].push_back(filename); - } - for (auto &entry : files_by_fs) { - entry.first.get().RemoveFiles(entry.second, opener); - } -} - -string VirtualFileSystem::PathSeparator(const string &path) { - return FindFileSystem(path, nullptr).PathSeparator(path); -} - -string VirtualFileSystem::CanonicalizePath(const string &path_p, optional_ptr opener) { - return FindFileSystem(path_p, opener).CanonicalizePath(path_p, opener); -} - -unique_ptr VirtualFileSystem::GlobFilesExtended(const string &path, const FileGlobInput &input, - optional_ptr opener) { - return FindFileSystem(path, opener).Glob(path, input, opener); -} - void VirtualFileSystem::RegisterSubSystem(unique_ptr fs) { lock_guard guard(registry_lock); auto new_registry = file_system_registry->RegisterSubSystem(std::move(fs)); diff --git a/src/duckdb/src/execution/expression_executor/execute_comparison.cpp b/src/duckdb/src/execution/expression_executor/execute_comparison.cpp index c20b2aa11..9311c715d 100644 --- a/src/duckdb/src/execution/expression_executor/execute_comparison.cpp +++ b/src/duckdb/src/execution/expression_executor/execute_comparison.cpp @@ -3,7 +3,7 @@ #include "duckdb/common/uhugeint.hpp" #include "duckdb/common/vector/flat_vector.hpp" #include "duckdb/common/vector/vector_iterator.hpp" -#include "duckdb/common/vector_operations/binary_executor.hpp" +#include "duckdb/common/vector_operations/string_comparison.hpp" #include "duckdb/common/vector_operations/vector_operations.hpp" #include "duckdb/execution/expression_executor.hpp" #include "duckdb/planner/expression/bound_comparison_expression.hpp" @@ -92,8 +92,7 @@ static bool TryPrimitiveSelectOperation(const Vector &left, const Vector &right, false_sel.get()); return true; case PhysicalType::VARCHAR: - result = BinaryExecutor::Select(left, right, sel.get(), count, true_sel.get(), - false_sel.get()); + result = StringComparison::Select(left, right, sel.get(), count, true_sel.get(), false_sel.get()); return true; default: return false; diff --git a/src/duckdb/src/execution/index/art/art.cpp b/src/duckdb/src/execution/index/art/art.cpp index c50ab1693..171f952c8 100644 --- a/src/duckdb/src/execution/index/art/art.cpp +++ b/src/duckdb/src/execution/index/art/art.cpp @@ -249,6 +249,16 @@ static bool TryMatchComparison(const Expression &expr, const Expression &filter_ return !constant_value.IsNull(); } +static void CollectConjunctionChildren(const Expression &expr, vector> &result) { + if (expr.GetExpressionType() != ExpressionType::CONJUNCTION_AND) { + result.push_back(expr); + return; + } + for (auto &child : expr.Cast().GetChildren()) { + CollectConjunctionChildren(*child, result); + } +} + static bool IsLowerBound(const ExpressionType comparison_type) { return comparison_type == ExpressionType::COMPARE_GREATERTHAN || comparison_type == ExpressionType::COMPARE_GREATERTHANOREQUALTO; @@ -259,73 +269,51 @@ unique_ptr ART::TryInitializeScan(const Expression &expr, const ExpressionType low_comparison_type = ExpressionType::INVALID; ExpressionType high_comparison_type = ExpressionType::INVALID; - if (filter_expr.GetExpressionType() == ExpressionType::COMPARE_BETWEEN) { - auto &between = filter_expr.Cast(); - auto &input = BoundBetweenExpression::Input(between); - if (!input.Equals(expr)) { - // The expression does not match the index expression. - return nullptr; - } - auto &lower_bound = BoundBetweenExpression::LowerBound(between); - auto &upper_bound = BoundBetweenExpression::UpperBound(between); - - if (lower_bound.GetExpressionType() != ExpressionType::VALUE_CONSTANT || - upper_bound.GetExpressionType() != ExpressionType::VALUE_CONSTANT) { - // Not a constant expression. - return nullptr; - } - - // A NULL bound matches no rows. - if (lower_bound.Cast().GetValue().IsNull() || - upper_bound.Cast().GetValue().IsNull()) { - return nullptr; + // Keeps the first bound on each side. + auto add_bound = [&](const Value &value, const ExpressionType comparison_type) { + auto is_lower = IsLowerBound(comparison_type); + auto &bound_value = is_lower ? low_value : high_value; + if (bound_value.IsNull()) { + bound_value = value; + (is_lower ? low_comparison_type : high_comparison_type) = comparison_type; } + }; - auto lower_inclusive = BoundBetweenExpression::LowerInclusive(between); - auto upper_inclusive = BoundBetweenExpression::UpperInclusive(between); - low_value = lower_bound.Cast().GetValue(); - low_comparison_type = - lower_inclusive ? ExpressionType::COMPARE_GREATERTHANOREQUALTO : ExpressionType::COMPARE_GREATERTHAN; - high_value = upper_bound.Cast().GetValue(); - high_comparison_type = - upper_inclusive ? ExpressionType::COMPARE_LESSTHANOREQUALTO : ExpressionType::COMPARE_LESSTHAN; - } else { - // A rewritten BETWEEN arrives as (lower bound) AND (upper bound). - // The index scan result is not filtered again, so the comparisons must cover the filter exactly. - vector> comparisons; - if (filter_expr.GetExpressionType() == ExpressionType::CONJUNCTION_AND) { - for (auto &child : filter_expr.Cast().GetChildren()) { - comparisons.push_back(*child); - } - } else { - comparisons.push_back(filter_expr); - } - if (comparisons.size() > 2) { - return nullptr; - } - for (auto &comparison : comparisons) { - ExpressionType comparison_type; - Value constant_value; - if (!TryMatchComparison(expr, comparison.get(), comparison_type, constant_value)) { - return nullptr; - } - if (comparison_type == ExpressionType::COMPARE_EQUAL) { - if (comparisons.size() != 1) { - return nullptr; - } - return InitializeScanSinglePredicate(constant_value, ExpressionType::COMPARE_EQUAL); + // Use the conjuncts that form a key range, the caller applies the remaining ones to the fetched rows. + vector> comparisons; + CollectConjunctionChildren(filter_expr, comparisons); + for (auto &comparison_ref : comparisons) { + auto &comparison = comparison_ref.get(); + if (comparison.GetExpressionType() == ExpressionType::COMPARE_BETWEEN) { + auto &between = comparison.Cast(); + auto &lower_bound = BoundBetweenExpression::LowerBound(between); + auto &upper_bound = BoundBetweenExpression::UpperBound(between); + if (!BoundBetweenExpression::Input(between).Equals(expr) || + lower_bound.GetExpressionType() != ExpressionType::VALUE_CONSTANT || + upper_bound.GetExpressionType() != ExpressionType::VALUE_CONSTANT) { + continue; } - auto is_lower = IsLowerBound(comparison_type); - auto &bound_value = is_lower ? low_value : high_value; - auto &bound_comparison_type = is_lower ? low_comparison_type : high_comparison_type; - if (!bound_value.IsNull()) { - // Two bounds on the same side. + auto &lower_value = lower_bound.Cast().GetValue(); + auto &upper_value = upper_bound.Cast().GetValue(); + // A NULL bound matches no rows. + if (lower_value.IsNull() || upper_value.IsNull()) { return nullptr; } - bound_value = constant_value; - bound_comparison_type = comparison_type; + add_bound(lower_value, BoundBetweenExpression::LowerComparisonType(between)); + add_bound(upper_value, BoundBetweenExpression::UpperComparisonType(between)); + continue; + } + ExpressionType comparison_type; + Value constant_value; + if (!TryMatchComparison(expr, comparison, comparison_type, constant_value)) { + continue; + } + if (comparison_type == ExpressionType::COMPARE_EQUAL) { + return InitializeScanSinglePredicate(constant_value, ExpressionType::COMPARE_EQUAL); } + add_bound(constant_value, comparison_type); } + // We cannot use an index scan. if (low_value.IsNull() && high_value.IsNull()) { return nullptr; diff --git a/src/duckdb/src/execution/join_hashtable.cpp b/src/duckdb/src/execution/join_hashtable.cpp index 053ceaa34..f4b8e5c54 100644 --- a/src/duckdb/src/execution/join_hashtable.cpp +++ b/src/duckdb/src/execution/join_hashtable.cpp @@ -93,7 +93,9 @@ JoinHashTable::SharedState::SharedState() JoinHashTable::ProbeState::ProbeState() : SharedState(), hashes(LogicalType::HASH), ht_offsets_and_salts_v(LogicalType::UBIGINT), - hashes_dense_v(LogicalType::HASH) { + hashes_dense_v(LogicalType::HASH), rows_to_probe_sel(STANDARD_VECTOR_SIZE), rows_found_sel(STANDARD_VECTOR_SIZE), + dense_entries(make_unsafe_uniq_array_uninitialized(STANDARD_VECTOR_SIZE)), + is_match_v(LogicalType::BOOLEAN), needs_next_v(LogicalType::BOOLEAN) { } JoinHashTable::ProbeDictionaryState::ProbeDictionaryState() : unique_entries(STANDARD_VECTOR_SIZE) { @@ -289,72 +291,154 @@ idx_t GetOptionalIndex(optional_ptr sel, const idx_t idx) return HAS_SEL ? sel->get_index(idx) : idx; } -static void AddPointerToCompare(SelectionVector &compare_sel, const ht_entry_t &entry, data_ptr_t *row_ptr_insert_to, - idx_t *ht_offsets_and_salts, idx_t row_ht_offset, idx_t &keys_to_compare_count, - const idx_t &row_index) { - compare_sel.set_index(keys_to_compare_count, row_index); - row_ptr_insert_to[row_index] = entry.GetPointer(); - // If the key does not match, we have to continue linear probing, we need to store the ht_offset and the salt - // for this element based on the row_index. We can't get the offset from the hash as we already might have - // some linear probing steps when arriving here. - ht_offsets_and_salts[row_index] = row_ht_offset | entry.GetSaltWithNulls(); - keys_to_compare_count += 1; +template +static inline void CheckEntry(const ht_entry_t entry, const hash_t hash, bool &has_salt_match, bool &needs_next) { + const bool occupied = entry.IsOccupied(); + // an empty entry reads as salt 0, so a match also needs occupied; & instead of && keeps it branch-free + const bool salt_match = occupied & (!USE_SALTS || entry.GetSalt() == ht_entry_t::ExtractSalt(hash)); + has_salt_match = salt_match; + needs_next = occupied & !salt_match; +} + +//! The entry `steps` slots after the initial slot of a densified hash +static inline const ht_entry_t &GetHTEntry(const ht_entry_t *entries, const hash_t hash_dense, const idx_t steps, + const idx_t bitmask) { + return entries[(hash_dense + steps) & bitmask]; +} + +//! The ht offset of that entry, with the salt of the hash +static inline idx_t GetHTOffsetAndSalt(const hash_t hash_dense, const idx_t steps, const idx_t bitmask) { + return ((hash_dense + steps) & bitmask) | (hash_dense & ht_entry_t::SALT_MASK); } +//! Per-row linear probing with branches template -static idx_t ProbeForPointersInternal(JoinHashTable::ProbeState &state, JoinHashTable &ht, - unsafe_optional_ptr entries, Vector &pointers_result_v, - optional_ptr row_sel, idx_t &count) { - auto hashes_dense = FlatVector::GetDataMutable(state.hashes_dense_v); +static idx_t ProbeForPointersBranching(JoinHashTable::ProbeState &state, JoinHashTable &ht, + unsafe_optional_ptr entries, Vector &pointers_result_v, + optional_ptr row_sel, const idx_t count) { + const auto hashes_dense = FlatVector::GetData(state.hashes_dense_v); const auto bitmask = ht.bitmask; - - const auto row_ptr_insert_to = FlatVector::GetDataMutable(pointers_result_v); + const auto pointers_result = FlatVector::GetDataMutable(pointers_result_v); const auto ht_offsets_and_salts = FlatVector::GetDataMutable(state.ht_offsets_and_salts_v); - idx_t keys_to_compare_count = 0; + idx_t compare_count = 0; for (idx_t i = 0; i < count; i++) { - PrefetchHashTableEntry(i, count, - [&](idx_t next_idx) { return &entries.get()[hashes_dense[next_idx] & bitmask]; }); - auto row_hash = hashes_dense[i]; // hashes have been flattened before -> always access dense - auto row_ht_offset = row_hash & bitmask; - - if (USE_SALTS) { - // increment the ht_offset of the entry as long as the next entry is occupied and salt does not match - while (true) { - const ht_entry_t entry = entries.get()[row_ht_offset]; - const bool occupied = entry.IsOccupied(); + const auto hash = hashes_dense[i]; + idx_t steps = 0; + while (true) { + const ht_entry_t entry = GetHTEntry(entries.get(), hash, steps, bitmask); + if (!entry.IsOccupied()) { + break; + } + if (!USE_SALTS || entry.GetSalt() == ht_entry_t::ExtractSalt(hash)) { + const auto row_index = GetOptionalIndex(row_sel, i); + state.keys_to_compare_sel.set_index(compare_count++, row_index); + pointers_result[row_index] = entry.GetPointerOrNull(); + ht_offsets_and_salts[row_index] = GetHTOffsetAndSalt(hash, steps, bitmask); + break; + } + steps++; + } + } + return compare_count; +} - // the entry is empty -> no match possible - if (!occupied) { - break; - } +//! Linear probing of all rows at once, one entry per round, without data-dependent branches; the probe works on dense +//! indices, mapped through row_sel. +template +static idx_t ProbeForPointersBranchless(JoinHashTable::ProbeState &state, JoinHashTable &ht, + unsafe_optional_ptr entries, Vector &pointers_result_v, + optional_ptr row_sel, const idx_t count) { + const auto hashes_dense = FlatVector::GetData(state.hashes_dense_v); + const auto bitmask = ht.bitmask; + const auto dense_entries = state.dense_entries.get(); - const hash_t row_salt = ht_entry_t::ExtractSalt(row_hash); - const bool salt_match = entry.GetSalt() == row_salt; - if (salt_match) { - // we know that the entry is occupied and the salt matches -> compare the keys - auto row_index = GetOptionalIndex(row_sel, i); - AddPointerToCompare(state.keys_to_compare_sel, entry, row_ptr_insert_to, ht_offsets_and_salts, - row_ht_offset, keys_to_compare_count, row_index); - break; - } + // the initial entry of every row; a loop that only loads keeps many cache misses in flight + const auto get_initial_entry = [&](const idx_t dense_index) { + return &GetHTEntry(entries.get(), hashes_dense[dense_index], 0, bitmask); + }; + const bool prefetch = ht.capacity > JoinHashTable::PREFETCH_MIN_CAPACITY; + for (idx_t i = 0; i < count; i++) { + if (prefetch) { + PrefetchHashTableEntry(i, count, get_initial_entry); + } + dense_entries[i] = *get_initial_entry(i); + } - // full and salt do not match -> continue probing - IncrementAndWrap(row_ht_offset, bitmask); - } - } else { - const ht_entry_t entry = entries.get()[row_ht_offset]; - const bool occupied = entry.IsOccupied(); - if (occupied) { - // the entry is occupied -> compare the keys - auto row_index = GetOptionalIndex(row_sel, i); - AddPointerToCompare(state.keys_to_compare_sel, entry, row_ptr_insert_to, ht_offsets_and_salts, - row_ht_offset, keys_to_compare_count, row_index); + // pointers and ht offsets go to their row index, so rows outside the selection keep theirs + const auto pointers_result = FlatVector::GetDataMutable(pointers_result_v); + const auto ht_offsets_and_salts = FlatVector::GetDataMutable(state.ht_offsets_and_salts_v); + const auto is_match = FlatVector::GetDataMutable(state.is_match_v); + const auto needs_next = FlatVector::GetDataMutable(state.needs_next_v); + for (idx_t i = 0; i < count; i++) { + const auto row_index = GetOptionalIndex(row_sel, i); + const auto entry = dense_entries[i]; + pointers_result[row_index] = entry.GetPointerOrNull(); + CheckEntry(entry, hashes_dense[i], is_match[i], needs_next[i]); + } + + // the rows whose initial entry holds another salt + idx_t need_additional_probe_n = SelectionVector::SelectFromBoolean( + needs_next, nullptr, count, array_ptr(state.rows_to_probe_sel.data(), STANDARD_VECTOR_SIZE)); + + // do another round of probing at the next ht offsets for all probe rows that had a salt mismatch + for (idx_t probe_round_idx = 1; need_additional_probe_n > 0; probe_round_idx++) { + const auto get_entry = [&](const idx_t probe_index) { + const auto dense_index = state.rows_to_probe_sel.get_index(probe_index); + return &GetHTEntry(entries.get(), hashes_dense[dense_index], probe_round_idx, bitmask); + }; + idx_t found_count = 0; + idx_t next_probe_count = 0; + for (idx_t i = 0; i < need_additional_probe_n; i++) { + const auto dense_index = state.rows_to_probe_sel.get_index(i); + // the cache lines were loaded in the initial round, but are no longer close: prefetch ahead again + if (prefetch) { + PrefetchHashTableEntry(i, need_additional_probe_n, get_entry); } + bool row_is_match; + bool row_needs_next; + CheckEntry(*get_entry(i), hashes_dense[dense_index], row_is_match, row_needs_next); + state.rows_found_sel.AppendIf(found_count, dense_index, row_is_match); + state.rows_to_probe_sel.AppendIf(next_probe_count, dense_index, row_needs_next); } + // only the rows that found their entry in this round need its pointer and ht offset + for (idx_t i = 0; i < found_count; i++) { + const auto dense_index = state.rows_found_sel.get_index(i); + const auto row_index = GetOptionalIndex(row_sel, dense_index); + const auto hash = hashes_dense[dense_index]; + const auto entry = GetHTEntry(entries.get(), hash, probe_round_idx, bitmask); + pointers_result[row_index] = entry.GetPointerOrNull(); + ht_offsets_and_salts[row_index] = GetHTOffsetAndSalt(hash, probe_round_idx, bitmask); + is_match[dense_index] = true; + } + need_additional_probe_n = next_probe_count; } - return keys_to_compare_count; + // the rows to compare, in row order: the scan references the probe columns when every row matches in order + const idx_t compare_count = SelectionVector::SelectFromBoolean( + is_match, nullptr, count, array_ptr(state.keys_to_compare_sel.data(), STANDARD_VECTOR_SIZE)); + if (HAS_SEL) { + for (idx_t i = 0; i < compare_count; i++) { + const auto dense_index = state.keys_to_compare_sel.get_index(i); + state.keys_to_compare_sel.set_index(i, row_sel->get_index(dense_index)); + } + } + return compare_count; +} + +//! Finds the first entry of every row whose salt matches (USE_SALTS) or that is occupied, and returns the number of +//! rows in keys_to_compare_sel, with their entry pointer in pointers_result_v. Short vectors and retries after a key +//! mismatch probe with branches. +template +static idx_t ProbeForPointersInternal(JoinHashTable::ProbeState &state, JoinHashTable &ht, + unsafe_optional_ptr entries, Vector &pointers_result_v, + optional_ptr row_sel, const idx_t count, + const bool is_retry) { + D_ASSERT(count <= STANDARD_VECTOR_SIZE); + if (is_retry || count <= JoinHashTable::BRANCHING_PROBE_MAX_COUNT) { + return ProbeForPointersBranching(state, ht, entries, pointers_result_v, row_sel, count); + } + return ProbeForPointersBranchless(state, ht, entries, pointers_result_v, row_sel, count); } /// for each entry, do linear probing until @@ -365,11 +449,36 @@ static idx_t ProbeForPointersInternal(JoinHashTable::ProbeState &state, JoinHash template static idx_t ProbeForPointers(JoinHashTable::ProbeState &state, JoinHashTable &ht, unsafe_optional_ptr entries, Vector &pointers_result_v, - optional_ptr row_sel, idx_t count, const bool has_row_sel) { + optional_ptr row_sel, idx_t count, const bool has_row_sel, + const bool is_retry) { if (has_row_sel) { - return ProbeForPointersInternal(state, ht, entries, pointers_result_v, row_sel, count); + return ProbeForPointersInternal(state, ht, entries, pointers_result_v, row_sel, count, + is_retry); } else { - return ProbeForPointersInternal(state, ht, entries, pointers_result_v, row_sel, count); + return ProbeForPointersInternal(state, ht, entries, pointers_result_v, row_sel, count, + is_retry); + } +} + +template +static void DensifyHashes(Vector &hashes_v, Vector &hashes_dense_v, optional_ptr row_sel, + const idx_t count, const idx_t bucket_shift, const idx_t bitmask) { + const auto to_dense = [&](const hash_t hash) { + return bucket_shift ? (hash & ht_entry_t::SALT_MASK) | ((hash >> bucket_shift) & bitmask) : hash; + }; + const auto hashes_dense = FlatVector::GetDataMutable(hashes_dense_v); + if (!HAS_SEL && hashes_v.GetVectorType() == VectorType::FLAT_VECTOR) { + // plain arrays: no unified format to set up, which short vectors cannot pay back + const auto hashes = FlatVector::GetData(hashes_v); + for (idx_t i = 0; i < count; i++) { + hashes_dense[i] = to_dense(hashes[i]); + } + return; + } + auto hashes_unified = hashes_v.Values(); + for (idx_t i = 0; i < count; i++) { + const auto row_index = GetOptionalIndex(row_sel, i); + hashes_dense[i] = to_dense(hashes_unified[row_index].GetValue()); } } @@ -380,22 +489,14 @@ static void GetRowPointersInternal(DataChunk &keys, TupleDataChunkState &key_sta Vector &hashes_v, optional_ptr row_sel, idx_t &count, JoinHashTable &ht, unsafe_optional_ptr entries, Vector &pointers_result_v, SelectionVector &match_sel, bool has_row_sel) { - // Densify original hashes, mapping resident buckets once. Retries below already contain offsets and salt. + // Densify the original hashes into salt and initial ht offset. Retries below already contain offsets and salt. const auto input_count = count; const auto bucket_shift = ht.GetBucketShift(); const auto bitmask = ht.bitmask; - if (has_row_sel || bucket_shift) { - auto hashes_unified = hashes_v.Values(); - auto hashes_dense = FlatVector::Writer(state.hashes_dense_v, input_count); - - for (idx_t i = 0; i < input_count; i++) { - const auto row_index = has_row_sel ? row_sel->get_index(i) : i; - const auto hash = hashes_unified[row_index].GetValue(); - hashes_dense.WriteValue(bucket_shift ? (hash & ht_entry_t::SALT_MASK) | ((hash >> bucket_shift) & bitmask) - : hash); - } + if (has_row_sel) { + DensifyHashes(hashes_v, state.hashes_dense_v, row_sel, input_count, bucket_shift, bitmask); } else { - VectorOperations::Copy(hashes_v, state.hashes_dense_v, input_count, 0, 0); + DensifyHashes(hashes_v, state.hashes_dense_v, row_sel, input_count, bucket_shift, bitmask); } // the number of keys that match for all iterations of the following loop @@ -404,9 +505,13 @@ static void GetRowPointersInternal(DataChunk &keys, TupleDataChunkState &key_sta idx_t keys_no_match_count; idx_t elements_to_probe_count = count; + // the branch-free probe stores no ht offset for a row compared at its initial entry: that row keeps this value + const auto ht_offsets_and_salts = FlatVector::GetDataMutable(state.ht_offsets_and_salts_v); + std::fill_n(ht_offsets_and_salts, keys.size(), DConstants::INVALID_INDEX); + bool is_retry = false; do { const idx_t keys_to_compare_count = ProbeForPointers(state, ht, entries, pointers_result_v, row_sel, - elements_to_probe_count, has_row_sel); + elements_to_probe_count, has_row_sel, is_retry); // if there are no keys to compare, we are done if (keys_to_compare_count == 0) { @@ -428,20 +533,34 @@ static void GetRowPointersInternal(DataChunk &keys, TupleDataChunkState &key_sta match_count++; } - const auto ht_offsets_and_salts = FlatVector::GetData(state.ht_offsets_and_salts_v); - const auto hashes_dense = FlatVector::GetDataMutable(state.hashes_dense_v); - - // For all the non-matches, increment the offset to continue probing but keep the salt intact - for (idx_t i = 0; i < keys_no_match_count; i++) { - const auto row_index = state.keys_no_match_sel.get_index(i); - auto ht_offset_and_salt = ht_offsets_and_salts[row_index]; - IncrementAndWrap(ht_offset_and_salt, bitmask | ht_entry_t::SALT_MASK); - hashes_dense[i] = ht_offset_and_salt; // populate dense again + if (keys_no_match_count > 0) { + if (!is_retry) { + // rows compared at their initial entry get its offset from the original hash + auto hashes_unified = hashes_v.Values(); + for (idx_t i = 0; i < keys_no_match_count; i++) { + const auto row_index = state.keys_no_match_sel.get_index(i); + if (ht_offsets_and_salts[row_index] == DConstants::INVALID_INDEX) { + const auto hash = hashes_unified[row_index].GetValue(); + const auto initial_offset = (hash >> bucket_shift) & bitmask; + ht_offsets_and_salts[row_index] = (hash & ht_entry_t::SALT_MASK) | initial_offset; + } + } + } + // For all the non-matches, increment the offset to continue probing but keep the salt intact + const auto hashes_dense = FlatVector::GetDataMutable(state.hashes_dense_v); + for (idx_t i = 0; i < keys_no_match_count; i++) { + const auto row_index = state.keys_no_match_sel.get_index(i); + auto ht_offset_and_salt = ht_offsets_and_salts[row_index]; + D_ASSERT(ht_offset_and_salt != DConstants::INVALID_INDEX); + IncrementAndWrap(ht_offset_and_salt, bitmask | ht_entry_t::SALT_MASK); + hashes_dense[i] = ht_offset_and_salt; // populate dense again + } } // in the next iteration, we have a selection vector with the keys that do not match row_sel = state.keys_no_match_sel; has_row_sel = true; + is_retry = true; elements_to_probe_count = keys_no_match_count; diff --git a/src/duckdb/src/execution/operator/aggregate/physical_window.cpp b/src/duckdb/src/execution/operator/aggregate/physical_window.cpp index fb26a303e..6f533a33e 100644 --- a/src/duckdb/src/execution/operator/aggregate/physical_window.cpp +++ b/src/duckdb/src/execution/operator/aggregate/physical_window.cpp @@ -166,6 +166,8 @@ class WindowHashGroup { OrderMasks order_masks; unordered_map order_mask_data; OnceFlag masks_initialized; + //! The number of partitions + atomic partition_count = 0; //! The fully materialised data collection unique_ptr collection; //! The processing stage for this group @@ -642,6 +644,7 @@ void WindowHashGroup::ComputeMasks(const idx_t block_begin, const idx_t block_en partition_mask.SetRangeInvalid(count, begin_entry, end_entry); if (!block_begin) { partition_mask.SetValidUnsafe(0); + ++partition_count; } for (auto &order_mask : order_masks) { order_mask.second.SetRangeInvalid(count, begin_entry, end_entry); @@ -687,6 +690,7 @@ void WindowHashGroup::ComputeMasks(const idx_t block_begin, const idx_t block_en for (idx_t i = 0; i < ndistinct; ++i) { const idx_t curr_index = row_idx + distinct.get_index(i); partition_mask.SetValidUnsafe(curr_index); + ++partition_count; for (auto &order_mask : order_masks) { order_mask.second.SetValidUnsafe(curr_index); } @@ -784,6 +788,13 @@ class WindowLocalSourceState : public LocalSourceState { void Finalize(ExecutionContext &context, InterruptState &interrupt); //! Get a chunk by evaluating functions void GetData(ExecutionContext &context, DataChunk &chunk, InterruptState &interrupt); + //! Evaluate a slice of the input + void Evaluate(ExecutionContext &context, const idx_t position, DataChunk &input, DataChunk &output, + InterruptState &interrupt); + //! Merge the input and output columns into the result + void BuildResult(ExecutionContext &context, DataChunk &input, DataChunk &output, DataChunk &result) const; + //! Co-Evaluation with Early Stop pruning + void CoEvaluate(ExecutionContext &context, DataChunk &result, InterruptState &interrupt); //! Storage and evaluation for the fully materialised data unique_ptr builder; @@ -797,6 +808,12 @@ class WindowLocalSourceState : public LocalSourceState { //! Storage and evaluation for chunks used in the evaluate phase ExpressionExecutor eval_exec; DataChunk eval_chunk; + + //! Early stop evaluation + idx_t partition_start = DConstants::INVALID_INDEX; + idx_t partition_end = DConstants::INVALID_INDEX; + DataChunk overlap_input; + SelectionVector overlap_sel; }; idx_t WindowHashGroup::InitTasks(idx_t per_thread_p) { @@ -976,7 +993,9 @@ WindowLocalSourceState::WindowLocalSourceState(WindowGlobalSourceState &gsource) output_types.emplace_back(wexpr.GetReturnType()); } output_chunk.Initialize(gsource.client, output_types); - + if (gsink.op.partition_limit.IsValid()) { + overlap_sel.Initialize(); + } auto &shared = gsink.shared; shared.PrepareCollection(coll_exec, coll_chunk); shared.PrepareSink(sink_exec, sink_chunk); @@ -1066,6 +1085,9 @@ bool WindowLocalSourceState::TryAssignTask() { // Scanner first, as it may be referencing sort blocks in the hash group scanner.reset(); + // Force a recalculation of the partition_start + partition_start = DConstants::INVALID_INDEX; + return gsource.TryNextTask(task, task_local); } @@ -1109,49 +1131,165 @@ void WindowLocalSourceState::ExecuteTask(ExecutionContext &context, DataChunk &r } } -void WindowLocalSourceState::GetData(ExecutionContext &context, DataChunk &result, InterruptState &interrupt) { - D_ASSERT(window_hash_group->GetStage() == WindowGroupStage::GETDATA); - - window_hash_group->UpdateScanner(scanner, task->begin_idx); - batch_index = window_hash_group->batch_base + task->begin_idx; - - const auto position = scanner->Scanned(); - auto &input_chunk = scanner->chunk; - scanner->Scan(); - +void WindowLocalSourceState::Evaluate(ExecutionContext &context, const idx_t position, DataChunk &input, + DataChunk &output, InterruptState &interrupt) { const auto &executors = gsource.gsink.executors; auto &gestates = window_hash_group->gestates; auto &local_states = window_hash_group->thread_states.at(task->thread_idx); - output_chunk.Reset(); + for (idx_t expr_idx = 0; expr_idx < executors.size(); ++expr_idx) { auto &executor = *executors[expr_idx]; - auto &result = output_chunk.data[expr_idx]; + auto &result = output.data[expr_idx]; if (eval_chunk.data.empty()) { - eval_chunk.SetChildCardinality(input_chunk.size()); + eval_chunk.SetChildCardinality(input.size()); } else { eval_chunk.Reset(); - eval_exec.Execute(input_chunk, eval_chunk); + eval_exec.Execute(input, eval_chunk); } OperatorSinkInput sink {*gestates[expr_idx], *local_states[expr_idx], interrupt}; - executor.Evaluate(context, position, eval_chunk, result, sink, input_chunk.size()); + executor.Evaluate(context, position, eval_chunk, result, sink, input.size()); } + output_chunk.Verify(context.client.db); +} +void WindowLocalSourceState::BuildResult(ExecutionContext &context, DataChunk &input, DataChunk &output, + DataChunk &result) const { idx_t out_idx = 0; - // input_chunk's cardinality is authoritative (its column buffers may still be a larger, stale capacity), so set the - // result cardinality explicitly here - before the references below alias input_chunk's/output_chunk's buffers. - result.SetChildCardinality(input_chunk.size()); - for (idx_t col_idx = 0; col_idx < input_chunk.ColumnCount(); col_idx++) { - result.data[out_idx++].Reference(input_chunk.data[col_idx]); + + // input_chunk's cardinality is authoritative (its column buffers may still be a larger, stale capacity), + // so set the result cardinality explicitly here - before the references below + // alias input_chunk's/output_chunk's buffers. + result.SetChildCardinality(input.size()); + for (idx_t col_idx = 0; col_idx < input.ColumnCount(); col_idx++) { + result.data[out_idx++].Reference(input.data[col_idx]); + } + for (idx_t col_idx = 0; col_idx < output.ColumnCount(); col_idx++) { + result.data[out_idx++].Reference(output.data[col_idx]); + } + + result.Verify(context.client.db); +} + +void WindowLocalSourceState::CoEvaluate(ExecutionContext &context, DataChunk &result, InterruptState &interrupt) { + const auto partition_limit = gsource.gsink.op.partition_limit; + const auto &partition_mask = window_hash_group->partition_mask; + const auto group_count = window_hash_group->count; + const auto k = partition_limit.GetIndex(); + idx_t n; + + output_chunk.Reset(); + + // Skip to the chunk that overlaps the next subrange + for (; task->begin_idx < task->end_idx; task->begin_idx++) { + // Read the next chunk + window_hash_group->UpdateScanner(scanner, task->begin_idx); + batch_index = window_hash_group->batch_base + task->begin_idx; + const auto input_base = scanner->Scanned(); + auto &input_chunk = scanner->chunk; + scanner->Scan(); + const auto input_count = input_chunk.size(); + const auto input_end = input_base + input_count; + + // Reset the partition start if we have a new task + if (partition_start == DConstants::INVALID_INDEX) { + n = 1; + partition_start = WindowBoundariesState::FindPrevStart(partition_mask, 0, input_base, n); + n = 1; + partition_end = WindowBoundariesState::FindNextStart(partition_mask, partition_start + 1, group_count, n); + } + auto limit_end = MinValue(partition_start + k, partition_end); + + // Lazy initialisation + if (!overlap_input.ColumnCount() && input_chunk.ColumnCount()) { + overlap_input.Initialize(gsource.client, input_chunk.GetTypes()); + } + + // Accumulate all the sub-partitions that intersect the chunk + // Profiling shows that a single call to Evaluate with gaps is preferable + // to repeated small ranges. This should be revisited when the strategies + // can implement the compaction during Sink and after we start allowing + // compatible function evaluation, some of which may be expensive. + idx_t overlap_count = 0; + idx_t span_begin = DConstants::INVALID_INDEX; + idx_t span_end = 0; + for (idx_t input_start = input_base; input_start < input_end; input_start = limit_end) { + // Scan forward until we have a limited partition that overlaps + while (limit_end <= input_start) { + n = 1; + partition_start = partition_end; + partition_end = + WindowBoundariesState::FindNextStart(partition_mask, partition_start + 1, group_count, n); + limit_end = MinValue(partition_start + k, partition_end); + } + if (partition_start >= input_end) { + break; + } + + // Copy the overlap to the limit buffers and evaluate + const auto overlap_begin = MaxValue(partition_start, input_start) - input_base; + const auto overlap_end = MinValue(limit_end, input_end) - input_base; + + // Fast track the entire input to avoid copying + if (overlap_begin == 0 && overlap_end == input_count) { + Evaluate(context, input_base, input_chunk, output_chunk, interrupt); + BuildResult(context, input_chunk, output_chunk, result); + ++task->begin_idx; + return; + } + + // Accumulate the overlap in an SV + span_begin = MinValue(span_begin, overlap_begin); + span_end = overlap_end; + for (auto i = overlap_begin; i < overlap_end; ++i) { + overlap_sel.set_index(overlap_count++, i - span_begin); + } + } + + // If we didn't find anything, move to the next chunk + if (!overlap_count) { + continue; + } + + overlap_input.Slice(input_chunk, span_begin, span_end); + Evaluate(context, input_base + span_begin, overlap_input, output_chunk, interrupt); + BuildResult(context, overlap_input, output_chunk, result); + if (overlap_count != span_end - span_begin) { + result.Slice(overlap_sel, overlap_count); + } + + // Move to the next chunk + ++task->begin_idx; + + return; } - for (idx_t col_idx = 0; col_idx < output_chunk.ColumnCount(); col_idx++) { - result.data[out_idx++].Reference(output_chunk.data[col_idx]); +} + +void WindowLocalSourceState::GetData(ExecutionContext &context, DataChunk &result, InterruptState &interrupt) { + D_ASSERT(window_hash_group->GetStage() == WindowGroupStage::GETDATA); + + // Apply co-evaluation with early stop + const auto partition_avg = LossyNumericCast(window_hash_group->count) / + LossyNumericCast(window_hash_group->partition_count.load()); + if (gsource.gsink.op.partition_limit.IsValid() && partition_avg < STANDARD_VECTOR_SIZE) { + CoEvaluate(context, result, interrupt); + return; } + window_hash_group->UpdateScanner(scanner, task->begin_idx); + batch_index = window_hash_group->batch_base + task->begin_idx; + + const auto position = scanner->Scanned(); + auto &input_chunk = scanner->chunk; + scanner->Scan(); + + output_chunk.Reset(); + + Evaluate(context, position, input_chunk, output_chunk, interrupt); + BuildResult(context, input_chunk, output_chunk, result); + // Move to the next chunk ++task->begin_idx; - - result.Verify(context.client.db); } unique_ptr PhysicalWindow::GetLocalSourceState(ExecutionContext &context, diff --git a/src/duckdb/src/execution/operator/csv_scanner/encode/csv_encoder.cpp b/src/duckdb/src/execution/operator/csv_scanner/encode/csv_encoder.cpp index 51a214bbe..1e56571fd 100644 --- a/src/duckdb/src/execution/operator/csv_scanner/encode/csv_encoder.cpp +++ b/src/duckdb/src/execution/operator/csv_scanner/encode/csv_encoder.cpp @@ -91,31 +91,31 @@ void CSVEncoder::Reset() { encoded_bytes_read = 0; } -idx_t CSVEncoder::Decode(const char *input, idx_t input_size, bool is_last, string &decoded) { +idx_t CSVEncoder::Decode(const char *input, idx_t input_size, bool is_last, Vector &result, string_t &decoded) { decode_input.Reset(); decode_input.SetChildCardinality(1); FlatVector::GetDataMutable(decode_input.data[0])[0] = string_t(input, UnsafeNumericCast(input_size)); FlatVector::GetDataMutable(decode_input.data[1])[0] = is_last; - Vector result(EncodingFunction::StreamResultType(), 1); decode_executor->ExecuteExpression(decode_input, result); auto values = result.Values>(); auto entry = values[0]; - auto decoded_value = entry.GetChildValue<0>().GetValue(); - decoded.assign(decoded_value.GetData(), decoded_value.GetSize()); + decoded = entry.GetChildValue<0>().GetValue(); return UnsafeNumericCast(entry.GetChildValue<1>().GetValue()); } idx_t CSVEncoder::DecodeBuffer(char *output_buffer, idx_t output_pos, idx_t output_size) { - string decoded; while (encoded_buffer.HasDataToRead() && output_pos < output_size) { const idx_t available = encoded_buffer.GetSize() - encoded_buffer.cur_pos; // Decode as much input as there is room in the output, extended until it holds a complete character - idx_t slice = MinValue(MaxValue(output_size - output_pos, minimum_input_window), available); + const idx_t room = MinValue(output_size - output_pos, MAX_DECODE_SLICE); + idx_t slice = MinValue(MaxValue(room, minimum_input_window), available); idx_t consumed = 0; + Vector result(EncodingFunction::StreamResultType(), 1); + string_t decoded; while (true) { const bool is_last = encoded_buffer.last_buffer && slice == available; - consumed = Decode(encoded_buffer.Ptr() + encoded_buffer.cur_pos, slice, is_last, decoded); + consumed = Decode(encoded_buffer.Ptr() + encoded_buffer.cur_pos, slice, is_last, result, decoded); if (consumed != 0 || slice == available) { break; } @@ -126,11 +126,11 @@ idx_t CSVEncoder::DecodeBuffer(char *output_buffer, idx_t output_pos, idx_t outp break; } encoded_buffer.cur_pos += consumed; - const idx_t to_copy = MinValue(decoded.size(), output_size - output_pos); - memcpy(output_buffer + output_pos, decoded.data(), to_copy); // NOLINT(bugprone-not-null-terminated-result) + const idx_t to_copy = MinValue(decoded.GetSize(), output_size - output_pos); + memcpy(output_buffer + output_pos, decoded.GetData(), to_copy); // NOLINT(bugprone-not-null-terminated-result) output_pos += to_copy; - if (to_copy < decoded.size()) { - pending_decoded.assign(decoded, to_copy, string::npos); + if (to_copy < decoded.GetSize()) { + pending_decoded.assign(decoded.GetData() + to_copy, decoded.GetSize() - to_copy); pending_pos = 0; } } diff --git a/src/duckdb/src/execution/operator/csv_scanner/scanner/string_value_scanner.cpp b/src/duckdb/src/execution/operator/csv_scanner/scanner/string_value_scanner.cpp index a4e073c42..ce5537dcf 100644 --- a/src/duckdb/src/execution/operator/csv_scanner/scanner/string_value_scanner.cpp +++ b/src/duckdb/src/execution/operator/csv_scanner/scanner/string_value_scanner.cpp @@ -1768,6 +1768,14 @@ StringValueScanner::MoveBufferResult StringValueScanner::TryMoveToNextBuffer() { result.current_line_position.begin = result.current_line_position.end; result.current_line_position.end = current_line_start; result.InvalidState(result); + if (!iterator.IsBoundarySet()) { + // without a boundary there is no FinishBoundaryScan to handle the error of this row + const auto chunk_col_id_before = result.chunk_col_id; + if (result.current_errors.HandleErrors(result)) { + result.InvalidateUnwrittenColumns(chunk_col_id_before); + result.number_of_rows++; + } + } } else { if (result.IsCommentSet(result)) { result.UnsetComment(result, iterator.pos.buffer_pos); diff --git a/src/duckdb/src/execution/operator/filter/physical_top_key_filter.cpp b/src/duckdb/src/execution/operator/filter/physical_top_key_filter.cpp new file mode 100644 index 000000000..f8f3938f4 --- /dev/null +++ b/src/duckdb/src/execution/operator/filter/physical_top_key_filter.cpp @@ -0,0 +1,295 @@ +#include "duckdb/execution/operator/filter/physical_top_key_filter.hpp" + +#include "duckdb/common/set.hpp" +#include "duckdb/common/sorting/topn_heap.hpp" +#include "duckdb/common/vector_operations/vector_operations.hpp" +#include "duckdb/execution/chunk_hasher.hpp" +#include "duckdb/execution/expression_executor.hpp" +#include "duckdb/function/create_sort_key.hpp" +#include "duckdb/parallel/thread_context.hpp" +#include "duckdb/planner/expression/bound_comparison_expression.hpp" +#include "duckdb/planner/filter/table_filter_functions.hpp" +#include "duckdb/storage/buffer_manager.hpp" + +namespace duckdb { + +PhysicalTopKeyFilter::PhysicalTopKeyFilter(PhysicalPlan &physical_plan, ClientContext &context, + vector types, vector orders_p, idx_t limit, + shared_ptr dynamic_filter_p, idx_t estimated_cardinality) + : PhysicalOperator(physical_plan, PhysicalOperatorType::TOP_KEY_FILTER, std::move(types), estimated_cardinality), + orders(std::move(orders_p)), limit(limit), dynamic_filter(std::move(dynamic_filter_p)) { + D_ASSERT(!orders.empty()); + const auto key_count = orders.size(); + for (idx_t key_idx = 0; key_idx < key_count; key_idx++) { + auto &type = orders[key_idx].expression->GetReturnType(); + not_distinct_from.push_back(BoundComparisonExpression::CreateOnColumns( + context, ExpressionType::COMPARE_NOT_DISTINCT_FROM, type, key_idx, type, key_count + key_idx)); + } +} + +PhysicalTopKeyFilter::~PhysicalTopKeyFilter() { +} + +//===--------------------------------------------------------------------===// +// Global State +//===--------------------------------------------------------------------===// +//! The bound shared by the threads: the smallest of the largest keys of the full local sets +class TopKeyFilterGlobalState : public GlobalOperatorState { +public: + explicit TopKeyFilterGlobalState(const PhysicalTopKeyFilter &op) : boundary(op.orders[0], op.dynamic_filter) { + } + + TopNBoundaryValue boundary; +}; + +//===--------------------------------------------------------------------===// +// Local State +//===--------------------------------------------------------------------===// +class TopKeyFilterState : public OperatorState { +public: + //! The number of key hashes that the cache of offered keys remembers + static constexpr idx_t SEEN_HASH_SLOTS = 4096; + //! After this many chunks without a change of the local set, a chunk is only offered to it when the number of + //! idle chunks has doubled. Skipping an offer delays the bound, it never makes the filter drop a row that it has + //! to keep. + static constexpr idx_t IDLE_WARMUP_CHUNKS = 16; + //! A thread offers keys to its set only after it has seen this many rows per key of the limit: filling the set + //! costs a sort key and an insert per distinct key, which a thread that sees few rows never earns back + static constexpr idx_t WARMUP_ROWS_PER_KEY = 256; + //! A thread that still passes more than one in INEFFECTIVE_PASS_FRACTION of this many rows stops filtering: the + //! limit covers too many of the keys for the filter to pay off + static constexpr idx_t INEFFECTIVE_CHECK_ROWS = idx_t(100) * STANDARD_VECTOR_SIZE; + static constexpr idx_t INEFFECTIVE_PASS_FRACTION = 8; + +public: + TopKeyFilterState(ExecutionContext &context, const PhysicalTopKeyFilter &op) + : op(op), executor(context.client), + selector(context.client, BufferManager::GetBufferManager(context.client).GetBufferAllocator(), op.orders, + op.not_distinct_from), + seen(SEEN_HASH_SLOTS, 0), hashes(LogicalType::HASH), pass_sel(STANDARD_VECTOR_SIZE), + candidate_sel(STANDARD_VECTOR_SIZE), new_sel(STANDARD_VECTOR_SIZE) { + vector key_types; + for (auto &order : op.orders) { + key_types.push_back(order.expression->GetReturnType()); + executor.AddExpression(*order.expression); + modifiers.emplace_back(order.type, order.null_order); + } + hasher = make_uniq(context.client, key_types); + auto &allocator = BufferManager::GetBufferManager(context.client).GetBufferAllocator(); + key_chunk.Initialize(allocator, key_types); + local_max_values.Initialize(allocator, key_types); + candidates.Initialize(allocator, key_types, vector(key_types.size(), false)); + sort_key_chunk.Initialize(allocator, {LogicalType::BLOB}); + } + + const PhysicalTopKeyFilter &op; + ExpressionExecutor executor; + vector modifiers; + //! The keys of the current input chunk + DataChunk key_chunk; + //! The global bound as this thread last saw it, and the selection of the rows up to a bound. A bound that is older + //! than the global one sorts after it: it only lets more rows pass. + TopNBoundarySelector selector; + //! The smallest "limit" distinct sort keys that this thread has seen, and the largest of them as constant vectors + set heap; + DataChunk local_max_values; + //! The hashes of keys that were offered to the set: a hit skips the sort key (a collision only skips an offer) + vector seen; + unique_ptr hasher; + Vector hashes; + DataChunk candidates; + DataChunk sort_key_chunk; + //! The number of chunks since the local set last changed + idx_t idle_chunks = 0; + //! The number of rows that this thread has seen + idx_t rows_seen = 0; + //! The number of rows that this thread has compared with the bound, and how many of them passed + idx_t checked_rows = 0; + idx_t passed_rows = 0; + //! Whether this thread has stopped filtering + bool pass_through = false; + + SelectionVector pass_sel; + SelectionVector candidate_sel; + SelectionVector new_sel; + +public: + void Finalize(const PhysicalOperator &op, ExecutionContext &context) override { + context.thread.profiler.Flush(op); + } + + //! Offers the rows that passed (sel, or the whole chunk) to the local set and publishes a changed bound + void MaintainHeap(optional_ptr sel, idx_t count, TopKeyFilterGlobalState &gstate) { + if (count == 0) { + return; + } + if (idle_chunks >= IDLE_WARMUP_CHUNKS && !IsPowerOfTwo(idle_chunks)) { + idle_chunks++; + return; + } + // the rows that can change the set: all of them while it is not full, or else those before its largest key + const auto is_full = heap.size() >= op.limit; + auto candidate_count = count; + auto candidates_sel = sel; + if (is_full) { + // strictly before the largest key of the set: an equal key is in the set already + candidate_count = selector.Select(key_chunk, local_max_values, sel, count, TopNBoundaryTies::EXCLUDE, + TopNBoundaryRowOrder::ANY, candidate_sel); + candidates_sel = &candidate_sel; + } + if (candidate_count == 0) { + idle_chunks++; + return; + } + // skip the keys that have been offered before + hasher->Hash(key_chunk, hashes); + hashes.Flatten(); + auto hash_data = FlatVector::GetData(hashes); + idx_t new_count = 0; + for (idx_t i = 0; i < candidate_count; i++) { + const auto row = candidates_sel ? candidates_sel->get_index(i) : i; + const auto hash = hash_data[row]; + auto &slot = seen[hash & (SEEN_HASH_SLOTS - 1)]; + // an empty slot is 0, as is the hash of an integer 0: a zero hash is never remembered + if (hash != 0 && slot == hash) { + continue; + } + slot = hash; + new_sel.set_index(new_count++, row); + } + if (new_count == 0) { + idle_chunks++; + return; + } + // create the sort keys of the new rows + candidates.Reset(); + candidates.Slice(key_chunk, new_sel, new_count); + sort_key_chunk.Reset(); + CreateSortKeyHelpers::CreateSortKey(candidates, modifiers, sort_key_chunk.data[0]); + auto sort_keys = FlatVector::GetData(sort_key_chunk.data[0]); + bool changed = false; + for (idx_t i = 0; i < new_count; i++) { + auto sort_key = sort_keys[i].GetString(); + if (heap.size() >= op.limit && sort_key >= *heap.rbegin()) { + continue; + } + if (!heap.insert(std::move(sort_key)).second) { + continue; + } + changed = true; + if (heap.size() > op.limit) { + heap.erase(std::prev(heap.end())); + } + } + if (!changed) { + idle_chunks++; + return; + } + idle_chunks = 0; + if (heap.size() >= op.limit) { + auto &local_max = *heap.rbegin(); + selector.Decode(local_max, local_max_values); + gstate.boundary.UpdateValue(string_t(local_max)); + } + } +}; + +void PhysicalTopKeyFilter::InitializeOutputChunk(Allocator &allocator, DataChunk &chunk) const { + // every output column only references or slices the input + chunk.Initialize(allocator, types, vector(types.size(), false)); +} + +unique_ptr PhysicalTopKeyFilter::GetOperatorState(ExecutionContext &context) const { + return make_uniq(context, *this); +} + +unique_ptr PhysicalTopKeyFilter::GetGlobalOperatorState(ClientContext &context) const { + // a new bound for every execution + if (dynamic_filter) { + dynamic_filter->Reset(); + } + return make_uniq(*this); +} + +OperatorResultType PhysicalTopKeyFilter::Execute(ExecutionContext &context, DataChunk &input, DataChunk &chunk, + GlobalOperatorState &gstate_p, OperatorState &state_p) const { + auto &gstate = gstate_p.Cast(); + auto &state = state_p.Cast(); + const auto count = input.size(); + if (count == 0) { + return OperatorResultType::NEED_MORE_INPUT; + } + if (state.pass_through) { + // contract: passing a row is always allowed + chunk.Reference(input); + return OperatorResultType::NEED_MORE_INPUT; + } + state.rows_seen += count; + const auto warming_up = state.rows_seen <= TopKeyFilterState::WARMUP_ROWS_PER_KEY * limit; + const auto has_boundary = state.selector.Refresh(gstate.boundary); + if (warming_up && !has_boundary) { + // no bound to filter with and no key to offer yet: the rows pass as they are (contract: extra rows may pass) + chunk.Reference(input); + return OperatorResultType::NEED_MORE_INPUT; + } + state.key_chunk.Reset(); + state.executor.Execute(input, state.key_chunk); + + // the rows up to the global bound, as far as this thread knows it + idx_t pass_count = count; + if (has_boundary) { + // the rows of the bound key itself pass (it is the key of a group that can be returned), in the order of the + // input (the aggregate may depend on it) + pass_count = + state.selector.Select(state.key_chunk, state.selector.BoundaryValues(), nullptr, count, + TopNBoundaryTies::INCLUDE, TopNBoundaryRowOrder::INPUT_ORDER, state.pass_sel); + if (!dynamic_filter && !warming_up) { + // without a dynamic filter in the scans this operator sees every row: if too many of them pass, the + // filter costs more than the aggregate saves. Passing every row is always correct. Every compared chunk + // counts, also one that is rejected as a whole (clustered input). + state.checked_rows += count; + state.passed_rows += pass_count; + if (state.checked_rows >= TopKeyFilterState::INEFFECTIVE_CHECK_ROWS) { + state.pass_through = + state.passed_rows > state.checked_rows / TopKeyFilterState::INEFFECTIVE_PASS_FRACTION; + state.checked_rows = 0; + state.passed_rows = 0; + } + } + if (pass_count == 0) { + return OperatorResultType::NEED_MORE_INPUT; + } + } + const auto filtered = pass_count < count; + // offer the rows that pass to the local set. A row after the bound cannot enter it, and a thread that is still + // warming up only filters with the bound of the other threads. + if (!warming_up) { + state.MaintainHeap(filtered ? &state.pass_sel : nullptr, pass_count, gstate); + } + if (filtered) { + chunk.Slice(input, state.pass_sel, pass_count); + } else { + chunk.Reference(input); + } + return OperatorResultType::NEED_MORE_INPUT; +} + +InsertionOrderPreservingMap PhysicalTopKeyFilter::ParamsToString() const { + InsertionOrderPreservingMap result; + string keys; + for (idx_t i = 0; i < orders.size(); i++) { + if (i > 0) { + keys += "\n"; + } + keys += orders[i].ToString(); + } + result["Keys"] = keys; + result["Limit"] = to_string(limit); + if (dynamic_filter) { + result["Dynamic Filter"] = "true"; + } + SetEstimatedCardinality(result, estimated_cardinality); + return result; +} + +} // namespace duckdb diff --git a/src/duckdb/src/execution/operator/helper/physical_update_extensions.cpp b/src/duckdb/src/execution/operator/helper/physical_update_extensions.cpp index d4232942a..6150aa9db 100644 --- a/src/duckdb/src/execution/operator/helper/physical_update_extensions.cpp +++ b/src/duckdb/src/execution/operator/helper/physical_update_extensions.cpp @@ -1,12 +1,33 @@ #include "duckdb/execution/operator/helper/physical_update_extensions.hpp" #include "duckdb/main/extension_helper.hpp" +#include "duckdb/parallel/callback_async_task.hpp" namespace duckdb { +//! Runs the pending updates as async tasks: BLOCKED while they run, HAVE_MORE_OUTPUT when they ran synchronously +static SourceResultType ScheduleUpdates(ExecutionContext &context, UpdateExtensionsGlobalState &data, + OperatorSourceInput &input) { + auto &client = context.client; + vector> tasks; + for (auto &pending : data.pending_updates) { + auto &result = data.update_result_entries[pending.result_index]; + tasks.push_back(make_uniq( + [&client, &pending, &result]() { ExtensionHelper::ExecuteExtensionUpdate(client, pending, result); })); + } + return AsyncResult::FromTasks(std::move(tasks), TaskSchedulerType::ASYNC).ScheduleOrExecute(context, input, data); +} + SourceResultType PhysicalUpdateExtensions::GetDataInternal(ExecutionContext &context, DataChunk &chunk, OperatorSourceInput &input) const { auto &data = input.global_state.Cast(); + if (!data.updates_scheduled) { + data.updates_scheduled = true; + if (!data.pending_updates.empty()) { + return ScheduleUpdates(context, data, input); + } + } + if (data.offset >= data.update_result_entries.size()) { // finished returning values return SourceResultType::FINISHED; @@ -24,6 +45,8 @@ SourceResultType PhysicalUpdateExtensions::GetDataInternal(ExecutionContext &con auto &previous_version = chunk.data[3]; // current_version VARCHAR auto ¤t_version = chunk.data[4]; + // error VARCHAR + auto &error = chunk.data[5]; while (data.offset < data.update_result_entries.size() && count < STANDARD_VECTOR_SIZE) { auto &entry = data.update_result_entries[data.offset]; @@ -33,6 +56,11 @@ SourceResultType PhysicalUpdateExtensions::GetDataInternal(ExecutionContext &con update_result.Append(Value(EnumUtil::ToString(entry.tag))); previous_version.Append(Value(entry.prev_version)); current_version.Append(Value(entry.installed_version)); + if (entry.tag == ExtensionUpdateResultTag::UPDATE_FAILED) { + error.Append(Value(entry.error)); + } else { + error.Append(Value(LogicalType::VARCHAR)); + } data.offset++; count++; @@ -47,11 +75,12 @@ unique_ptr PhysicalUpdateExtensions::GetGlobalSourceState(Cli if (info->extensions_to_update.empty()) { // Update all - res->update_result_entries = ExtensionHelper::UpdateExtensions(context); + ExtensionHelper::PrepareExtensionUpdates(context, res->update_result_entries, res->pending_updates); } else { // Update extensions in extensions_to_update for (const auto &ext : info->extensions_to_update) { - res->update_result_entries.emplace_back(ExtensionHelper::UpdateExtension(context, ext.GetIdentifierName())); + ExtensionHelper::PrepareExtensionUpdate(context, ext.GetIdentifierName(), res->update_result_entries, + res->pending_updates); } } diff --git a/src/duckdb/src/execution/operator/persistent/physical_insert.cpp b/src/duckdb/src/execution/operator/persistent/physical_insert.cpp index 7fc9c09c7..4778019b8 100644 --- a/src/duckdb/src/execution/operator/persistent/physical_insert.cpp +++ b/src/duckdb/src/execution/operator/persistent/physical_insert.cpp @@ -418,7 +418,7 @@ static void VerifyOnConflictCondition(ExecutionContext &context, DataChunk &comb auto &indexes = local_storage.GetIndexes(context.client.GetContext(), data_table); auto storage = local_storage.GetStorage(data_table); - indexes.VerifyUniqueIndexes(storage ? &storage->delete_indexes : nullptr, tuples, nullptr); + indexes.VerifyUniqueIndexes(storage ? &storage->GetDeleteIndexes() : nullptr, tuples, nullptr); throw InternalException("VerifyUniqueIndexes was expected to throw but didn't"); } @@ -440,7 +440,7 @@ static idx_t HandleInsertConflicts(DuckTableEntry &table, ExecutionContext &cont data_table.VerifyAppendConstraints(constraint_state, context.client, tuples, storage, &conflict_manager); } else { auto &indexes = local_storage.GetIndexes(context.client.GetContext(), data_table); - indexes.VerifyUniqueIndexes(storage ? &storage->delete_indexes : nullptr, tuples, &conflict_manager); + indexes.VerifyUniqueIndexes(storage ? &storage->GetDeleteIndexes() : nullptr, tuples, &conflict_manager); } if (!conflict_manager.HasConflicts()) { diff --git a/src/duckdb/src/execution/operator/persistent/physical_update.cpp b/src/duckdb/src/execution/operator/persistent/physical_update.cpp index 67ee1afb8..b83092b97 100644 --- a/src/duckdb/src/execution/operator/persistent/physical_update.cpp +++ b/src/duckdb/src/execution/operator/persistent/physical_update.cpp @@ -506,4 +506,12 @@ SourceResultType PhysicalUpdate::GetDataInternal(ExecutionContext &context, Data return chunk.size() == 0 ? SourceResultType::FINISHED : SourceResultType::HAVE_MORE_OUTPUT; } +InsertionOrderPreservingMap PhysicalUpdate::ParamsToString() const { + InsertionOrderPreservingMap result; + result["Table"] = + tableref.schema.GetQualifiedName(tableref.name).ToString(QualifiedNameToStringMode::HIDE_DEFAULT_SCHEMA); + result["Update Mode"] = update_is_del_and_insert ? "Delete + Insert" : "In Place"; + return result; +} + } // namespace duckdb diff --git a/src/duckdb/src/execution/operator/scan/physical_expression_scan.cpp b/src/duckdb/src/execution/operator/scan/physical_expression_scan.cpp index bdc286942..703eb8a83 100644 --- a/src/duckdb/src/execution/operator/scan/physical_expression_scan.cpp +++ b/src/duckdb/src/execution/operator/scan/physical_expression_scan.cpp @@ -45,7 +45,7 @@ OperatorResultType PhysicalExpressionScan::Execute(ExecutionContext &context, Da for (; chunk.size() + input.size() <= STANDARD_VECTOR_SIZE && state.expression_index < expressions.size(); state.expression_index++) { state.temp_chunk.Reset(); - EvaluateExpression(context.client, state.expression_index, &input, chunk, &state.temp_chunk); + EvaluateExpression(context.client, state.expression_index, &input, chunk, state.temp_chunk); } if (state.expression_index < expressions.size()) { return OperatorResultType::HAVE_MORE_OUTPUT; @@ -57,19 +57,7 @@ OperatorResultType PhysicalExpressionScan::Execute(ExecutionContext &context, Da void PhysicalExpressionScan::EvaluateExpression(ClientContext &context, idx_t expression_idx, optional_ptr child_chunk, DataChunk &result, - optional_ptr temp_chunk_ptr) const { - if (temp_chunk_ptr) { - EvaluateExpressionInternal(context, expression_idx, child_chunk, result, *temp_chunk_ptr); - } else { - DataChunk temp_chunk; - temp_chunk.Initialize(Allocator::Get(context), GetTypes()); - EvaluateExpressionInternal(context, expression_idx, child_chunk, result, temp_chunk); - } -} - -void PhysicalExpressionScan::EvaluateExpressionInternal(ClientContext &context, idx_t expression_idx, - optional_ptr child_chunk, DataChunk &result, - DataChunk &temp_chunk) const { + DataChunk &temp_chunk) const { ExpressionExecutor executor(context, expressions[expression_idx]); if (child_chunk) { child_chunk->Verify(context.db); diff --git a/src/duckdb/src/execution/operator/scan/physical_table_scan.cpp b/src/duckdb/src/execution/operator/scan/physical_table_scan.cpp index 2ae0bfd0d..03964e4f6 100644 --- a/src/duckdb/src/execution/operator/scan/physical_table_scan.cpp +++ b/src/duckdb/src/execution/operator/scan/physical_table_scan.cpp @@ -198,15 +198,7 @@ SourceResultType PhysicalTableScan::GetDataInternal(ExecutionContext &context, D // the function parked return SourceResultType::BLOCKED; } - if (input.interrupt_state.CanCallback()) { - annotated_lock_guard guard(g_state.lock); - if (g_state.CanBlock()) { - data.async_result.ScheduleTasks(input.interrupt_state, context.pipeline->executor); - return SourceResultType::BLOCKED; - } - } - data.async_result.ExecuteTasksSynchronously(context.client); - return SourceResultType::HAVE_MORE_OUTPUT; + return data.async_result.ScheduleOrExecute(context, input, g_state); } return AsyncResult::GetSourceResultType(output_async_result, chunk.size()); } diff --git a/src/duckdb/src/execution/operator/schema/physical_create_index.cpp b/src/duckdb/src/execution/operator/schema/physical_create_index.cpp index 2cf929850..bed7ee669 100644 --- a/src/duckdb/src/execution/operator/schema/physical_create_index.cpp +++ b/src/duckdb/src/execution/operator/schema/physical_create_index.cpp @@ -134,8 +134,6 @@ SinkFinalizeType PhysicalCreateIndex::Finalize(Pipeline &pipeline, Event &event, bound_index->Verify(); - D_ASSERT(!bound_index->ToString(true).empty()); - bound_index->VerifyAllocations(); auto &storage = table.GetStorage(); @@ -191,7 +189,7 @@ SinkFinalizeType PhysicalCreateIndex::Finalize(Pipeline &pipeline, Event &event, auto index_entry = storage.GetDataTableInfo()->GetIndexes().AddIndex(std::move(bound_index), index_oid, check_mode); if (local_table_storage) { // Existing transaction-local rows are verified when committing, so we only add a delete index. - index_entry->InitializeLocalDeleteIndex(local_table_storage->delete_indexes); + index_entry->InitializeLocalDeleteIndex(local_table_storage->GetDeleteIndexes()); } return SinkFinalizeType::READY; diff --git a/src/duckdb/src/execution/physical_plan/plan_aggregate.cpp b/src/duckdb/src/execution/physical_plan/plan_aggregate.cpp index b5c6dcf10..244d1d8d5 100644 --- a/src/duckdb/src/execution/physical_plan/plan_aggregate.cpp +++ b/src/duckdb/src/execution/physical_plan/plan_aggregate.cpp @@ -84,7 +84,8 @@ bool PhysicalPlanGenerator::HasSingleValuePartitions(ClientContext &context, break; } case PhysicalOperatorType::FILTER: - // continue into child operators + case PhysicalOperatorType::TOP_KEY_FILTER: + // these operators only remove rows and forward every column: continue into child operators child_ref = child_op.children[0]; break; default: diff --git a/src/duckdb/src/execution/physical_plan/plan_expression_get.cpp b/src/duckdb/src/execution/physical_plan/plan_expression_get.cpp index 62aaacccd..1765755bd 100644 --- a/src/duckdb/src/execution/physical_plan/plan_expression_get.cpp +++ b/src/duckdb/src/execution/physical_plan/plan_expression_get.cpp @@ -28,12 +28,20 @@ PhysicalOperator &PhysicalPlanGenerator::CreatePlan(LogicalExpressionGet &op) { DataChunk chunk; chunk.Initialize(allocator, op.types); + DataChunk temp_chunk; + temp_chunk.Initialize(allocator, op.types); ColumnDataAppendState append_state; cast_chunk_scan.collection->InitializeAppend(append_state); for (idx_t expression_idx = 0; expression_idx < cast_expr_scan.expressions.size(); expression_idx++) { - chunk.Reset(); - cast_expr_scan.EvaluateExpression(context, expression_idx, nullptr, chunk); + if (chunk.size() == STANDARD_VECTOR_SIZE) { + cast_chunk_scan.collection->Append(append_state, chunk); + chunk.Reset(); + } + temp_chunk.Reset(); + cast_expr_scan.EvaluateExpression(context, expression_idx, nullptr, chunk, temp_chunk); + } + if (chunk.size() > 0) { cast_chunk_scan.collection->Append(append_state, chunk); } return chunk_scan; diff --git a/src/duckdb/src/execution/physical_plan/plan_limit.cpp b/src/duckdb/src/execution/physical_plan/plan_limit.cpp index 684b2b82d..9aa6e8374 100644 --- a/src/duckdb/src/execution/physical_plan/plan_limit.cpp +++ b/src/duckdb/src/execution/physical_plan/plan_limit.cpp @@ -8,7 +8,6 @@ #include "duckdb/execution/operator/projection/physical_projection.hpp" #include "duckdb/execution/operator/scan/physical_table_scan.hpp" #include "duckdb/execution/physical_plan_generator.hpp" -#include "duckdb/logging/logger.hpp" #include "duckdb/main/config.hpp" #include "duckdb/planner/operator/logical_limit.hpp" @@ -177,11 +176,7 @@ PhysicalOperator &PhysicalPlanGenerator::CreatePlan(LogicalLimit &op) { auto total_limit = GetLimit(op.limit_val, op.offset_val); bool zero_offset = op.offset_val.Type() == LimitNodeType::CONSTANT_VALUE && op.offset_val.GetConstantValue() == 0; if (op.offset_val.Type() != LimitNodeType::UNSET && !zero_offset && !PreserveInsertionOrder(plan)) { - DUCKDB_LOG_WARNING(context, - "OFFSET is applied to a query whose row order is not guaranteed - the result may " - "differ between runs. This happens when the query contains order-breaking operators (e.g. " - "hash joins or aggregations), reads from a source that does not preserve order, or when " - "preserve_insertion_order=false. Add an ORDER BY to make the result deterministic."); + LogicalLimit::WarnUnorderedOffset(context); } // Unpartitioned hash tables become expensive to Combine at large sizes static constexpr idx_t LIMITED_DISTINCT_THRESHOLD = 100000; diff --git a/src/duckdb/src/execution/physical_plan/plan_top_key_filter.cpp b/src/duckdb/src/execution/physical_plan/plan_top_key_filter.cpp new file mode 100644 index 000000000..dd82a013e --- /dev/null +++ b/src/duckdb/src/execution/physical_plan/plan_top_key_filter.cpp @@ -0,0 +1,16 @@ +#include "duckdb/execution/operator/filter/physical_top_key_filter.hpp" +#include "duckdb/execution/physical_plan_generator.hpp" +#include "duckdb/planner/operator/logical_top_key_filter.hpp" + +namespace duckdb { + +PhysicalOperator &PhysicalPlanGenerator::CreatePlan(LogicalTopKeyFilter &op) { + D_ASSERT(op.children.size() == 1); + auto &plan = CreatePlan(*op.children[0]); + auto &filter = Make(context, op.types, std::move(op.orders), op.limit, + std::move(op.dynamic_filter), op.estimated_cardinality); + filter.children.push_back(plan); + return filter; +} + +} // namespace duckdb diff --git a/src/duckdb/src/execution/physical_plan_generator.cpp b/src/duckdb/src/execution/physical_plan_generator.cpp index 1acf4ba32..8c9d2723d 100644 --- a/src/duckdb/src/execution/physical_plan_generator.cpp +++ b/src/duckdb/src/execution/physical_plan_generator.cpp @@ -105,6 +105,8 @@ PhysicalOperator &PhysicalPlanGenerator::CreatePlanInternal(LogicalOperator &op) return CreatePlan(op.Cast()); case LogicalOperatorType::LOGICAL_TOP_N: return CreatePlan(op.Cast()); + case LogicalOperatorType::LOGICAL_TOP_KEY_FILTER: + return CreatePlan(op.Cast()); case LogicalOperatorType::LOGICAL_COPY_TO_FILE: return CreatePlan(op.Cast()); case LogicalOperatorType::LOGICAL_DUMMY_SCAN: diff --git a/src/duckdb/src/function/builtin_encodings.cpp b/src/duckdb/src/function/builtin_encodings.cpp index 299fda45b..32661f004 100644 --- a/src/duckdb/src/function/builtin_encodings.cpp +++ b/src/duckdb/src/function/builtin_encodings.cpp @@ -10,11 +10,37 @@ namespace duckdb { namespace { +#if defined(__BYTE_ORDER__) && __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__ && (defined(__GNUC__) || defined(__clang__)) +#define ENCODING_FAST_PATH 1 +#endif + void DecodeLatin1ToUTF8(const char *input, idx_t input_size, bool is_last, char *output, idx_t &consumed, idx_t &written) { idx_t out = 0; - for (idx_t i = 0; i < input_size; i++) { - const auto ch = static_cast(input[i]); + idx_t i = 0; + while (i < input_size) { +#ifdef ENCODING_FAST_PATH + // Copy 8 ASCII bytes at a time + while (i + 8 <= input_size) { + uint64_t word; + memcpy(&word, input + i, sizeof(word)); + const uint64_t high_bits = word & 0x8080808080808080ULL; + // Copy the whole word, but only advance past the ASCII prefix + memcpy(output + out, &word, sizeof(word)); + if (high_bits) { + const idx_t ascii_prefix = static_cast(__builtin_ctzll(high_bits)) / 8; + i += ascii_prefix; + out += ascii_prefix; + break; + } + i += 8; + out += 8; + } + if (i >= input_size) { + break; + } +#endif + const auto ch = static_cast(input[i++]); if (ch > 0x7F && ch <= 0x9F) { throw InvalidInputException("File is not latin-1 encoded"); } @@ -114,6 +140,31 @@ void DecodeUTF16ToUTF8(const char *input, idx_t input_size, bool is_last, char * idx_t pos = 0; idx_t out = 0; while (pos < input_size) { +#ifdef ENCODING_FAST_PATH + // Narrow 4 ASCII code units at a time + while (pos + 8 <= input_size) { + uint64_t word; + memcpy(&word, input + pos, sizeof(word)); + const uint64_t high_bits = word & 0xFF80FF80FF80FF80ULL; + // Narrow the whole word, but only advance past the ASCII prefix + uint64_t narrow = word & 0x00FF00FF00FF00FFULL; + narrow = (narrow | (narrow >> 8)) & 0x0000FFFF0000FFFFULL; + narrow = (narrow | (narrow >> 16)) & 0x00000000FFFFFFFFULL; + const auto narrowed = static_cast(narrow); + memcpy(output + out, &narrowed, sizeof(narrowed)); + if (high_bits) { + const idx_t ascii_units = static_cast(__builtin_ctzll(high_bits)) / 16; + pos += ascii_units * 2; + out += ascii_units; + break; + } + pos += 8; + out += 4; + } + if (pos >= input_size) { + break; + } +#endif if (pos + 1 >= input_size) { if (is_last) { throw InvalidInputException("Input is not valid UTF-16"); diff --git a/src/duckdb/src/function/cast/nested_to_varchar_cast.cpp b/src/duckdb/src/function/cast/nested_to_varchar_cast.cpp index 7e7298b4f..97923ecfe 100644 --- a/src/duckdb/src/function/cast/nested_to_varchar_cast.cpp +++ b/src/duckdb/src/function/cast/nested_to_varchar_cast.cpp @@ -102,7 +102,7 @@ void GetUnquotedRows(const Vector &source, idx_t count, vector &is_unquote continue; } auto type_id = value.GetTypeId(); - is_unquoted[i] = type_id == VariantLogicalType::OBJECT || type_id == VariantLogicalType::ARRAY; + is_unquoted[i] = type_id == LogicalTypeId::STRUCT || type_id == LogicalTypeId::LIST; } } diff --git a/src/duckdb/src/function/cast/variant/from_variant.cpp b/src/duckdb/src/function/cast/variant/from_variant.cpp index e41dd96df..ecdecd919 100644 --- a/src/duckdb/src/function/cast/variant/from_variant.cpp +++ b/src/duckdb/src/function/cast/variant/from_variant.cpp @@ -528,7 +528,7 @@ class VariantVarcharSerializer { static bool VisitBitstring(const string_t &, VariantVarcharSerializer &, bool) { return false; } - static bool VisitDefault(VariantLogicalType, const_data_ptr_t, VariantVarcharSerializer &, bool) { + static bool VisitDefault(const LogicalType &, const_data_ptr_t, VariantVarcharSerializer &, bool) { return false; } diff --git a/src/duckdb/src/function/cast/variant/to_json.cpp b/src/duckdb/src/function/cast/variant/to_json.cpp index f6dc3940f..640b9f03e 100644 --- a/src/duckdb/src/function/cast/variant/to_json.cpp +++ b/src/duckdb/src/function/cast/variant/to_json.cpp @@ -161,8 +161,8 @@ struct JSONConverterBase { return yyjson_mut_rawncpy(doc, val_str.c_str(), val_str.size()); } - static yyjson_mut_val *VisitDefault(VariantLogicalType type_id, const_data_ptr_t, yyjson_mut_doc *) { - throw InternalException("VariantLogicalType(%s) not handled", EnumUtil::ToString(type_id)); + static yyjson_mut_val *VisitDefault(const LogicalType &type, const_data_ptr_t, yyjson_mut_doc *) { + throw InternalException("VariantLogicalType(%s) not handled", type.ToString()); } }; diff --git a/src/duckdb/src/function/function_list.cpp b/src/duckdb/src/function/function_list.cpp index ae4eea669..9ca5a91bd 100644 --- a/src/duckdb/src/function/function_list.cpp +++ b/src/duckdb/src/function/function_list.cpp @@ -171,6 +171,7 @@ static const StaticFunctionDefinition function[] = { DUCKDB_SCALAR_FUNCTION_SET_ALIAS(DivideFun), DUCKDB_SCALAR_FUNCTION_ALIAS(EndsWithFun), DUCKDB_SCALAR_FUNCTION(ErrorFun), + DUCKDB_SCALAR_FUNCTION(ExtensionRepositoryUrl), DUCKDB_WINDOW_FUNCTION(FillFun), DUCKDB_SCALAR_FUNCTION(FinalizeFun), DUCKDB_AGGREGATE_FUNCTION_SET(FirstFun), diff --git a/src/duckdb/src/function/scalar/system/extension_repository_url.cpp b/src/duckdb/src/function/scalar/system/extension_repository_url.cpp new file mode 100644 index 000000000..8003e48e7 --- /dev/null +++ b/src/duckdb/src/function/scalar/system/extension_repository_url.cpp @@ -0,0 +1,68 @@ +#include "duckdb/function/scalar/system_functions.hpp" + +#include "duckdb/common/vector_operations/unary_executor.hpp" +#include "duckdb/main/client_context.hpp" +#include "duckdb/main/database.hpp" +#include "duckdb/main/extension_repository_manager.hpp" +#include "duckdb/planner/expression/bound_function_expression.hpp" + +namespace duckdb { + +namespace { + +//! The connection is captured at bind time: reading what a host publishes is an https request, which takes the +//! settings and secrets of the connection that asks for it +struct ExtensionRepositoryUrlBindData : FunctionData { + explicit ExtensionRepositoryUrlBindData(ClientContext &context_p) : context(context_p) { + } + + ClientContext &context; + + unique_ptr Copy() const override { + return make_uniq(context); + } + bool Equals(const FunctionData &other_p) const override { + auto &other = other_p.Cast(); + return &context == &other.context; + } +}; + +unique_ptr ExtensionRepositoryUrlBind(BindScalarFunctionInput &input) { + return make_uniq(input.GetClientContext()); +} + +void ExtensionRepositoryUrlFunction(DataChunk &args, ExpressionState &state, Vector &result) { + auto &func_expr = state.expr.Cast(); + const auto &info = func_expr.BindInfo()->Cast(); + auto &context = info.context; + auto &db = DatabaseInstance::GetDatabase(context); + + // every host costs a request, so a host that repeats within the chunk is resolved once. Nothing is remembered + // beyond it: the function is volatile, and what a host publishes is its to change + unordered_map resolved; + UnaryExecutor::Execute(args.data[0], result, args.size(), [&](string_t host) { + auto name = host.GetString(); + auto entry = resolved.find(name); + if (entry == resolved.end()) { + auto resolution = ExtensionRepositoryManager::ResolveRepositoryFromHost( + db, context, name, ExtensionRepositoryHostCaller::LOOKUP); + entry = resolved.emplace(std::move(name), std::move(resolution.url)).first; + } + return StringVector::AddString(result, entry->second); + }); +} + +} // namespace + +ScalarFunction ExtensionRepositoryUrl::GetFunction() { + // the parameter is declared by name: duckdb_functions() lists signatures, and an undeclared one shows as col0 + ScalarFunction function({FunctionParameter(Identifier("host"), LogicalType::VARCHAR)}, LogicalType::VARCHAR, + ExtensionRepositoryUrlFunction, ExtensionRepositoryUrlBind, nullptr, nullptr, + LogicalType(LogicalTypeId::INVALID), FunctionStability::VOLATILE); + // a name that is not a host, a host that cannot be reached or a file that is not what it should be are all errors + // of the call, raised while it runs + function.SetFallible(); + return function; +} + +} // namespace duckdb diff --git a/src/duckdb/src/function/scalar/variant/variant_array_length.cpp b/src/duckdb/src/function/scalar/variant/variant_array_length.cpp index 74f22b2bd..a6e0a24f6 100644 --- a/src/duckdb/src/function/scalar/variant/variant_array_length.cpp +++ b/src/duckdb/src/function/scalar/variant/variant_array_length.cpp @@ -10,7 +10,7 @@ static void WriteArrayLengthsResult(const optional &node, VectorWri length_writer.WriteNull(); return; } - if (node->GetTypeId() != VariantLogicalType::ARRAY) { + if (node->GetTypeId() != LogicalTypeId::LIST) { length_writer.WriteValue(0); return; } diff --git a/src/duckdb/src/function/scalar/variant/variant_comparator.cpp b/src/duckdb/src/function/scalar/variant/variant_comparator.cpp index 8ea0535ed..0cc38584c 100644 --- a/src/duckdb/src/function/scalar/variant/variant_comparator.cpp +++ b/src/duckdb/src/function/scalar/variant/variant_comparator.cpp @@ -45,7 +45,7 @@ constexpr data_t BLOB_ESCAPE_CHARACTER = 1; constexpr data_t BIT_SORT_KEY_ZERO = 2; constexpr data_t BIT_SORT_KEY_ONE = 3; -data_t GetVariantTypeRank(const VariantLogicalType type_id) { +data_t GetVariantTypeRank(const LogicalTypeId type_id) { return static_cast(GetVariantComparisonType(type_id)); } @@ -154,7 +154,7 @@ bool EncodeVariantNode(const VariantNode &it, SINK &sink, vectorGetOrderedEntries(); while (frame.next_child < entries.size()) { auto entry = entries[frame.next_child++]; diff --git a/src/duckdb/src/function/scalar/variant/variant_contains.cpp b/src/duckdb/src/function/scalar/variant/variant_contains.cpp index ec7eb410b..a5da15141 100644 --- a/src/duckdb/src/function/scalar/variant/variant_contains.cpp +++ b/src/duckdb/src/function/scalar/variant/variant_contains.cpp @@ -28,18 +28,18 @@ struct VariantNeedle { } VariantNode node; - VariantLogicalType type_id; + LogicalTypeId type_id; VariantComparisonType category; optional number_key; }; //! Whether two primitive values of the same comparison category are equal -bool IsPrimitiveEqual(const VariantNode &haystack, VariantLogicalType haystack_type, VariantNeedle &needle) { +bool IsPrimitiveEqual(const VariantNode &haystack, LogicalTypeId haystack_type, VariantNeedle &needle) { switch (needle.category) { case VariantComparisonType::NULL_VALUE: return true; case VariantComparisonType::BOOLEAN: - return haystack_type == needle.type_id; + return haystack.GetBool() == needle.node.GetBool(); case VariantComparisonType::UUID: return haystack.GetData() == needle.node.GetData(); case VariantComparisonType::REAL: @@ -217,7 +217,7 @@ class VariantMatchFrame { if (arrays) { return arrays->NextPair(haystack_child, needle_child); } - return objects->NextPair(haystack_child, needle_child); + return Objects().NextPair(haystack_child, needle_child); } //! Moves on to the next needle child if the pair matched, and to its next candidate otherwise @@ -226,11 +226,25 @@ class VariantMatchFrame { arrays->PairCompared(matched); return; } - objects->PairCompared(matched); + Objects().PairCompared(matched); } bool AllMatched() const { - return arrays ? arrays->AllMatched() : objects->AllMatched(); + return arrays ? arrays->AllMatched() : Objects().AllMatched(); + } + +private: + VariantObjectMatch &Objects() { + if (!objects) { + throw InternalException("VariantMatchFrame holds neither an array nor an object"); + } + return *objects; + } + const VariantObjectMatch &Objects() const { + if (!objects) { + throw InternalException("VariantMatchFrame holds neither an array nor an object"); + } + return *objects; } private: @@ -283,7 +297,7 @@ bool ChildrenMatch(const VariantNode &haystack, const VariantNode &needle, Varia } //! Whether the haystack value itself matches the needle -bool MatchesNeedle(const VariantNode &haystack, VariantLogicalType haystack_type, VariantNeedle &needle, +bool MatchesNeedle(const VariantNode &haystack, LogicalTypeId haystack_type, VariantNeedle &needle, vector &frames) { const auto category = GetVariantComparisonType(haystack_type); if (category != needle.category) { @@ -302,8 +316,8 @@ bool MatchesNeedle(const VariantNode &haystack, VariantLogicalType haystack_type //! An array or object of the haystack, with the child to visit next class VariantWalkFrame { public: - VariantWalkFrame(const VariantNode &container, VariantLogicalType type_id) { - if (type_id == VariantLogicalType::ARRAY) { + VariantWalkFrame(const VariantNode &container, LogicalTypeId type_id) { + if (type_id == LogicalTypeId::LIST) { elements.emplace(container.GetArrayChildren()); } else { entries.emplace(container, VariantIterationOrder::INTERNAL); @@ -311,21 +325,27 @@ class VariantWalkFrame { } bool NextChild(VariantNode &child) { - return elements ? NextElement(child) : NextEntryValue(child); + if (elements) { + return NextElement(*elements, child); + } + if (!entries) { + throw InternalException("VariantWalkFrame holds neither an array nor an object"); + } + return NextEntryValue(*entries, child); } private: - bool NextElement(VariantNode &child) { - if (next_index == elements->size()) { + bool NextElement(const VariantArrayIterator &array, VariantNode &child) { + if (next_index == array.size()) { return false; } - child = (*elements)[next_index++]; + child = array[next_index++]; return true; } - bool NextEntryValue(VariantNode &child) { - while (next_index < entries->GetRawCount()) { - child = entries->RawEntry(next_index++).value; + bool NextEntryValue(const VariantObjectIterator &object, VariantNode &child) { + while (next_index < object.GetRawCount()) { + child = object.RawEntry(next_index++).value; // Shredded values may have missing object keys for a given row if (!child.IsMissing()) { return true; @@ -350,7 +370,7 @@ class VariantHaystackWalk { //! Moves to the next value, which is the first child of the current one if it has any bool Next() { - if (type_id == VariantLogicalType::ARRAY || type_id == VariantLogicalType::OBJECT) { + if (type_id == LogicalTypeId::LIST || type_id == LogicalTypeId::STRUCT) { frames.emplace_back(value, type_id); } while (!frames.empty()) { @@ -366,14 +386,14 @@ class VariantHaystackWalk { const VariantNode &Value() const { return value; } - VariantLogicalType Type() const { + LogicalTypeId Type() const { return type_id; } private: vector &frames; VariantNode value; - VariantLogicalType type_id; + LogicalTypeId type_id; }; //! The stacks of a given needle-haystack search diff --git a/src/duckdb/src/function/scalar/variant/variant_extract_string.cpp b/src/duckdb/src/function/scalar/variant/variant_extract_string.cpp index b499de186..49570d744 100644 --- a/src/duckdb/src/function/scalar/variant/variant_extract_string.cpp +++ b/src/duckdb/src/function/scalar/variant/variant_extract_string.cpp @@ -14,13 +14,13 @@ class VariantStringWriter { } void operator()(const optional &node, VectorWriter &string_writer) const { - if (!node || node->IsNull() || node->GetTypeId() == VariantLogicalType::VARIANT_NULL) { + if (!node || node->IsNull() || node->GetTypeId() == LogicalTypeId::SQLNULL) { string_writer.WriteNull(); return; } const auto type_id = node->GetTypeId(); - if (type_id == VariantLogicalType::VARCHAR) { + if (type_id == LogicalTypeId::VARCHAR) { string_writer.WriteValue(node->GetString()); return; } diff --git a/src/duckdb/src/function/scalar/variant/variant_keys.cpp b/src/duckdb/src/function/scalar/variant/variant_keys.cpp index be5940535..ce82b35fd 100644 --- a/src/duckdb/src/function/scalar/variant/variant_keys.cpp +++ b/src/duckdb/src/function/scalar/variant/variant_keys.cpp @@ -11,7 +11,7 @@ static void WriteKeysResult(const optional &node, VectorWriterGetTypeId() != VariantLogicalType::OBJECT) { + if (node->GetTypeId() != LogicalTypeId::STRUCT) { list_writer.WriteList(0); return; } diff --git a/src/duckdb/src/function/scalar/variant/variant_normalize.cpp b/src/duckdb/src/function/scalar/variant/variant_normalize.cpp index 9c6d02918..acee26983 100644 --- a/src/duckdb/src/function/scalar/variant/variant_normalize.cpp +++ b/src/duckdb/src/function/scalar/variant/variant_normalize.cpp @@ -183,8 +183,8 @@ void VariantNormalizer::VisitObject(const UnifiedVariantVectorData &variant, idx } } -void VariantNormalizer::VisitDefault(VariantLogicalType type_id, const_data_ptr_t, VariantNormalizerState &state) { - throw InternalException("VariantLogicalType(%s) not handled", EnumUtil::ToString(type_id)); +void VariantNormalizer::VisitDefault(const LogicalType &type, const_data_ptr_t, VariantNormalizerState &state) { + throw InternalException("VariantLogicalType(%s) not handled", type.ToString()); } void VariantNormalizer::Normalize(const Vector &variant_vec, Vector &result) { diff --git a/src/duckdb/src/function/scalar/variant/variant_path_function.cpp b/src/duckdb/src/function/scalar/variant/variant_path_function.cpp index 47e66de2a..ceb73139c 100644 --- a/src/duckdb/src/function/scalar/variant/variant_path_function.cpp +++ b/src/duckdb/src/function/scalar/variant/variant_path_function.cpp @@ -10,8 +10,8 @@ namespace { void EmitSelectedNode(const VariantNode &node, VariantBuilder &builder) { if (!node.IsNull() && !node.IsMissing()) { const auto type = node.GetTypeId(); - if (type != VariantLogicalType::OBJECT && type != VariantLogicalType::ARRAY) { - builder.EmitPrimitiveNode(node, type); + if (type != LogicalTypeId::STRUCT && type != LogicalTypeId::LIST) { + builder.EmitPrimitiveNode(node); return; } } @@ -67,7 +67,7 @@ void VariantPathFunction::ExecuteVariant(DataChunk &input, const ExpressionState } optional VariantPathFunction::ResolveIndex(const VariantNode &node, int64_t index) { - if (node.IsNull() || node.IsMissing() || node.GetTypeId() != VariantLogicalType::ARRAY) { + if (node.IsNull() || node.IsMissing() || node.GetTypeId() != LogicalTypeId::LIST) { return {}; } const auto elements = node.GetArrayChildren(); @@ -133,14 +133,15 @@ void VariantPathFunction::ExecuteVariantMany(const Vector &input, const vector &node, VectorWriterGetTypeId(); + //! variant_type reports the type name of the physical variant encoding + const auto type = VariantTypeFromLogicalTypeId(node->GetTypeId(), node->GetBool()); types_writer.WriteValue(string_t(EnumUtil::ToString(type))); } diff --git a/src/duckdb/src/function/scalar/variant/variant_value.cpp b/src/duckdb/src/function/scalar/variant/variant_value.cpp index 17a369e1c..1505d1b29 100644 --- a/src/duckdb/src/function/scalar/variant/variant_value.cpp +++ b/src/duckdb/src/function/scalar/variant/variant_value.cpp @@ -13,9 +13,9 @@ bool IsScalarValue(const VariantNode &node) { return false; } switch (node.GetTypeId()) { - case VariantLogicalType::VARIANT_NULL: - case VariantLogicalType::OBJECT: - case VariantLogicalType::ARRAY: + case LogicalTypeId::SQLNULL: + case LogicalTypeId::STRUCT: + case LogicalTypeId::LIST: return false; default: return true; diff --git a/src/duckdb/src/function/table/glob.cpp b/src/duckdb/src/function/table/glob.cpp index b7715f1c5..ce62e3ce0 100644 --- a/src/duckdb/src/function/table/glob.cpp +++ b/src/duckdb/src/function/table/glob.cpp @@ -3,16 +3,29 @@ #include "duckdb/function/function_set.hpp" #include "duckdb/common/atomic.hpp" #include "duckdb/common/file_system.hpp" +#include "duckdb/common/vector/list_vector.hpp" +#include "duckdb/common/vector/map_vector.hpp" +#include "duckdb/common/vector_operations/vector_operations.hpp" +#include "duckdb/main/client_context.hpp" #include "duckdb/main/config.hpp" #include "duckdb/common/multi_file/multi_file_reader.hpp" #include "duckdb/execution/progress_data.hpp" +#include #include namespace duckdb { struct GlobFunctionBindData : public TableFunctionData { - shared_ptr file_list; + explicit GlobFunctionBindData(FileGlobInput glob_input_p) : glob_input(std::move(glob_input_p)) { + } + + //! The globs to expand + vector globs; + //! How the globs are expanded + FileGlobInput glob_input; + //! Whether to also return the options to open every file with + bool full_file_info = false; bool SupportStatementCache() const override { return false; @@ -21,62 +34,233 @@ struct GlobFunctionBindData : public TableFunctionData { static unique_ptr GlobFunctionBind(ClientContext &context, TableFunctionBindInput &input, vector &return_types, vector &names) { - auto result = make_uniq(); - auto multi_file_reader = MultiFileReader::Create(input.table_function); - result->file_list = multi_file_reader->CreateFileList(context, input.inputs[0], FileGlobOptions::ALLOW_EMPTY); + bool allow_empty = true; + bool full_file_info = false; + string fallback_extension; + for (auto &entry : input.named_parameters) { + if (entry.second.IsNull()) { + continue; + } + if (entry.first == "allow_empty") { + allow_empty = BooleanValue::Get(entry.second); + } else if (entry.first == "fallback_extension") { + fallback_extension = StringValue::Get(entry.second); + } else if (entry.first == "full_file_info") { + full_file_info = BooleanValue::Get(entry.second); + } + } + FileGlobInput glob_input(allow_empty ? FileGlobOptions::ALLOW_EMPTY : FileGlobOptions::DISALLOW_EMPTY); + if (!fallback_extension.empty()) { + // a pattern without a glob that matches nothing is globbed as a directory of files with this extension + glob_input = FileGlobInput(FileGlobOptions::FALLBACK_GLOB, fallback_extension); + glob_input.allow_empty = allow_empty; + } return_types.emplace_back(LogicalType::VARCHAR); names.emplace_back("file"); + if (full_file_info) { + return_types.emplace_back(LogicalType::MAP(LogicalType::VARCHAR, LogicalType::VARIANT())); + names.emplace_back("options"); + } + auto result = make_uniq(std::move(glob_input)); + result->full_file_info = full_file_info; + auto multi_file_reader = MultiFileReader::Create(input.table_function); + result->globs = multi_file_reader->ParseFileList(input.inputs[0]); return std::move(result); } struct GlobFunctionState : public GlobalTableFunctionState { - GlobFunctionState() : files_returned(0) { - } + //! The glob that is being expanded + idx_t current_glob = 0; + //! The files of the glob that is being expanded, and the scan over them + unique_ptr glob_files; + MultiFileListScanData scan_state; + + //! The files that have been expanded but not yet returned + vector pending_files; + idx_t pending_offset = 0; - MultiFileListScanData file_list_scan; - atomic files_returned; - //! The progress is estimated while the glob is being expanded - keeps it monotonic + //! Progress tracking - the progress is estimated while the globs are being expanded + atomic files_expanded {0}; + atomic files_returned {0}; + atomic all_files_expanded {false}; + //! Keeps the progress monotonic MonotonicProgress progress; }; static unique_ptr GlobFunctionInit(ClientContext &context, TableFunctionInitInput &input) { - auto &bind_data = input.bind_data->Cast(); - auto res = make_uniq(); - - bind_data.file_list->InitializeScan(res->file_list_scan); + return make_uniq(); +} - return std::move(res); +//! Expand the next batch of files - the files of a glob that can be fetched with a single I/O operation, sorted. +//! Returns false when all globs have been expanded +static bool GlobExpandNext(ClientContext &context, const GlobFunctionBindData &bind_data, GlobFunctionState &state, + vector &result) { + if (state.current_glob >= bind_data.globs.size()) { + state.all_files_expanded = true; + return false; + } + auto ¤t_entry = bind_data.globs[state.current_glob]; + if (current_entry.extended_info) { + // the file was specified together with the options to open it with - use it as-is + result.push_back(current_entry); + state.current_glob++; + state.files_expanded++; + return true; + } + if (!state.glob_files) { + // glob is not yet started for this entry - start it and initiate the scan over its files + auto &fs = FileSystem::GetFileSystem(context); + state.glob_files = fs.GlobFileList(current_entry.path, bind_data.glob_input); + state.scan_state = MultiFileListScanData(); + state.glob_files->InitializeScan(state.scan_state); + } + // get the next batch of files we can fetch through the glob + auto &glob_list = *state.glob_files; + state.scan_state.scan_type = MultiFileListScanType::ALWAYS_FETCH; + OpenFileInfo file; + if (!glob_list.Scan(state.scan_state, file)) { + // no more files available in this glob - move to the next glob + state.glob_files.reset(); + state.current_glob++; + return true; + } + auto batch_start = result.size(); + result.push_back(std::move(file)); + // now continue scanning files that are already available (i.e. that don't require extra I/O operations to fetch) + state.scan_state.scan_type = MultiFileListScanType::FETCH_IF_AVAILABLE; + while (glob_list.Scan(state.scan_state, file)) { + result.push_back(std::move(file)); + } + std::sort(result.begin() + NumericCast(batch_start), result.end()); + state.files_expanded += result.size() - batch_start; + return true; } -static void GlobFunction(ClientContext &context, TableFunctionInput &data_p, DataChunk &output) { +//! Expand until there are files to return - returns the number of files to return next (0 when done) +static idx_t GlobNextFiles(ClientContext &context, TableFunctionInput &data_p) { auto &bind_data = data_p.bind_data->Cast(); auto &state = data_p.global_state->Cast(); + while (state.pending_offset >= state.pending_files.size()) { + if (context.IsInterrupted()) { + throw InterruptException(); + } + state.pending_files.clear(); + state.pending_offset = 0; + if (!GlobExpandNext(context, bind_data, state, state.pending_files)) { + return 0; + } + } + return MinValue(STANDARD_VECTOR_SIZE, state.pending_files.size() - state.pending_offset); +} + +static void WriteFiles(GlobFunctionState &state, Vector &result, idx_t count) { + auto writer = FlatVector::Writer(result, count); + for (idx_t i = 0; i < count; i++) { + writer.WriteValue(string_t(state.pending_files[state.pending_offset + i].path)); + } +} - state.file_list_scan.scan_type = MultiFileListScanType::ALWAYS_FETCH; - idx_t count = 0; - auto &file_column = output.data[0]; - while (count < STANDARD_VECTOR_SIZE) { - OpenFileInfo file; - if (!bind_data.file_list->Scan(state.file_list_scan, file)) { - break; +//! Write the options to open the files with as a MAP(VARCHAR, VARIANT). The values are converted to VARIANT one +//! type at a time - a glob produces the same few option types for every file +static void WriteFileOptions(ClientContext &context, GlobFunctionState &state, Vector &result, idx_t count) { + idx_t option_count = 0; + for (idx_t i = 0; i < count; i++) { + auto &file = state.pending_files[state.pending_offset + i]; + if (file.extended_info) { + option_count += file.extended_info->options.size(); + } + } + ListVector::Reserve(result, option_count); + auto &keys = MapVector::GetKeys(result); + auto &values = MapVector::GetValues(result); + + //! the values of every type, and the position of each value among the options + vector value_types; + vector>> typed_values; + vector> value_positions; + value_positions.reserve(option_count); + { + auto list_writer = FlatVector::Writer(result, count); + auto key_writer = FlatVector::Writer(keys, option_count); + idx_t offset = 0; + for (idx_t i = 0; i < count; i++) { + auto &file = state.pending_files[state.pending_offset + i]; + if (!file.extended_info) { + list_writer.WriteNull(); + continue; + } + auto &options = file.extended_info->options; + list_writer.WriteValue(list_entry_t(offset, options.size())); + offset += options.size(); + for (auto &option : options) { + key_writer.WriteValue(string_t(option.first)); + idx_t type_idx; + for (type_idx = 0; type_idx < value_types.size(); type_idx++) { + if (value_types[type_idx] == option.second.type()) { + break; + } + } + if (type_idx == value_types.size()) { + value_types.push_back(option.second.type()); + typed_values.emplace_back(); + } + value_positions.emplace_back(type_idx, typed_values[type_idx].size()); + typed_values[type_idx].push_back(option.second); + } + } + } + ListVector::SetListSize(result, option_count); + if (option_count == 0) { + return; + } + // convert the values of every type to VARIANT in one go, one after the other + Vector variants(LogicalType::VARIANT(), option_count); + vector type_offsets; + idx_t variant_offset = 0; + for (idx_t type_idx = 0; type_idx < value_types.size(); type_idx++) { + auto &type_values = typed_values[type_idx]; + Vector typed(value_types[type_idx], type_values.size()); + for (idx_t i = 0; i < type_values.size(); i++) { + typed.SetValue(i, type_values[i].get()); } - file_column.Append(Value(file.path)); - count++; - state.file_list_scan.scan_type = MultiFileListScanType::FETCH_IF_AVAILABLE; + Vector converted(LogicalType::VARIANT(), type_values.size()); + VectorOperations::Cast(context, typed, converted, type_values.size()); + VectorOperations::Copy(converted, variants, type_values.size(), 0, variant_offset); + type_offsets.push_back(variant_offset); + variant_offset += type_values.size(); + } + // and put them in the position of their option + SelectionVector sel(option_count); + for (idx_t i = 0; i < option_count; i++) { + auto &position = value_positions[i]; + sel.set_index(i, type_offsets[position.first] + position.second); + } + VectorOperations::Copy(variants, values, sel, option_count, 0, 0); +} + +static void GlobFunction(ClientContext &context, TableFunctionInput &data_p, DataChunk &output) { + auto &bind_data = data_p.bind_data->Cast(); + auto &state = data_p.global_state->Cast(); + auto count = GlobNextFiles(context, data_p); + if (count == 0) { + return; + } + WriteFiles(state, output.data[0], count); + if (bind_data.full_file_info) { + WriteFileOptions(context, state, output.data[1], count); } + state.pending_offset += count; state.files_returned.fetch_add(count, std::memory_order_relaxed); } static double GlobFunctionProgress(ClientContext &context, const FunctionData *bind_data_p, const GlobalTableFunctionState *global_state) { - auto &bind_data = bind_data_p->Cast(); auto &state = global_state->Cast(); auto files_returned = static_cast(state.files_returned.load(std::memory_order_relaxed)); - // only look at the files that have been expanded so far - expanding the glob here would perform I/O - auto file_count = bind_data.file_list->GetFileCount(0); double fraction; - if (file_count.type == FileExpansionType::ALL_FILES_EXPANDED) { - fraction = file_count.count == 0 ? 1.0 : files_returned / static_cast(file_count.count); + if (state.all_files_expanded) { + auto file_count = state.files_expanded.load(); + fraction = file_count == 0 ? 1.0 : files_returned / static_cast(file_count); } else { // the number of files is not known yet - converge towards 100% as files are returned fraction = 1 - 1 / (1 + std::log2(1 + files_returned / static_cast(STANDARD_VECTOR_SIZE))); @@ -87,7 +271,12 @@ static double GlobFunctionProgress(ClientContext &context, const FunctionData *b } void GlobTableFunction::RegisterFunction(BuiltinFunctions &set) { - TableFunction glob_function("glob", FunctionSignature().AddPositionalOnly("pattern", LogicalType::VARCHAR), + TableFunction glob_function("glob", + FunctionSignature() + .AddPositionalOnly("pattern", LogicalType::VARCHAR) + .AddKeywordOnly("allow_empty", LogicalType::BOOLEAN, Value::BOOLEAN(true)) + .AddKeywordOnly("fallback_extension", LogicalType::VARCHAR, Value()) + .AddKeywordOnly("full_file_info", LogicalType::BOOLEAN, Value::BOOLEAN(false)), GlobFunction, GlobFunctionBind, GlobFunctionInit); glob_function.table_scan_progress = GlobFunctionProgress; // lists the filesystem at execution time diff --git a/src/duckdb/src/function/table/read_duckdb.cpp b/src/duckdb/src/function/table/read_duckdb.cpp index ec4f57a4d..6374cc492 100644 --- a/src/duckdb/src/function/table/read_duckdb.cpp +++ b/src/duckdb/src/function/table/read_duckdb.cpp @@ -12,6 +12,11 @@ #include "duckdb/storage/data_table.hpp" #include "duckdb/main/database_manager.hpp" #include "duckdb/parser/parsed_data/attach_info.hpp" +#include "duckdb/execution/expression_executor.hpp" +#include "duckdb/planner/expression/bound_reference_expression.hpp" +#include "duckdb/planner/expression_iterator.hpp" +#include "duckdb/planner/table_filter_state.hpp" +#include "duckdb/storage/table/column_segment.hpp" namespace duckdb { @@ -84,6 +89,8 @@ struct AttachedDatabaseWrapper { optional_ptr table_entry; }; +struct DuckDBReadLocalState; + class DuckDBReader : public BaseFileReader { public: DuckDBReader(ClientContext &context, OpenFileInfo file, const DuckDBFileReaderOptions &options); @@ -106,6 +113,15 @@ class DuckDBReader : public BaseFileReader { AttachedDatabase &GetAttachedDatabase(); TableCatalogEntry &GetTableEntry(); +private: + //! The filters the table scan evaluates - those on the columns that are read as the file stores them + optional_ptr GetScanFilters(); + //! Prepares the conversions of expression_map and the filters that apply to their results + void InitializeConvertedColumns(ClientContext &context, DuckDBReadLocalState &lstate); + //! Scans the table into the chunk of the file, converts the columns of expression_map and applies their filters + void ScanConvertedColumns(ClientContext &context, TableFunctionInput &input, DuckDBReadLocalState &lstate, + DataChunk &chunk); + private: ClientContext &context; shared_ptr db_wrapper; @@ -115,6 +131,8 @@ class DuckDBReader : public BaseFileReader { atomic finished; //! The column indexes to scan - the row id is scanned if no columns are projected vector scan_column_indexes; + //! The subset of the filters that is pushed into the table scan - only set when some columns are converted + unique_ptr scan_filters; idx_t column_count; Identifier schema_name; Identifier table_name; @@ -122,11 +140,31 @@ class DuckDBReader : public BaseFileReader { struct DuckDBReadGlobalState : GlobalTableFunctionState {}; +//! A scan column the multi-file scan wants converted before its filters apply (see BaseFileReader::expression_map) +struct DuckDBConvertedColumn { + //! The position of the scan column the conversion produces + idx_t position; + unique_ptr expression; + unique_ptr executor; + //! The columns of the file the expression reads - the scan columns starting at position + unique_ptr input; +}; + struct DuckDBReadLocalState : LocalTableFunctionState { unique_ptr local_state; shared_ptr attached_database; //! The chunk to scan into when no columns are projected (we then scan the row ids) DataChunk row_id_chunk; + //! The columns of the current file that are converted after the table scan + vector converted_columns; + //! For each scan column, whether it is one of the converted columns + vector converted_position; + //! The filters on the converted columns, as the position of the scan column and the filter state + vector>> converted_filters; + //! What the table scan produces, in the types of the file, when some columns are converted afterwards + DataChunk file_chunk; + //! Whether the previous scan into file_chunk was blocked + bool resuming_blocked_scan = false; }; string DuckDBFileReaderOptions::GetCandidates(const vector> &tables) const { @@ -306,22 +344,131 @@ bool DuckDBReader::TryInitializeScan(ClientContext &context, GlobalTableFunction // the table scan requires at least one column - scan the row id if no columns are projected scan_column_indexes.emplace_back(COLUMN_IDENTIFIER_ROW_ID); } + if (filters && !expression_map.empty()) { + // a filter on a converted column is written against the converted values, not against those of the file - + // it is applied after the conversion, the table scan only evaluates the filters on the other columns + scan_filters = filters->Copy(); + for (auto &entry : expression_map) { + if (scan_filters->HasFilter(entry.first)) { + scan_filters->RemoveFilterByColumnIndex(entry.first); + } + } + } // initialize the scan over this table - TableFunctionInitInput input(bind_data.get(), scan_column_indexes, vector(), filters.get()); + TableFunctionInitInput input(bind_data.get(), scan_column_indexes, vector(), GetScanFilters()); global_state = scan_function.init_global(context, input); } AssignSharedPointer(lstate.attached_database, db_wrapper); // initialize the local scan ThreadContext thread(context); ExecutionContext exec_context(context, thread, nullptr); - TableFunctionInitInput input(bind_data.get(), scan_column_indexes, vector(), filters.get()); + TableFunctionInitInput input(bind_data.get(), scan_column_indexes, vector(), GetScanFilters()); lstate.local_state = scan_function.init_local(exec_context, input, global_state.get()); + InitializeConvertedColumns(context, lstate); if (column_indexes.empty() && lstate.row_id_chunk.ColumnCount() == 0) { lstate.row_id_chunk.Initialize(context, {LogicalType::ROW_TYPE}); } return true; } +optional_ptr DuckDBReader::GetScanFilters() { + if (!scan_filters) { + return filters.get(); + } + return scan_filters->HasFilters() ? scan_filters.get() : nullptr; +} + +void DuckDBReader::InitializeConvertedColumns(ClientContext &context, DuckDBReadLocalState &lstate) { + lstate.converted_columns.clear(); + lstate.converted_position.clear(); + lstate.converted_filters.clear(); + lstate.file_chunk.Destroy(); + lstate.resuming_blocked_scan = false; + for (auto &entry : expression_map) { + DuckDBConvertedColumn converted; + converted.position = entry.first.GetIndex(); + converted.expression = entry.second.expression->Copy(); + converted.executor = make_uniq(context, *converted.expression); + // the expression refers to the scan columns starting at its position, which the table scan produces as stored + vector input_types(entry.second.column_indexes.size()); + ExpressionIterator::VisitExpression( + *converted.expression, + [&](const BoundReferenceExpression &ref) { input_types[ref.Index()] = ref.GetReturnType(); }); + if (converted.position + input_types.size() > scan_column_indexes.size()) { + throw InternalException("Converted column %llu of read_duckdb is out of range", converted.position); + } + converted.input = make_uniq(); + converted.input->InitializeEmpty(input_types); + lstate.converted_position.resize(scan_column_indexes.size(), false); + lstate.converted_position[converted.position] = true; + lstate.converted_columns.push_back(std::move(converted)); + } + if (lstate.converted_columns.empty() || !filters) { + return; + } + for (auto &entry : *filters) { + if (expression_map.find(entry.GetIndex()) != expression_map.end()) { + lstate.converted_filters.emplace_back(entry.GetIndex().GetIndex(), + TableFilterState::Initialize(context, entry.Filter())); + } + } +} + +void DuckDBReader::ScanConvertedColumns(ClientContext &context, TableFunctionInput &input, DuckDBReadLocalState &lstate, + DataChunk &chunk) { + auto &file_chunk = lstate.file_chunk; + if (file_chunk.ColumnCount() == 0) { + // the table scan produces the columns the expressions read in the types of the file + auto file_types = chunk.GetTypes(); + for (auto &converted : lstate.converted_columns) { + for (idx_t i = 0; i < converted.input->ColumnCount(); i++) { + file_types[converted.position + i] = converted.input->data[i].GetType(); + } + } + file_chunk.Initialize(context, file_types); + } + if (!lstate.resuming_blocked_scan) { + file_chunk.Reset(); + } + scan_function.function(context, input, file_chunk); + lstate.resuming_blocked_scan = input.async_result.GetResultType() == AsyncResultType::BLOCKED; + const auto count = file_chunk.size(); + if (lstate.resuming_blocked_scan || count == 0) { + return; + } + for (auto &converted : lstate.converted_columns) { + auto &converted_input = *converted.input; + for (idx_t i = 0; i < converted_input.ColumnCount(); i++) { + converted_input.data[i].Reference(file_chunk.data[converted.position + i]); + } + converted_input.SetChildCardinality(count); + converted.executor->ExecuteExpression(converted_input, chunk.data[converted.position]); + } + // the other columns are produced as stored + for (idx_t i = 0; i < file_chunk.ColumnCount(); i++) { + if (!lstate.converted_position[i]) { + chunk.data[i].Reference(file_chunk.data[i]); + } + } + chunk.SetChildCardinality(count); + + // apply the filters on the converted columns + idx_t remaining = count; + SelectionVector selection; + selection.Initialize(nullptr); + for (auto &filter : lstate.converted_filters) { + if (remaining == 0) { + break; + } + ColumnSegment::FilterSelection(selection, chunk.data[filter.first], *filter.second, count, remaining); + } + if (remaining == 0) { + chunk.Reset(); + } else if (remaining != count) { + chunk.Slice(selection, remaining); + } +} + AsyncResult DuckDBReader::Scan(ClientContext &context, GlobalTableFunctionState &gstate_p, LocalTableFunctionState &lstate_p, DataChunk &chunk) { auto &lstate = lstate_p.Cast(); @@ -337,6 +484,8 @@ AsyncResult DuckDBReader::Scan(ClientContext &context, GlobalTableFunctionState lstate.row_id_chunk.Reset(); scan_function.function(context, input, lstate.row_id_chunk); chunk.SetChildCardinality(lstate.row_id_chunk.size()); + } else if (!lstate.converted_columns.empty()) { + ScanConvertedColumns(context, input, lstate, chunk); } else { scan_function.function(context, input, chunk); } @@ -344,7 +493,10 @@ AsyncResult DuckDBReader::Scan(ClientContext &context, GlobalTableFunctionState if (input.async_result.GetResultType() == AsyncResultType::BLOCKED) { return std::move(input.async_result); } - auto source_result = AsyncResult::GetSourceResultType(input.async_result.GetResultType(), chunk.size()); + // the filters on converted columns can reject every row the table scan produced - the scan ends when the table + // scan produces nothing + auto scan_count = lstate.converted_columns.empty() ? chunk.size() : lstate.file_chunk.size(); + auto source_result = AsyncResult::GetSourceResultType(input.async_result.GetResultType(), scan_count); if (source_result == SourceResultType::FINISHED) { finished = true; } diff --git a/src/duckdb/src/function/table/table_scan.cpp b/src/duckdb/src/function/table/table_scan.cpp index f7e30da34..5daa6701a 100644 --- a/src/duckdb/src/function/table/table_scan.cpp +++ b/src/duckdb/src/function/table/table_scan.cpp @@ -15,6 +15,7 @@ #include "duckdb/common/typedefs.hpp" #include "duckdb/common/types/value_map.hpp" #include "duckdb/common/unique_ptr.hpp" +#include "duckdb/execution/adaptive_filter.hpp" #include "duckdb/execution/index/art/art.hpp" #include "duckdb/execution/index/art/iterator.hpp" #include "duckdb/function/function_set.hpp" @@ -42,6 +43,7 @@ #include "duckdb/storage/data_table.hpp" #include "duckdb/storage/storage_index.hpp" #include "duckdb/storage/table_io_manager.hpp" +#include "duckdb/storage/table/column_segment.hpp" #include "duckdb/storage/table/data_table_info.hpp" #include "duckdb/storage/table/scan_state.hpp" #include "duckdb/planner/expression_iterator.hpp" @@ -231,6 +233,31 @@ class DuckIndexScanState : public TableScanGlobalState { return std::move(l_state); } + //! The index scan can return a superset of the matching rows, so apply all table filters to the fetched rows. + static void FilterFetchedRows(ScanFilterInfo &filter_info, DataChunk &chunk) { + auto adaptive_filter = filter_info.GetAdaptiveFilter(); + if (!adaptive_filter || chunk.size() == 0) { + return; + } + const auto count = chunk.size(); + SelectionVector sel; + sel.Initialize(nullptr); + idx_t approved_tuple_count = count; + auto &filter_list = filter_info.GetFilterList(); + const auto &permutation = adaptive_filter->GetPermutation(); + for (idx_t i = 0; i < filter_list.size(); i++) { + auto &filter = filter_list[permutation[i]]; + ColumnSegment::FilterSelection(sel, chunk.data[filter.scan_column_index], *filter.filter_state, count, + approved_tuple_count); + if (approved_tuple_count == 0) { + break; + } + } + if (approved_tuple_count != count) { + chunk.Slice(sel, approved_tuple_count); + } + } + void TableScanFunc(ClientContext &context, TableFunctionInput &data_p, DataChunk &output) override { auto &bind_data = data_p.bind_data->Cast(); auto &duck_table = bind_data.table.Cast(); @@ -285,9 +312,11 @@ class DuckIndexScanState : public TableScanGlobalState { if (CanRemoveFilterColumns()) { l_state.all_columns.Reset(); storage.Fetch(tx, l_state.all_columns, column_ids, local_vector, scan_count, l_state.fetch_state); + FilterFetchedRows(l_state.scan_state.GetFilterInfo(), l_state.all_columns); output.ReferenceColumns(l_state.all_columns, projection_ids); } else { storage.Fetch(tx, output, column_ids, local_vector, scan_count, l_state.fetch_state); + FilterFetchedRows(l_state.scan_state.GetFilterInfo(), output); } l_state.rows_scanned += scan_count; @@ -300,6 +329,7 @@ class DuckIndexScanState : public TableScanGlobalState { } // output is empty, loop back, since there might be results to be picked up from LOCAL_STORAGE phase + output.Reset(); continue; } return; @@ -1104,13 +1134,13 @@ unique_ptr TableScanInitGlobal(ClientContext &context, auto &filter_set = *input.filters; - // FIXME: We currently only support scanning one ART with one filter. - // If multiple filters exist, i.e., a = 11 AND b = 24, we need to - // 1. 1.1. Find + scan one ART for a = 11. - // 1.2. Find + scan one ART for b = 24. - // 1.3. Return the intersecting row IDs. + // Scan one ART with the filter on its column. The index scan applies all filters to the fetched rows. + // FIXME: For multiple filters, i.e., a = 11 AND b = 24, we could also + // 1. Scan the ARTs for a = 11 and b = 24, and intersect the row IDs. // 2. (Reorder and) scan a single ART with a compound key of (a, b). - if (filter_set.FilterCount() != 1) { + // FIXME: We use the first ART within the thresholds, not the most selective one. Each failed probe can scan up + // to max_count row IDs before falling back to a table scan. + if (!filter_set.HasFilters()) { return DuckTableScanInitGlobal(context, input, storage, bind_data); } diff --git a/src/duckdb/src/function/table/version/pragma_version.cpp b/src/duckdb/src/function/table/version/pragma_version.cpp index d3e81a89d..405955fad 100644 --- a/src/duckdb/src/function/table/version/pragma_version.cpp +++ b/src/duckdb/src/function/table/version/pragma_version.cpp @@ -1,5 +1,5 @@ #ifndef DUCKDB_PATCH_VERSION -#define DUCKDB_PATCH_VERSION "0-alpha57538" +#define DUCKDB_PATCH_VERSION "0-dev95858" #endif #ifndef DUCKDB_MINOR_VERSION #define DUCKDB_MINOR_VERSION 1 @@ -8,10 +8,10 @@ #define DUCKDB_MAJOR_VERSION 2 #endif #ifndef DUCKDB_VERSION -#define DUCKDB_VERSION "v2.1.0-alpha57538" +#define DUCKDB_VERSION "v2.1.0-dev95858" #endif #ifndef DUCKDB_SOURCE_ID -#define DUCKDB_SOURCE_ID "5e78b7f833" +#define DUCKDB_SOURCE_ID "ca7a503a52" #endif #include "duckdb/function/table/system_functions.hpp" #include "duckdb/main/database.hpp" diff --git a/src/duckdb/src/function/variant/variant_shredding.cpp b/src/duckdb/src/function/variant/variant_shredding.cpp index 49c0eff7f..bc85be6fe 100644 --- a/src/duckdb/src/function/variant/variant_shredding.cpp +++ b/src/duckdb/src/function/variant/variant_shredding.cpp @@ -366,7 +366,7 @@ VariantShreddingState::VariantShreddingState(const LogicalType &type, idx_t tota bool VariantShreddingState::ValueIsShredded(UnifiedVariantVectorData &variant, idx_t row, uint32_t values_index) { auto type_id = variant.GetTypeId(row, values_index); - if (!GetVariantTypes().count(type_id)) { + if (!GetVariantTypes().count(VariantTypeToLogicalTypeId(type_id))) { return false; } if (type_id == VariantLogicalType::DECIMAL) { diff --git a/src/duckdb/src/function/window/window_value_function.cpp b/src/duckdb/src/function/window/window_value_function.cpp index 011fc958a..48fc16883 100644 --- a/src/duckdb/src/function/window/window_value_function.cpp +++ b/src/duckdb/src/function/window/window_value_function.cpp @@ -1838,6 +1838,8 @@ WindowFunction FillFun::GetFunction() { //! Never ignore nulls (that's the point!) fun.SetCanIgnoreNulls(false); + //! The ORDER BY values are the X axis of the interpolation + fun.SetRequiresOrdering(true); return fun; } diff --git a/src/duckdb/src/include/duckdb/common/buffer_ptr.hpp b/src/duckdb/src/include/duckdb/common/buffer_ptr.hpp index a72365a99..a2711d261 100644 --- a/src/duckdb/src/include/duckdb/common/buffer_ptr.hpp +++ b/src/duckdb/src/include/duckdb/common/buffer_ptr.hpp @@ -107,6 +107,7 @@ class buffer_ptr { // NOLINT: mimic std casing } } template + // NOLINTNEXTLINE(cppcoreguidelines-rvalue-reference-param-not-moved): steals the owner's control block buffer_ptr(buffer_ptr &&owner, T *ptr_p) noexcept : ptr(ptr_p), control(owner.control) { owner.ptr = nullptr; owner.control = nullptr; @@ -118,6 +119,9 @@ class buffer_ptr { // NOLINT: mimic std casing } buffer_ptr &operator=(const buffer_ptr &other) noexcept { + if (this == &other) { + return *this; + } return Assign(other); } template ::value, int>::type = 0> @@ -238,9 +242,13 @@ class enable_buffer_from_this { // NOLINT: mimic std casing } protected: + // Protected like std::enable_shared_from_this, so any class in a hierarchy can derive from it + // NOLINTNEXTLINE(bugprone-crtp-constructor-accessibility) enable_buffer_from_this() noexcept = default; + // NOLINTNEXTLINE(bugprone-crtp-constructor-accessibility) enable_buffer_from_this(const enable_buffer_from_this &) noexcept { } + // NOLINTNEXTLINE(bugprone-unhandled-self-assignment): assignment keeps the owner, so it is a no-op enable_buffer_from_this &operator=(const enable_buffer_from_this &) noexcept { // Assignment changes the payload, not its owner. return *this; diff --git a/src/duckdb/src/include/duckdb/common/enum_util.hpp b/src/duckdb/src/include/duckdb/common/enum_util.hpp index 3cb1c14f3..6baa6c64f 100644 --- a/src/duckdb/src/include/duckdb/common/enum_util.hpp +++ b/src/duckdb/src/include/duckdb/common/enum_util.hpp @@ -252,6 +252,8 @@ enum class ExtensionLoadResult : uint8_t; enum class ExtensionRepositoryAccess : uint8_t; +enum class ExtensionRepositoryHostCaller : uint8_t; + enum class ExtensionRepositoryType : uint8_t; enum class ExtensionUpdateResultTag : uint8_t; @@ -332,6 +334,8 @@ enum class IndexDeltaType : uint8_t; enum class InsertColumnOrder : uint8_t; +enum class IntegerRounding : uint8_t; + enum class InterruptMode : uint8_t; enum class JoinFilterPushdownMode : uint8_t; @@ -664,6 +668,10 @@ enum class ThreadPinMode : uint8_t; enum class TimestampCastResult : uint8_t; +enum class TopNBoundaryRowOrder : uint8_t; + +enum class TopNBoundaryTies : uint8_t; + enum class TransactionInvalidationPolicy : uint8_t; enum class TransactionModifierType : uint8_t; @@ -1053,6 +1061,9 @@ const char* EnumUtil::ToChars(ExtensionLoadResult value); template<> const char* EnumUtil::ToChars(ExtensionRepositoryAccess value); +template<> +const char* EnumUtil::ToChars(ExtensionRepositoryHostCaller value); + template<> const char* EnumUtil::ToChars(ExtensionRepositoryType value); @@ -1173,6 +1184,9 @@ const char* EnumUtil::ToChars(IndexDeltaType value); template<> const char* EnumUtil::ToChars(InsertColumnOrder value); +template<> +const char* EnumUtil::ToChars(IntegerRounding value); + template<> const char* EnumUtil::ToChars(InterruptMode value); @@ -1671,6 +1685,12 @@ const char* EnumUtil::ToChars(ThreadPinMode value); template<> const char* EnumUtil::ToChars(TimestampCastResult value); +template<> +const char* EnumUtil::ToChars(TopNBoundaryRowOrder value); + +template<> +const char* EnumUtil::ToChars(TopNBoundaryTies value); + template<> const char* EnumUtil::ToChars(TransactionInvalidationPolicy value); @@ -2089,6 +2109,9 @@ ExtensionLoadResult EnumUtil::FromString(const char *value) template<> ExtensionRepositoryAccess EnumUtil::FromString(const char *value); +template<> +ExtensionRepositoryHostCaller EnumUtil::FromString(const char *value); + template<> ExtensionRepositoryType EnumUtil::FromString(const char *value); @@ -2209,6 +2232,9 @@ IndexDeltaType EnumUtil::FromString(const char *value); template<> InsertColumnOrder EnumUtil::FromString(const char *value); +template<> +IntegerRounding EnumUtil::FromString(const char *value); + template<> InterruptMode EnumUtil::FromString(const char *value); @@ -2707,6 +2733,12 @@ ThreadPinMode EnumUtil::FromString(const char *value); template<> TimestampCastResult EnumUtil::FromString(const char *value); +template<> +TopNBoundaryRowOrder EnumUtil::FromString(const char *value); + +template<> +TopNBoundaryTies EnumUtil::FromString(const char *value); + template<> TransactionInvalidationPolicy EnumUtil::FromString(const char *value); diff --git a/src/duckdb/src/include/duckdb/common/enums/logical_operator_type.hpp b/src/duckdb/src/include/duckdb/common/enums/logical_operator_type.hpp index 097d2bf40..2f5c081a8 100644 --- a/src/duckdb/src/include/duckdb/common/enums/logical_operator_type.hpp +++ b/src/duckdb/src/include/duckdb/common/enums/logical_operator_type.hpp @@ -31,6 +31,7 @@ enum class LogicalOperatorType : uint8_t { LOGICAL_PIVOT = 14, LOGICAL_COPY_DATABASE = 15, LOGICAL_SECURE_VIEW = 16, + LOGICAL_TOP_KEY_FILTER = 17, // ----------------------------- // Data sources diff --git a/src/duckdb/src/include/duckdb/common/enums/optimizer_type.hpp b/src/duckdb/src/include/duckdb/common/enums/optimizer_type.hpp index 36dd1e417..4dd9260b8 100644 --- a/src/duckdb/src/include/duckdb/common/enums/optimizer_type.hpp +++ b/src/duckdb/src/include/duckdb/common/enums/optimizer_type.hpp @@ -72,7 +72,8 @@ enum class OptimizerType : uint32_t { WINDOW_FUSION = 55, SET_OPERATION_AGGREGATE = 56, JOIN_TO_SEMI_JOIN = 57, - MARK_JOIN_SIMPLIFIER = 58 + MARK_JOIN_SIMPLIFIER = 58, + GROUP_BY_TOP_KEY = 59 }; string OptimizerTypeToString(OptimizerType type); diff --git a/src/duckdb/src/include/duckdb/common/enums/physical_operator_type.hpp b/src/duckdb/src/include/duckdb/common/enums/physical_operator_type.hpp index cbfab147c..d2f533462 100644 --- a/src/duckdb/src/include/duckdb/common/enums/physical_operator_type.hpp +++ b/src/duckdb/src/include/duckdb/common/enums/physical_operator_type.hpp @@ -30,6 +30,7 @@ enum class PhysicalOperatorType : uint8_t { PARTITIONED_AGGREGATE, LIMITED_DISTINCT, FILTER, + TOP_KEY_FILTER, PROJECTION, COPY_TO_FILE, BATCH_COPY_TO_FILE, diff --git a/src/duckdb/src/include/duckdb/common/exception/http_exception.hpp b/src/duckdb/src/include/duckdb/common/exception/http_exception.hpp index 10617fde2..59f56c6e7 100644 --- a/src/duckdb/src/include/duckdb/common/exception/http_exception.hpp +++ b/src/duckdb/src/include/duckdb/common/exception/http_exception.hpp @@ -8,6 +8,7 @@ #pragma once +#include "duckdb/common/case_insensitive_map.hpp" #include "duckdb/common/exception.hpp" #include "duckdb/common/to_string.hpp" @@ -59,8 +60,13 @@ class HTTPException : public Exception { extra_info["status_code"] = to_string(status_code); extra_info["reason"] = reason; extra_info["response_body"] = response_body; - for (auto &entry : headers) { - extra_info["header_" + entry.first] = entry.second; + // Exception metadata stores only the first field line for each header name. + case_insensitive_set_t seen; + for (const auto &entry : headers) { + const bool first_occurrence = seen.insert(entry.first).second; + if (first_occurrence) { + extra_info.emplace("header_" + entry.first, entry.second); + } } return extra_info; } diff --git a/src/duckdb/src/include/duckdb/common/file_open_flags.hpp b/src/duckdb/src/include/duckdb/common/file_open_flags.hpp index 69c2e7af8..8502eed33 100644 --- a/src/duckdb/src/include/duckdb/common/file_open_flags.hpp +++ b/src/duckdb/src/include/duckdb/common/file_open_flags.hpp @@ -89,7 +89,7 @@ class FileOpenFlags { compression = std::move(new_compression); } - CachingMode GetCachingMode() { + CachingMode GetCachingMode() const { return caching_mode; } void SetCachingMode(CachingMode new_caching_mode) { diff --git a/src/duckdb/src/include/duckdb/common/file_system.hpp b/src/duckdb/src/include/duckdb/common/file_system.hpp index 52846ed2a..3772f9ec3 100644 --- a/src/duckdb/src/include/duckdb/common/file_system.hpp +++ b/src/duckdb/src/include/duckdb/common/file_system.hpp @@ -337,21 +337,6 @@ class FileSystem { DUCKDB_API vector GlobFiles(const string &pattern, const FileGlobInput &input = FileGlobOptions::DISALLOW_EMPTY); - //! registers a sub-file system to handle certain file name prefixes, e.g. http:// etc. - DUCKDB_API virtual void RegisterSubSystem(unique_ptr sub_fs); - //! Register a compression filesystem (both built-in and provided by extensions), keyed by its compression type - DUCKDB_API virtual void RegisterCompressionFilesystem(unique_ptr fs); - - //! Unregister a sub-filesystem by name - DUCKDB_API virtual void UnregisterSubSystem(const string &name); - - // !Extract a sub-filesystem by name, with ownership transferred, return nullptr if not registered or the subsystem - // has been disabled. - DUCKDB_API virtual unique_ptr ExtractSubSystem(const string &name); - - //! List registered sub-filesystems, including builtin ones - DUCKDB_API virtual vector ListSubSystems(); - //! Whether or not a sub-system can handle a specific file path DUCKDB_API virtual bool CanHandleFile(const string &fpath); @@ -387,12 +372,6 @@ class FileSystem { DUCKDB_API static bool IsRemoteFile(const string &path); DUCKDB_API static bool IsRemoteFile(const string &path, string &extension); - DUCKDB_API virtual void SetDisabledFileSystems(const vector &names); - DUCKDB_API virtual vector GetDisabledFileSystems(); - DUCKDB_API virtual bool SubSystemIsDisabled(const string &name); - //! Check if the filesystem that would handle this path is disabled - DUCKDB_API virtual bool IsDisabledForPath(const string &path); - DUCKDB_API static bool IsDirectory(const OpenFileInfo &info); //! Canonicalize a path diff --git a/src/duckdb/src/include/duckdb/common/multi_file/multi_file_function.hpp b/src/duckdb/src/include/duckdb/common/multi_file/multi_file_function.hpp index 4ac76903c..efe9415ec 100644 --- a/src/duckdb/src/include/duckdb/common/multi_file/multi_file_function.hpp +++ b/src/duckdb/src/include/duckdb/common/multi_file/multi_file_function.hpp @@ -889,10 +889,10 @@ class MultiFileFunction : public TableFunction { context, file_idx, *result); result->files_opened++; if (init_result == ReaderInitializeType::SKIP_READING_FILE) { - //! File can be skipped entirely, close it and move on + //! File can be skipped entirely, close it - the scan moves past skipped files when it reaches them, + //! the readers before this one still have to be scanned reader_data->file_state = MultiFileFileState::SKIPPED; reader_data->reader = nullptr; - result->file_index++; } } } diff --git a/src/duckdb/src/include/duckdb/common/multi_file/multi_file_list.hpp b/src/duckdb/src/include/duckdb/common/multi_file/multi_file_list.hpp index 75fe4216b..442e60ecf 100644 --- a/src/duckdb/src/include/duckdb/common/multi_file/multi_file_list.hpp +++ b/src/duckdb/src/include/duckdb/common/multi_file/multi_file_list.hpp @@ -196,32 +196,4 @@ class LazyMultiFileList : public MultiFileList { optional_ptr services; }; -//! MultiFileList that takes a list of globs and resolves all of the globs lazily into files -class GlobMultiFileList : public LazyMultiFileList { -public: - GlobMultiFileList(ClientContext &context, vector globs, FileGlobInput input); - //! Entries that carry explicit open options (i.e. an ExtendedOpenFileInfo) are emitted as-is instead of - //! being glob-expanded - they refer to a file the caller already knows the exact identity of - GlobMultiFileList(ClientContext &context, vector globs, FileGlobInput input); - - vector GetDisplayFileList(optional_idx max_files = optional_idx()) const override; - -protected: - bool ExpandNextPath() const override; - -protected: - //! The ClientContext for globbing - ClientContext &context; - //! The list of globs to expand - const vector globs; - //! Glob input - const FileGlobInput glob_input; - //! The current glob to expand - mutable idx_t current_glob; - //! File lists for the underlying globs - mutable vector> file_lists; - //! Current scan state - mutable MultiFileListScanData scan_state; -}; - } // namespace duckdb diff --git a/src/duckdb/src/include/duckdb/common/multi_file/table_function_multi_file_list.hpp b/src/duckdb/src/include/duckdb/common/multi_file/table_function_multi_file_list.hpp new file mode 100644 index 000000000..9f360503c --- /dev/null +++ b/src/duckdb/src/include/duckdb/common/multi_file/table_function_multi_file_list.hpp @@ -0,0 +1,58 @@ +//===----------------------------------------------------------------------===// +// DuckDB +// +// duckdb/common/multi_file/table_function_multi_file_list.hpp +// +// +//===----------------------------------------------------------------------===// + +#pragma once + +#include "duckdb/common/multi_file/multi_file_list.hpp" +#include "duckdb/common/types/data_chunk.hpp" +#include "duckdb/function/table_function.hpp" + +namespace duckdb { + +//! MultiFileList whose files are produced by a table function from the catalog, which is run lazily - one chunk at +//! a time - as files are requested. The first column the function produces holds the files: a VARCHAR path, or a +//! file struct (a STRUCT or VARIANT) that holds the options to open the file with - see OpenFileInfo::FromValue. +//! An optional second column of type MAP(VARCHAR, ...) holds (further) options to open the file with. +//! The function is run outside of a pipeline, so it cannot have a local state +class TableFunctionMultiFileList : public LazyMultiFileList { +public: + //! Look up the built-in table function in the system catalog, bind it over the given inputs and list the files it + //! produces + TableFunctionMultiFileList(ClientContext &context, const Identifier &function_name, vector inputs, + named_argument_map_t named_parameters = named_argument_map_t()); + ~TableFunctionMultiFileList() override; + + //! Displays the files the function was called with (e.g. the globs), rather than the files they expand to + vector GetDisplayFileList(optional_idx max_files = optional_idx()) const override; + +protected: + bool ExpandNextPath() const override; + +private: + //! Initialize the state of the function - happens on the first expansion, so creating the list does no work + void InitializeFunction() const; + //! Read the files from the chunk the function produced + void ReadFiles(DataChunk &output) const; + +private: + //! The ClientContext the function is run in + ClientContext &context; + //! The table function that produces the files + TableFunction function; + unique_ptr bind_data; + //! The types the function produces - the first one holds the files + vector return_types; + //! The files the function was called with, if its first input is a file or a list of files + vector input_files; + + mutable bool initialized = false; + mutable unique_ptr global_state; + mutable DataChunk chunk; +}; + +} // namespace duckdb diff --git a/src/duckdb/src/include/duckdb/common/open_file_info.hpp b/src/duckdb/src/include/duckdb/common/open_file_info.hpp index 29d4088d9..e3fc1de4a 100644 --- a/src/duckdb/src/include/duckdb/common/open_file_info.hpp +++ b/src/duckdb/src/include/duckdb/common/open_file_info.hpp @@ -60,7 +60,7 @@ struct OpenFileInfo { //! options to open the file with in its other fields (a VARIANT holding either is unpacked). Errors name the //! function that was given the file DUCKDB_API static OpenFileInfo FromValue(const Value &input, const Identifier &function_name); - //! The inverse of FromValue: the path as a VARCHAR when there are no options, a file struct otherwise + //! The inverse of FromValue: the path as a VARCHAR for a plain path, a file struct otherwise DUCKDB_API Value ToValue() const; bool operator<(const OpenFileInfo &rhs) const { diff --git a/src/duckdb/src/include/duckdb/common/opener_file_system.hpp b/src/duckdb/src/include/duckdb/common/opener_file_system.hpp index faf91fa9a..e45ebaf9f 100644 --- a/src/duckdb/src/include/duckdb/common/opener_file_system.hpp +++ b/src/duckdb/src/include/duckdb/common/opener_file_system.hpp @@ -9,6 +9,7 @@ #pragma once #include "duckdb/common/file_system.hpp" +#include "duckdb/common/virtual_file_system.hpp" namespace duckdb { class MultiFileList; @@ -16,9 +17,6 @@ class MultiFileList; // The OpenerFileSystem is wrapper for a file system that pushes an appropriate FileOpener into the various API calls class OpenerFileSystem : public FileSystem { public: - virtual FileSystem &GetFileSystem() const = 0; - virtual optional_ptr GetOpener() const = 0; - void VerifyNoOpener(optional_ptr opener); void VerifyCanAccessDirectory(const string &path); void VerifyCanAccessFile(const string &path); @@ -45,7 +43,7 @@ class OpenerFileSystem : public FileSystem { } void Read(FileHandle &handle, void *buffer, int64_t nr_bytes, idx_t location) override { - GetFileSystem().Read(handle, buffer, nr_bytes, location); + handle.file_system.Read(handle, buffer, nr_bytes, location); } void Write(FileHandle &handle, void *buffer, int64_t nr_bytes, idx_t location) override { @@ -53,41 +51,41 @@ class OpenerFileSystem : public FileSystem { } int64_t Read(FileHandle &handle, void *buffer, int64_t nr_bytes) override { - return GetFileSystem().Read(handle, buffer, nr_bytes); + return handle.file_system.Read(handle, buffer, nr_bytes); } int64_t Write(FileHandle &handle, void *buffer, int64_t nr_bytes) override { - return GetFileSystem().Write(handle, buffer, nr_bytes); + return handle.file_system.Write(handle, buffer, nr_bytes); } int64_t GetFileSize(FileHandle &handle) override { - return GetFileSystem().GetFileSize(handle); + return handle.file_system.GetFileSize(handle); } timestamp_t GetLastModifiedTime(FileHandle &handle) override { - return GetFileSystem().GetLastModifiedTime(handle); + return handle.file_system.GetLastModifiedTime(handle); } string GetVersionTag(FileHandle &handle) override { - return GetFileSystem().GetVersionTag(handle); + return handle.file_system.GetVersionTag(handle); } FileType GetFileType(FileHandle &handle) override { - return GetFileSystem().GetFileType(handle); + return handle.file_system.GetFileType(handle); } FileMetadata Stats(FileHandle &handle) override { - return GetFileSystem().Stats(handle); + return handle.file_system.Stats(handle); } void Truncate(FileHandle &handle, int64_t new_size) override { - GetFileSystem().Truncate(handle, new_size); + handle.file_system.Truncate(handle, new_size); } void FileSync(FileHandle &handle) override { - GetFileSystem().FileSync(handle); + handle.file_system.FileSync(handle); } bool DirectoryExists(const string &directory, optional_ptr opener) override { VerifyNoOpener(opener); VerifyCanAccessDirectory(directory); - return GetFileSystem().DirectoryExists(directory, GetOpener()); + return FindFileSystem(directory).DirectoryExists(directory, GetOpener()); } void CreateDirectory(const string &directory, optional_ptr opener) override { CreateDirectoryExtended(directory, {CreateDirectoryMode::SINGLE}, opener); @@ -99,7 +97,7 @@ class OpenerFileSystem : public FileSystem { } VerifyNoOpener(opener); VerifyCanAccessDirectory(directory); - return GetFileSystem().CreateDirectoryExtended(directory, options, GetOpener()); + return FindFileSystem(directory).CreateDirectoryExtended(directory, options, GetOpener()); } void CreateDirectoriesRecursive(const string &path, optional_ptr opener = nullptr) override { CreateDirectoryExtended(path, {CreateDirectoryMode::RECURSIVE}, opener); @@ -112,7 +110,7 @@ class OpenerFileSystem : public FileSystem { optional_ptr opener) override { VerifyNoOpener(opener); VerifyCanAccessDirectory(directory); - return GetFileSystem().RemoveDirectoryExtended(directory, options, GetOpener()); + return FindFileSystem(directory).RemoveDirectoryExtended(directory, options, GetOpener()); } void MoveFile(const string &source, const string &target, optional_ptr opener) override { @@ -126,7 +124,7 @@ class OpenerFileSystem : public FileSystem { "extensions'", source, target); } - GetFileSystem().MoveFile(source, target, GetOpener()); + FindFileSystem(source).MoveFile(source, target, GetOpener()); } bool DirectoryExists(const string &directory) { @@ -177,85 +175,58 @@ class OpenerFileSystem : public FileSystem { bool FileExists(const string &filename, optional_ptr opener) override { VerifyNoOpener(opener); VerifyCanAccessFile(filename); - return GetFileSystem().FileExists(filename, GetOpener()); + return FindFileSystem(filename).FileExists(filename, GetOpener()); } optional GetStatsIfExists(const OpenFileInfo &file, optional_ptr opener) override { VerifyNoOpener(opener); VerifyCanAccessFile(file.path); - return GetFileSystem().GetStatsIfExists(file, GetOpener()); + return FindFileSystem(file.path).GetStatsIfExists(file, GetOpener()); } bool IsPipe(const string &filename, optional_ptr opener) override { VerifyNoOpener(opener); - return GetFileSystem().IsPipe(filename, GetOpener()); + return FindFileSystem(filename).IsPipe(filename, GetOpener()); } void RemoveFile(const string &filename, optional_ptr opener) override { VerifyNoOpener(opener); VerifyCanAccessFile(filename); - GetFileSystem().RemoveFile(filename, GetOpener()); + FindFileSystem(filename).RemoveFile(filename, GetOpener()); } bool TryRemoveFile(const string &filename, optional_ptr opener) override { VerifyNoOpener(opener); VerifyCanAccessFile(filename); - return GetFileSystem().TryRemoveFile(filename, GetOpener()); + return FindFileSystem(filename).TryRemoveFile(filename, GetOpener()); } void RemoveFiles(const vector &filenames, optional_ptr opener) override { VerifyNoOpener(opener); + reference_map_t> files_by_fs; for (const auto &filename : filenames) { VerifyCanAccessFile(filename); + files_by_fs[FindFileSystem(filename)].push_back(filename); + } + for (auto &entry : files_by_fs) { + entry.first.get().RemoveFiles(entry.second, GetOpener()); } - GetFileSystem().RemoveFiles(filenames, GetOpener()); } string PathSeparator(const string &path) override { - return GetFileSystem().PathSeparator(path); + auto fixed_fs = GetFixedFileSystem(); + auto &fs = fixed_fs ? *fixed_fs : GetFileSystem().FindFileSystem(path, nullptr); + return fs.PathSeparator(path); } vector Glob(const string &path, FileOpener *opener = nullptr) override { VerifyNoOpener(opener); VerifyCanAccessFile(path); - return GetFileSystem().Glob(path, GetOpener().get()); + return FindFileSystem(path).Glob(path, GetOpener().get()); } std::string GetName() const override { - return "OpenerFileSystem - " + GetFileSystem().GetName(); - } - - void RegisterSubSystem(unique_ptr sub_fs) override { - GetFileSystem().RegisterSubSystem(std::move(sub_fs)); - } - - void RegisterCompressionFilesystem(unique_ptr fs) override; - - void UnregisterSubSystem(const string &name) override { - GetFileSystem().UnregisterSubSystem(name); - } - - unique_ptr ExtractSubSystem(const string &name) override { - return GetFileSystem().ExtractSubSystem(name); - } - - void SetDisabledFileSystems(const vector &names) override { - GetFileSystem().SetDisabledFileSystems(names); - } - - vector GetDisabledFileSystems() override { - return GetFileSystem().GetDisabledFileSystems(); - } - - bool SubSystemIsDisabled(const string &name) override { - return GetFileSystem().SubSystemIsDisabled(name); - } - - bool IsDisabledForPath(const string &path) override { - return GetFileSystem().IsDisabledForPath(path); - } - - vector ListSubSystems() override { - return GetFileSystem().ListSubSystems(); + auto fixed_fs = GetFixedFileSystem(); + return "OpenerFileSystem - " + (fixed_fs ? fixed_fs->GetName() : GetFileSystem().GetName()); } protected: @@ -266,7 +237,14 @@ class OpenerFileSystem : public FileSystem { if (IsDuckDBExtensionName(file.path)) { VerifyCanAccessExtension(file.path, flags); } - return GetFileSystem().OpenFile(file, flags, GetOpener()); + auto fixed_fs = GetFixedFileSystem(); + if (fixed_fs) { + return fixed_fs->OpenFile(file, flags, GetOpener()); + } + if (flags.GetCachingMode() == CachingMode::NO_CACHING) { + return GetFileSystem().OpenFile(file, flags, GetOpener()); + } + return OpenCachedFile(file, flags); } bool SupportsOpenFileExtended() const override { @@ -283,7 +261,7 @@ class OpenerFileSystem : public FileSystem { optional_ptr opener) override { VerifyNoOpener(opener); VerifyCanAccessDirectory(directory); - return GetFileSystem().ListFiles(directory, callback, GetOpener().get()); + return FindFileSystem(directory).ListFiles(directory, callback, GetOpener()); } bool SupportsListFilesExtended() const override { @@ -299,10 +277,27 @@ class OpenerFileSystem : public FileSystem { string CanonicalizePath(const string &path_p, optional_ptr opener = nullptr) override { VerifyNoOpener(opener); - return GetFileSystem().CanonicalizePath(path_p, GetOpener()); + return FindFileSystem(path_p).CanonicalizePath(path_p, GetOpener()); } private: + //! The root that picks the file system of a path + virtual VirtualFileSystem &GetFileSystem() const = 0; + virtual optional_ptr GetOpener() const = 0; + //! If set, every path goes to this file system instead of the one the root picks + virtual optional_ptr GetFixedFileSystem() const { + return nullptr; + } + + //! The file system that handles the path + FileSystem &FindFileSystem(const string &path) { + auto fixed_fs = GetFixedFileSystem(); + if (fixed_fs) { + return *fixed_fs; + } + return GetFileSystem().FindFileSystem(path, GetOpener()); + } + unique_ptr OpenCachedFile(const OpenFileInfo &file, const FileOpenFlags &flags); void VerifyCanAccessFileInternal(const string &path, FileType type); }; diff --git a/src/duckdb/src/include/duckdb/common/operator/comparison_operators.hpp b/src/duckdb/src/include/duckdb/common/operator/comparison_operators.hpp index 16bb17703..3473f9cba 100644 --- a/src/duckdb/src/include/duckdb/common/operator/comparison_operators.hpp +++ b/src/duckdb/src/include/duckdb/common/operator/comparison_operators.hpp @@ -339,6 +339,38 @@ inline bool GreaterThan::Operation(const string_t &left, const string_t &right) return left > right; } +//! Branchless string equality, only valid when one side is inlined (e.g. a short constant) +struct InlinedStringEquals { + template + static inline bool Operation(const T &left, const T &right) { + return string_t::StringComparisonOperators::InlinedEquals(left, right); + } +}; +struct InlinedStringNotEquals { + template + static inline bool Operation(const T &left, const T &right) { + return !string_t::StringComparisonOperators::InlinedEquals(left, right); + } +}; + +//! Maps Equals / NotEquals to the operator to use against an inlined string constant +template +struct InlinedStringEqualityOperator { + static constexpr bool ENABLED = false; +}; + +template <> +struct InlinedStringEqualityOperator { + static constexpr bool ENABLED = true; + using OPERATOR = InlinedStringEquals; +}; + +template <> +struct InlinedStringEqualityOperator { + static constexpr bool ENABLED = true; + using OPERATOR = InlinedStringNotEquals; +}; + //===--------------------------------------------------------------------===// // Specialized Interval Comparison Operators //===--------------------------------------------------------------------===// diff --git a/src/duckdb/src/include/duckdb/common/shared_ptr_ipp.hpp b/src/duckdb/src/include/duckdb/common/shared_ptr_ipp.hpp index fe31d24e4..e7400ee44 100644 --- a/src/duckdb/src/include/duckdb/common/shared_ptr_ipp.hpp +++ b/src/duckdb/src/include/duckdb/common/shared_ptr_ipp.hpp @@ -125,6 +125,9 @@ class shared_ptr { // NOLINT: invalid case style // Assign from shared_ptr copy shared_ptr &operator=(const shared_ptr &other) noexcept { + if (this == &other) { + return *this; + } internal = other.internal; return *this; } diff --git a/src/duckdb/src/include/duckdb/common/sorting/topn_heap.hpp b/src/duckdb/src/include/duckdb/common/sorting/topn_heap.hpp index ebfc845c3..1110c88f8 100644 --- a/src/duckdb/src/include/duckdb/common/sorting/topn_heap.hpp +++ b/src/duckdb/src/include/duckdb/common/sorting/topn_heap.hpp @@ -77,6 +77,66 @@ struct TopNBoundaryValue { } }; +//! What the selection does with the rows whose keys are equal to the boundary +enum class TopNBoundaryTies : uint8_t { + //! Only the rows that sort strictly before the boundary are selected. For an operator that already holds the + //! boundary row itself, such as the heap of the Top-N: an equal row cannot replace it. + EXCLUDE, + //! The rows that are equal to the boundary are selected as well. For an operator that has to pass every row of + //! the boundary key on, such as the top-key filter below an aggregate. + INCLUDE +}; + +//! The order of the rows in the selection +enum class TopNBoundaryRowOrder : uint8_t { + //! The rows are selected key by key: the selection is not in the order of the input. For a consumer that does not + //! depend on it, such as a heap. + ANY, + //! The selection is in the order of the input rows. For a streaming operator that forwards the rows. + INPUT_ORDER +}; + +//! The thread-local side of a boundary: its copy of the shared boundary, and the selection of the rows of a chunk of +//! keys that sort before a boundary in the lexicographic order of the keys +class TopNBoundarySelector { +public: + //! not_distinct_from: the NOT DISTINCT FROM comparison of every key with its boundary value (created at plan time), + //! over the input [keys..., boundary values...] + TopNBoundarySelector(ClientContext &context, Allocator &allocator, const vector &orders, + const vector> ¬_distinct_from); + + //! Refreshes the local copy of the shared boundary. Returns whether there is a boundary. + bool Refresh(TopNBoundaryValue &global_boundary); + //! The local copy of the shared boundary as constant vectors (only valid if there is a boundary) + DataChunk &BoundaryValues() { + return boundary_values; + } + //! Decodes a boundary in sort-key format into constant vectors + void Decode(const string &sort_key, DataChunk &target) const; + + //! Selects the rows of "keys" (those of sel, or all of them) that sort before "bound" - constant vectors, one per + //! key - and writes their indexes to result. Returns their number. + idx_t Select(DataChunk &keys, DataChunk &bound, optional_ptr sel, idx_t count, + TopNBoundaryTies ties, TopNBoundaryRowOrder row_order, SelectionVector &result); + +private: + const vector &orders; + vector modifiers; + //! NOT DISTINCT FROM comparison of every key column with its boundary value + vector> not_distinct_from; + //! The shared boundary as this thread last saw it: in sort-key format and as constant vectors + string boundary_val; + DataChunk boundary_values; + DataChunk compare_chunk; + //! The input of not_distinct_from: [keys..., boundary values...] + DataChunk boundary_compare_chunk; + SelectionVector true_sel; + SelectionVector false_sel; + SelectionVector new_remaining_sel; + //! Marks the selected rows to restore the order of the input (allocated on first use) + unsafe_unique_array selected_rows; +}; + struct TopOneFunc { typedef idx_t (*topone_size_t)(); typedef optional_idx (*topone_update_t)(data_ptr_t state_p, Vector &sort_key, const idx_t count); @@ -111,8 +171,6 @@ class TopNHeap { idx_t offset; idx_t heap_size; ExpressionExecutor executor; - //! NOT DISTINCT FROM comparison of every sort column - vector> not_distinct_from; DataChunk sort_chunk; DataChunk heap_data; DataChunk sort_keys; @@ -121,17 +179,9 @@ class TopNHeap { SelectionVector matching_sel; - DataChunk compare_chunk; - //! Cached global boundary value as a set of constant vectors - DataChunk boundary_values; - //! The input of not_distinct_from: [sort columns..., boundary values...] - DataChunk boundary_compare_chunk; - //! Cached global boundary value in sort-key format - string boundary_val; + //! The local copy of the global boundary value and the selection of the rows before it (heap only) + unique_ptr boundary_selector; SelectionVector final_sel; - SelectionVector true_sel; - SelectionVector false_sel; - SelectionVector new_remaining_sel; unique_ptr topone; vector topone_state; diff --git a/src/duckdb/src/include/duckdb/common/types/column/column_data_collection_segment.hpp b/src/duckdb/src/include/duckdb/common/types/column/column_data_collection_segment.hpp index da7285205..e010637d6 100644 --- a/src/duckdb/src/include/duckdb/common/types/column/column_data_collection_segment.hpp +++ b/src/duckdb/src/include/duckdb/common/types/column/column_data_collection_segment.hpp @@ -43,7 +43,9 @@ enum class ColumnDataRepresentation : uint8_t { //! A single value plus a row count CONSTANT, //! Per-row dictionary codes in block data referencing a per-segment dictionary - DICTIONARY + DICTIONARY, + //! Row values of a list child longer than a vector, in block data sized to exactly its count + LARGE_FLAT }; //! The value of a CONSTANT entry @@ -90,7 +92,7 @@ struct VectorMetaData { uint32_t block_id = 0; uint32_t offset = 0; //! The number of entries present in this vector - uint16_t count; + uint32_t count; //! Whether block space has been allocated for this entry bool is_allocated = false; //! The representation class of this entry @@ -173,6 +175,9 @@ class ColumnDataCollectionSegment { //! Allocate space for string data during append (BUFFER_MANAGER_ALLOCATOR only) VectorDataIndex AllocateStringHeap(idx_t size, ChunkMetaData &chunk_meta, ColumnDataAppendState &append_state, VectorDataIndex prev_index = VectorDataIndex()); + //! Allocate a LARGE_FLAT entry holding exactly 'count' rows of a constant-size type + VectorDataIndex AllocateLargeVector(idx_t type_size, idx_t count, ChunkMetaData &chunk_meta, + ChunkManagementState *chunk_state); //! Allocate block storage for an entry whose allocation was deferred or whose storage is replaced void AllocateVectorStorage(VectorDataIndex index, idx_t allocation_size, ChunkMetaData &chunk_meta, ChunkManagementState *chunk_state); @@ -198,6 +203,8 @@ class ColumnDataCollectionSegment { D_ASSERT(index.index < vector_data.size()); return vector_data[index.index]; } + //! The number of rows the block data of an entry has room for + static idx_t GetVectorCapacity(const VectorMetaData &vdata); idx_t ChunkCount() const; //! Get the total *used* size (not cached) @@ -214,9 +221,11 @@ class ColumnDataCollectionSegment { void Verify(); - static idx_t GetDataSize(idx_t type_size); - static validity_t *GetValidityPointerForWriting(data_ptr_t base_ptr, idx_t type_size); - static validity_t *GetValidityPointer(data_ptr_t base_ptr, idx_t type_size, idx_t count); + static idx_t GetDataSize(idx_t type_size, idx_t capacity = STANDARD_VECTOR_SIZE); + static validity_t *GetValidityPointerForWriting(data_ptr_t base_ptr, idx_t type_size, + idx_t capacity = STANDARD_VECTOR_SIZE); + static validity_t *GetValidityPointer(data_ptr_t base_ptr, idx_t type_size, idx_t count, + idx_t capacity = STANDARD_VECTOR_SIZE); private: idx_t ReadVectorInternal(ChunkManagementState &state, VectorDataIndex vector_index, Vector &result); diff --git a/src/duckdb/src/include/duckdb/common/types/selection_vector.hpp b/src/duckdb/src/include/duckdb/common/types/selection_vector.hpp index e980c3308..d77a3ffa0 100644 --- a/src/duckdb/src/include/duckdb/common/types/selection_vector.hpp +++ b/src/duckdb/src/include/duckdb/common/types/selection_vector.hpp @@ -123,6 +123,11 @@ struct SelectionVector { D_ASSERT(idx < capacity); sel_vector[idx] = UnsafeNumericCast(loc); } + //! Writes loc at position count and advances count only if keep is set, without a branch + inline void AppendIf(idx_t &count, idx_t loc, bool keep) { + set_index(count, loc); + count += keep; + } //! Shift entries left by `offset`, i.e. sel[i] = sel[i + offset] for i in [0, count). No-op if offset == 0. void ShiftLeft(const idx_t offset, const idx_t count); inline void swap(idx_t i, idx_t j) { // NOLINT: allow casing for legacy reasons diff --git a/src/duckdb/src/include/duckdb/common/types/string_type.hpp b/src/duckdb/src/include/duckdb/common/types/string_type.hpp index dd0cc8b92..eb13cff50 100644 --- a/src/duckdb/src/include/duckdb/common/types/string_type.hpp +++ b/src/duckdb/src/include/duckdb/common/types/string_type.hpp @@ -21,6 +21,8 @@ namespace duckdb { +enum class StringComparisonMode { GENERIC, INLINED, PREFIX }; + struct string_t { friend struct StringComparisonOperators; @@ -195,28 +197,54 @@ struct string_t { return false; } // compare up to shared length. if still the same, compare lengths + template static bool GreaterThan(const string_t &left, const string_t &right) { - const uint32_t left_length = UnsafeNumericCast(left.GetSize()); - const uint32_t right_length = UnsafeNumericCast(right.GetSize()); - const uint32_t min_length = std::min(left_length, right_length); - #ifndef DUCKDB_DEBUG_NO_INLINE - uint32_t a_prefix = Load(const_data_ptr_cast(left.GetPrefix())); - uint32_t b_prefix = Load(const_data_ptr_cast(right.GetPrefix())); - - // Check on prefix ----- - // We don't need to mask since: - // if the prefix is greater(after bswap), it will stay greater regardless of the extra bytes - // if the prefix is smaller(after bswap), it will stay smaller regardless of the extra bytes - // if the prefix is equal, the extra bytes are guaranteed to be /0 for the shorter one - + const auto a_prefix = left.GetPrefixIntegerComparable(); + const auto b_prefix = right.GetPrefixIntegerComparable(); if (a_prefix != b_prefix) { - return BSwapIfLE(a_prefix) > BSwapIfLE(b_prefix); + return a_prefix > b_prefix; + } + if constexpr (MODE == StringComparisonMode::INLINED) { + if (left.IsInlined() && right.IsInlined()) { + return InlinedSuffixGreaterThan(left, right); + } + } else if constexpr (MODE == StringComparisonMode::PREFIX) { + // Inline strings are zero-padded; out-of-line strings contain more than twelve bytes. + const auto a_suffix = BSwapIfLE(Load(const_data_ptr_cast(left.GetData()) + PREFIX_BYTES)); + const auto b_suffix = BSwapIfLE(Load(const_data_ptr_cast(right.GetData()) + PREFIX_BYTES)); + if (a_suffix != b_suffix) { + return a_suffix > b_suffix; + } + if (left.IsInlined() || right.IsInlined()) { + return left.GetSize() > right.GetSize(); + } + const auto min_length = MinValue(left.GetSize(), right.GetSize()); + const auto cmp = + memcmp(left.GetData() + INLINE_BYTES, right.GetData() + INLINE_BYTES, min_length - INLINE_BYTES); + return cmp > 0 || (cmp == 0 && left.GetSize() > right.GetSize()); } #endif + const auto left_length = left.GetSize(); + const auto right_length = right.GetSize(); + const auto min_length = MinValue(left_length, right_length); auto memcmp_res = memcmp(left.GetData(), right.GetData(), min_length); return memcmp_res > 0 || (memcmp_res == 0 && left_length > right_length); } + //! Both strings must be inlined and have equal prefixes: the zero-padded inlined bytes are compared as one + //! big-endian integer, ties are broken by length (e.g. "a" < "a\0") + static inline bool InlinedSuffixGreaterThan(const string_t &left, const string_t &right) { + const auto a_suffix = BSwapIfLE(Load(const_data_ptr_cast(&left) + 8u)); + const auto b_suffix = BSwapIfLE(Load(const_data_ptr_cast(&right) + 8u)); + return (a_suffix > b_suffix) | ((a_suffix == b_suffix) & (left.GetSize() > right.GetSize())); + } + //! At least one side must be inlined: equal strings then have equal (inlined) lengths, so all 16 bytes match + static inline bool InlinedEquals(const string_t &a, const string_t &b) { + const auto a_ptr = const_data_ptr_cast(&a); + const auto b_ptr = const_data_ptr_cast(&b); + return ((Load(a_ptr) ^ Load(b_ptr)) | + (Load(a_ptr + 8u) ^ Load(b_ptr + 8u))) == 0; + } }; bool operator==(const string_t &r) const { diff --git a/src/duckdb/src/include/duckdb/common/types/variant.hpp b/src/duckdb/src/include/duckdb/common/types/variant.hpp index ca2dcc989..e630a6cdf 100644 --- a/src/duckdb/src/include/duckdb/common/types/variant.hpp +++ b/src/duckdb/src/include/duckdb/common/types/variant.hpp @@ -126,6 +126,8 @@ struct VariantVectorData { Vector &keys; }; +//! The type tag of a value in the encoded VARIANT layout. Storage-level only: code that does not read or write the +//! encoded bytes should use LogicalType / LogicalTypeId (see VariantNode::GetType) enum class VariantLogicalType : uint8_t { VARIANT_NULL = 0, BOOL_TRUE = 1, @@ -166,6 +168,17 @@ enum class VariantLogicalType : uint8_t { ENUM_SIZE /* always kept as last item of the enum */ }; +//! Storage-level helpers: all other variant code should work with LogicalType(Id) instead of VariantLogicalType +//! VARIANT_NULL -> SQLNULL, BOOL_TRUE/BOOL_FALSE -> BOOLEAN, OBJECT -> STRUCT, ARRAY -> LIST +DUCKDB_API LogicalTypeId VariantTypeToLogicalTypeId(VariantLogicalType type); +//! Inverse of VariantTypeToLogicalTypeId, returns false for types that cannot be stored in a VARIANT +//! 'bool_value' selects BOOL_TRUE/BOOL_FALSE for BOOLEAN +DUCKDB_API bool TryVariantTypeFromLogicalTypeId(LogicalTypeId id, VariantLogicalType &result, bool bool_value = false); +//! The LogicalType of a VARIANT value of the given type id. Properties that the id does not carry are defaulted: +//! DECIMAL has no width/scale, STRUCT (OBJECT) has no children, LIST (ARRAY) holds VARIANT +DUCKDB_API LogicalType VariantDefaultType(LogicalTypeId id); +DUCKDB_API VariantLogicalType VariantTypeFromLogicalTypeId(LogicalTypeId id, bool bool_value = false); + struct UnifiedVariantVectorData { public: explicit UnifiedVariantVectorData(const RecursiveUnifiedVectorFormat &variant); diff --git a/src/duckdb/src/include/duckdb/common/types/variant/parquet_variant_iterator.hpp b/src/duckdb/src/include/duckdb/common/types/variant/parquet_variant_iterator.hpp index bbdd85505..9c06864a2 100644 --- a/src/duckdb/src/include/duckdb/common/types/variant/parquet_variant_iterator.hpp +++ b/src/duckdb/src/include/duckdb/common/types/variant/parquet_variant_iterator.hpp @@ -111,7 +111,12 @@ class ParquetVariantNode { return kind == Kind::MISSING; } - DUCKDB_API VariantLogicalType GetTypeId() const; + //! The logical type of the value (see VariantDefaultType for OBJECT/ARRAY values) + DUCKDB_API LogicalType GetType() const; + //! The logical type id of the value (SQLNULL for NULL, STRUCT for an OBJECT, LIST for an ARRAY) + DUCKDB_API LogicalTypeId GetTypeId() const; + //! Returns the payload of a BOOLEAN value + DUCKDB_API bool GetBool() const; //! Returns the fixed-width primitive payload (loaded / re-encoded as T) template T GetData() const; @@ -123,6 +128,11 @@ class ParquetVariantNode { DUCKDB_API ParquetArrayIterator GetArrayChildren() const; private: + friend struct VariantNodeStorageAccess; + + //! The storage-level type of the value + VariantLogicalType GetVariantType() const; + explicit ParquetVariantNode(Kind kind) : kind(kind) { } diff --git a/src/duckdb/src/include/duckdb/common/types/variant/variant_builder.hpp b/src/duckdb/src/include/duckdb/common/types/variant/variant_builder.hpp index 62bdb2088..4c4082a27 100644 --- a/src/duckdb/src/include/duckdb/common/types/variant/variant_builder.hpp +++ b/src/duckdb/src/include/duckdb/common/types/variant/variant_builder.hpp @@ -35,6 +35,14 @@ namespace duckdb { +//! Grants the variant builder access to the storage-level type of a VariantNode / ParquetVariantNode +struct VariantNodeStorageAccess { + template + static VariantLogicalType GetStorageType(const NODE &node) { + return node.GetVariantType(); + } +}; + //===--------------------------------------------------------------------===// // Building a VARIANT in a single pass //===--------------------------------------------------------------------===// @@ -361,6 +369,12 @@ struct VariantBuilder { byte_offsets.push_back(byte_offset); } + //! Emit a primitive value sourced from a VariantNode-like cursor, using the storage type of the cursor + template + void EmitPrimitiveNode(const NODE &it) { + EmitPrimitiveNode(it, VariantNodeStorageAccess::GetStorageType(it)); + } + //! Emit a primitive value sourced from a VariantNode-like cursor. The fixed-width payload is fetched by //! value via 'it.GetData()' (chosen by 'type_id'); strings via 'it.GetString()'; decimals via //! 'it.GetDecimalProperties()' followed by 'it.GetData()' at the physical type implied by the width. @@ -554,7 +568,7 @@ void EmitIterator(const NODE &root, VariantBuilder &builder) { builder.EmitNull(); return; } - auto type_id = node.GetTypeId(); + auto type_id = VariantNodeStorageAccess::GetStorageType(node); switch (type_id) { case VariantLogicalType::OBJECT: { auto children = CollectObjectChildren(node); diff --git a/src/duckdb/src/include/duckdb/common/types/variant_comparison.hpp b/src/duckdb/src/include/duckdb/common/types/variant_comparison.hpp index fda067822..cf74318a2 100644 --- a/src/duckdb/src/include/duckdb/common/types/variant_comparison.hpp +++ b/src/duckdb/src/include/duckdb/common/types/variant_comparison.hpp @@ -100,16 +100,16 @@ struct VariantNumberKey { } }; -VariantComparisonType GetVariantComparisonType(VariantLogicalType type); +VariantComparisonType GetVariantComparisonType(LogicalTypeId type); //! Compute the canonical logical value in the REAL rank, this is not directly byte comparable. -double VariantGetRealValue(VariantLogicalType type_id, const VariantNode &node); +double VariantGetRealValue(LogicalTypeId type_id, const VariantNode &node); //! Compute the number key for any value in the NUMBER rank (integer, decimal or bignum) -VariantNumberKey VariantGetNumberKey(VariantLogicalType type_id, const VariantNode &node); +VariantNumberKey VariantGetNumberKey(LogicalTypeId type_id, const VariantNode &node); //! Compute the nanoseconds since the epoch for any TIMESTAMP rank value -hugeint_t VariantGetTimestampValue(VariantLogicalType type_id, const VariantNode &node); +hugeint_t VariantGetTimestampValue(LogicalTypeId type_id, const VariantNode &node); //! Compute the nanoseconds since the epoch (UTC) for any TIMESTAMP_TZ rank value -hugeint_t VariantGetTimestampTZValue(VariantLogicalType type_id, const VariantNode &node); +hugeint_t VariantGetTimestampTZValue(LogicalTypeId type_id, const VariantNode &node); //! Compute the nanoseconds since midnight for any TIME rank value -int64_t VariantGetTimeValue(VariantLogicalType type_id, const VariantNode &node); +int64_t VariantGetTimeValue(LogicalTypeId type_id, const VariantNode &node); } // namespace duckdb diff --git a/src/duckdb/src/include/duckdb/common/types/variant_iterator.hpp b/src/duckdb/src/include/duckdb/common/types/variant_iterator.hpp index 4f11f9621..db38ce6d8 100644 --- a/src/duckdb/src/include/duckdb/common/types/variant_iterator.hpp +++ b/src/duckdb/src/include/duckdb/common/types/variant_iterator.hpp @@ -135,6 +135,7 @@ class VariantIterator { class VariantArrayIterator; class VariantObjectIterator; +struct VariantNodeStorageAccess; //! A lightweight cursor pointing at a single logical VARIANT value. class VariantNode { @@ -158,14 +159,19 @@ class VariantNode { return kind == Kind::MISSING; } - //! The logical type of the value the cursor points at - VariantLogicalType GetTypeId() const; + //! The logical type of the value the cursor points at (see VariantDefaultType for OBJECT/ARRAY values) + LogicalType GetType() const; + //! The logical type id of the value the cursor points at (SQLNULL for a VARIANT NULL, STRUCT for an OBJECT, + //! LIST for an ARRAY) + LogicalTypeId GetTypeId() const; + //! Returns the payload of a BOOLEAN value + bool GetBool() const; //! Returns the fixed-width primitive payload loaded as T (e.g. GetData()). For a DECIMAL the //! payload follows the (width, scale) prefix, so T must match the physical type implied by the width. template T GetData() const { - if (GetTypeId() == VariantLogicalType::DECIMAL) { + if (GetVariantType() == VariantLogicalType::DECIMAL) { return Load(GetDecimal().value_ptr); } return Load(GetDataPointer()); @@ -192,6 +198,9 @@ class VariantNode { VariantArrayIterator GetArrayChildren() const; private: + //! The storage-level type of the value the cursor points at + VariantLogicalType GetVariantType() const; + //! Resolve the shredded node (a "STRUCT(typed_value, [untyped_value_index])" wrapper, or a //! flattened primitive) at the given index into a concrete cursor static VariantNode ResolveShredded(const VariantIterator &state, const ShreddedVariantIterator &node, idx_t index, @@ -225,6 +234,7 @@ class VariantNode { friend class VariantIterator; friend class VariantArrayIterator; friend class VariantObjectIterator; + friend struct VariantNodeStorageAccess; }; //! Lazily iterates the element values of an ARRAY VariantNode. Random-access: no child cursor is diff --git a/src/duckdb/src/include/duckdb/common/types/variant_visitor.hpp b/src/duckdb/src/include/duckdb/common/types/variant_visitor.hpp index 76b17c47a..2b783106f 100644 --- a/src/duckdb/src/include/duckdb/common/types/variant_visitor.hpp +++ b/src/duckdb/src/include/duckdb/common/types/variant_visitor.hpp @@ -93,7 +93,8 @@ class VariantVisitor { case VariantLogicalType::BIGNUM: case VariantLogicalType::GEOMETRY: case VariantLogicalType::GEOGRAPHY: - return VisitString(type_id, variant, row, values_idx, std::forward(args)...); + return VisitString(VariantTypeToLogicalTypeId(type_id), variant, row, values_idx, + std::forward(args)...); case VariantLogicalType::DECIMAL: return VisitDecimal(variant, row, values_idx, std::forward(args)...); case VariantLogicalType::ARRAY: { @@ -123,7 +124,8 @@ class VariantVisitor { case VariantLogicalType::TIMESTAMP_NANOS_TZ: return Visitor::VisitTimestampTZNanos(Load(ptr), std::forward(args)...); default: - return Visitor::VisitDefault(type_id, ptr, std::forward(args)...); + return Visitor::VisitDefault(VariantDefaultType(VariantTypeToLogicalTypeId(type_id)), ptr, + std::forward(args)...); } } @@ -131,83 +133,78 @@ class VariantVisitor { static ReturnType Visit(const VariantNode &node, idx_t depth, Args &&...args) { CheckDepth(depth); if (node.IsNull() || node.IsMissing()) { - VisitMetadata(VariantLogicalType::VARIANT_NULL, args...); return Visitor::VisitNull(std::forward(args)...); } auto type_id = node.GetTypeId(); - VisitMetadata(type_id, args...); - switch (type_id) { - case VariantLogicalType::VARIANT_NULL: + case LogicalTypeId::SQLNULL: return Visitor::VisitNull(std::forward(args)...); - case VariantLogicalType::BOOL_TRUE: - return Visitor::VisitBoolean(true, std::forward(args)...); - case VariantLogicalType::BOOL_FALSE: - return Visitor::VisitBoolean(false, std::forward(args)...); - case VariantLogicalType::INT8: + case LogicalTypeId::BOOLEAN: + return Visitor::VisitBoolean(node.GetBool(), std::forward(args)...); + case LogicalTypeId::TINYINT: return Visitor::template VisitInteger(node.GetData(), std::forward(args)...); - case VariantLogicalType::INT16: + case LogicalTypeId::SMALLINT: return Visitor::template VisitInteger(node.GetData(), std::forward(args)...); - case VariantLogicalType::INT32: + case LogicalTypeId::INTEGER: return Visitor::template VisitInteger(node.GetData(), std::forward(args)...); - case VariantLogicalType::INT64: + case LogicalTypeId::BIGINT: return Visitor::template VisitInteger(node.GetData(), std::forward(args)...); - case VariantLogicalType::INT128: + case LogicalTypeId::HUGEINT: return Visitor::template VisitInteger(node.GetData(), std::forward(args)...); - case VariantLogicalType::UINT8: + case LogicalTypeId::UTINYINT: return Visitor::template VisitInteger(node.GetData(), std::forward(args)...); - case VariantLogicalType::UINT16: + case LogicalTypeId::USMALLINT: return Visitor::template VisitInteger(node.GetData(), std::forward(args)...); - case VariantLogicalType::UINT32: + case LogicalTypeId::UINTEGER: return Visitor::template VisitInteger(node.GetData(), std::forward(args)...); - case VariantLogicalType::UINT64: + case LogicalTypeId::UBIGINT: return Visitor::template VisitInteger(node.GetData(), std::forward(args)...); - case VariantLogicalType::UINT128: + case LogicalTypeId::UHUGEINT: return Visitor::template VisitInteger(node.GetData(), std::forward(args)...); - case VariantLogicalType::FLOAT: + case LogicalTypeId::FLOAT: return Visitor::VisitFloat(node.GetData(), std::forward(args)...); - case VariantLogicalType::DOUBLE: + case LogicalTypeId::DOUBLE: return Visitor::VisitDouble(node.GetData(), std::forward(args)...); - case VariantLogicalType::UUID: + case LogicalTypeId::UUID: return Visitor::VisitUUID(node.GetData(), std::forward(args)...); - case VariantLogicalType::DATE: + case LogicalTypeId::DATE: return Visitor::VisitDate(node.GetData(), std::forward(args)...); - case VariantLogicalType::INTERVAL: + case LogicalTypeId::INTERVAL: return Visitor::VisitInterval(node.GetData(), std::forward(args)...); - case VariantLogicalType::VARCHAR: - case VariantLogicalType::BLOB: - case VariantLogicalType::BITSTRING: - case VariantLogicalType::BIGNUM: - case VariantLogicalType::GEOMETRY: - case VariantLogicalType::GEOGRAPHY: + case LogicalTypeId::VARCHAR: + case LogicalTypeId::BLOB: + case LogicalTypeId::BIT: + case LogicalTypeId::BIGNUM: + case LogicalTypeId::GEOMETRY: + case LogicalTypeId::GEOGRAPHY: return VisitString(type_id, node.GetString(), std::forward(args)...); - case VariantLogicalType::DECIMAL: + case LogicalTypeId::DECIMAL: return VisitDecimal(node, std::forward(args)...); - case VariantLogicalType::ARRAY: + case LogicalTypeId::LIST: return Visitor::VisitArray(node, depth, std::forward(args)...); - case VariantLogicalType::OBJECT: + case LogicalTypeId::STRUCT: return Visitor::VisitObject(node, depth, std::forward(args)...); - case VariantLogicalType::TIME_MICROS: + case LogicalTypeId::TIME: return Visitor::VisitTime(node.GetData(), std::forward(args)...); - case VariantLogicalType::TIME_NANOS: + case LogicalTypeId::TIME_NS: return Visitor::VisitTimeNanos(node.GetData(), std::forward(args)...); - case VariantLogicalType::TIME_MICROS_TZ: + case LogicalTypeId::TIME_TZ: return Visitor::VisitTimeTZ(node.GetData(), std::forward(args)...); - case VariantLogicalType::TIMESTAMP_SEC: + case LogicalTypeId::TIMESTAMP_SEC: return Visitor::VisitTimestampSec(node.GetData(), std::forward(args)...); - case VariantLogicalType::TIMESTAMP_MILIS: + case LogicalTypeId::TIMESTAMP_MS: return Visitor::VisitTimestampMs(node.GetData(), std::forward(args)...); - case VariantLogicalType::TIMESTAMP_MICROS: + case LogicalTypeId::TIMESTAMP: return Visitor::VisitTimestamp(node.GetData(), std::forward(args)...); - case VariantLogicalType::TIMESTAMP_NANOS: + case LogicalTypeId::TIMESTAMP_NS: return Visitor::VisitTimestampNanos(node.GetData(), std::forward(args)...); - case VariantLogicalType::TIMESTAMP_MICROS_TZ: + case LogicalTypeId::TIMESTAMP_TZ: return Visitor::VisitTimestampTZ(node.GetData(), std::forward(args)...); - case VariantLogicalType::TIMESTAMP_NANOS_TZ: + case LogicalTypeId::TIMESTAMP_TZ_NS: return Visitor::VisitTimestampTZNanos(node.GetData(), std::forward(args)...); default: - return Visitor::VisitDefault(type_id, nullptr, std::forward(args)...); + return Visitor::VisitDefault(node.GetType(), nullptr, std::forward(args)...); } } @@ -305,48 +302,48 @@ class VariantVisitor { } template - static ReturnType VisitString(VariantLogicalType type_id, const UnifiedVariantVectorData &variant, idx_t row, + static ReturnType VisitString(LogicalTypeId type_id, const UnifiedVariantVectorData &variant, idx_t row, uint32_t values_idx, Args &&...args) { auto decoded_string = VariantUtils::DecodeStringData(variant, row, values_idx); - if (type_id == VariantLogicalType::VARCHAR) { + if (type_id == LogicalTypeId::VARCHAR) { return Visitor::VisitString(decoded_string, std::forward(args)...); } - if (type_id == VariantLogicalType::BLOB) { + if (type_id == LogicalTypeId::BLOB) { return Visitor::VisitBlob(decoded_string, std::forward(args)...); } - if (type_id == VariantLogicalType::BIGNUM) { + if (type_id == LogicalTypeId::BIGNUM) { return Visitor::VisitBignum(decoded_string, std::forward(args)...); } - if (type_id == VariantLogicalType::GEOMETRY) { + if (type_id == LogicalTypeId::GEOMETRY) { return Visitor::VisitGeometry(decoded_string, std::forward(args)...); } - if (type_id == VariantLogicalType::GEOGRAPHY) { + if (type_id == LogicalTypeId::GEOGRAPHY) { return Visitor::VisitGeography(decoded_string, std::forward(args)...); } - if (type_id == VariantLogicalType::BITSTRING) { + if (type_id == LogicalTypeId::BIT) { return Visitor::VisitBitstring(decoded_string, std::forward(args)...); } throw InternalException("String-backed variant type (%s) not handled", EnumUtil::ToString(type_id)); } template - static ReturnType VisitString(VariantLogicalType type_id, const string_t &value, Args &&...args) { - if (type_id == VariantLogicalType::VARCHAR) { + static ReturnType VisitString(LogicalTypeId type_id, const string_t &value, Args &&...args) { + if (type_id == LogicalTypeId::VARCHAR) { return Visitor::VisitString(value, std::forward(args)...); } - if (type_id == VariantLogicalType::BLOB) { + if (type_id == LogicalTypeId::BLOB) { return Visitor::VisitBlob(value, std::forward(args)...); } - if (type_id == VariantLogicalType::BIGNUM) { + if (type_id == LogicalTypeId::BIGNUM) { return Visitor::VisitBignum(value, std::forward(args)...); } - if (type_id == VariantLogicalType::GEOMETRY) { + if (type_id == LogicalTypeId::GEOMETRY) { return Visitor::VisitGeometry(value, std::forward(args)...); } - if (type_id == VariantLogicalType::GEOGRAPHY) { + if (type_id == LogicalTypeId::GEOGRAPHY) { return Visitor::VisitGeography(value, std::forward(args)...); } - if (type_id == VariantLogicalType::BITSTRING) { + if (type_id == LogicalTypeId::BIT) { return Visitor::VisitBitstring(value, std::forward(args)...); } throw InternalException("String-backed variant type (%s) not handled", EnumUtil::ToString(type_id)); diff --git a/src/duckdb/src/include/duckdb/common/unordered_multimap.hpp b/src/duckdb/src/include/duckdb/common/unordered_multimap.hpp new file mode 100644 index 000000000..7bf66f960 --- /dev/null +++ b/src/duckdb/src/include/duckdb/common/unordered_multimap.hpp @@ -0,0 +1,15 @@ +//===----------------------------------------------------------------------===// +// DuckDB +// +// duckdb/common/unordered_multimap.hpp +// +// +//===----------------------------------------------------------------------===// + +#pragma once + +#include + +namespace duckdb { +using std::unordered_multimap; +} diff --git a/src/duckdb/src/include/duckdb/common/vector_operations/string_comparison.hpp b/src/duckdb/src/include/duckdb/common/vector_operations/string_comparison.hpp new file mode 100644 index 000000000..83f0ef2ea --- /dev/null +++ b/src/duckdb/src/include/duckdb/common/vector_operations/string_comparison.hpp @@ -0,0 +1,93 @@ +//===----------------------------------------------------------------------===// +// DuckDB +// +// duckdb/common/vector_operations/string_comparison.hpp +// +//===----------------------------------------------------------------------===// + +#pragma once + +#include "duckdb/common/vector_operations/binary_executor.hpp" + +namespace duckdb { + +template +struct StringOrderingOperator { + template + static bool Operation(const T &left, const T &right) { + using COMPARE = string_t::StringComparisonOperators; + if constexpr (std::is_same_v) { + return COMPARE::GreaterThan(left, right); + } else if constexpr (std::is_same_v) { + return COMPARE::GreaterThan(right, left); + } else if constexpr (std::is_same_v) { + return !COMPARE::GreaterThan(right, left); + } else { + static_assert(std::is_same_v, "Expected an ordering comparison"); + return !COMPARE::GreaterThan(left, right); + } + } +}; + +struct StringComparison { + template + static constexpr bool IsOrdering() { + return std::is_same_v || std::is_same_v || + std::is_same_v || std::is_same_v; + } + + static bool HasInlinedConstant(const Vector &left, const Vector &right); + static StringComparisonMode SelectMode(const Vector &left, const Vector &right, idx_t count); + static StringComparisonMode SelectMode(const UnifiedVectorFormat &input, const string_t &constant, + const SelectionVector &sel, idx_t count); + + template + static auto Dispatch(StringComparisonMode mode, FUNC &&function) { + switch (mode) { + case StringComparisonMode::GENERIC: + return function(StringOrderingOperator()); + case StringComparisonMode::PREFIX: + return function(StringOrderingOperator()); + default: + return function(OP()); + } + } + + template + static void Execute(const Vector &left, const Vector &right, Vector &result) { + if constexpr (InlinedStringEqualityOperator::ENABLED) { + if (HasInlinedConstant(left, right)) { + using INLINED_OP = typename InlinedStringEqualityOperator::OPERATOR; + BinaryExecutor::Execute(left, right, result); + return; + } + } else if constexpr (IsOrdering()) { + if (left.size() == right.size()) { + return Dispatch(SelectMode(left, right, left.size()), [&](auto op) { + BinaryExecutor::Execute(left, right, result); + }); + } + } + BinaryExecutor::Execute(left, right, result); + } + + template + static idx_t Select(const Vector &left, const Vector &right, const SelectionVector *sel, idx_t count, + SelectionVector *true_sel, SelectionVector *false_sel) { + if constexpr (InlinedStringEqualityOperator::ENABLED) { + if (HasInlinedConstant(left, right)) { + using INLINED_OP = typename InlinedStringEqualityOperator::OPERATOR; + return BinaryExecutor::Select(left, right, sel, count, true_sel, + false_sel); + } + } else if constexpr (IsOrdering()) { + return Dispatch(SelectMode(left, right, count), [&](auto op) { + return BinaryExecutor::Select(left, right, sel, count, true_sel, + false_sel); + }); + } + return BinaryExecutor::Select(left, right, sel, count, true_sel, false_sel); + } +}; + +} // namespace duckdb diff --git a/src/duckdb/src/include/duckdb/common/virtual_file_system.hpp b/src/duckdb/src/include/duckdb/common/virtual_file_system.hpp index cc3f48c5b..2ce661973 100644 --- a/src/duckdb/src/include/duckdb/common/virtual_file_system.hpp +++ b/src/duckdb/src/include/duckdb/common/virtual_file_system.hpp @@ -15,99 +15,49 @@ namespace duckdb { struct FileSystemRegistry; +class DatabaseInstance; +class ClientContext; -// bunch of wrappers to allow registering protocol handlers -class VirtualFileSystem : public FileSystem { +//! The root of the file systems of a database: it picks the file system that handles a path from the registered +//! protocol handlers, applies compression and pipes on top, and holds the registry of the file systems and their +//! compression. It is not a FileSystem itself: the files it opens belong to the file system that handled them. +class VirtualFileSystem { public: - VirtualFileSystem(); - explicit VirtualFileSystem(unique_ptr &&inner_file_system); - ~VirtualFileSystem() override; - - void Read(FileHandle &handle, void *buffer, int64_t nr_bytes, idx_t location) override; - void Write(FileHandle &handle, void *buffer, int64_t nr_bytes, idx_t location) override; - int64_t Read(FileHandle &handle, void *buffer, int64_t nr_bytes) override; - int64_t Write(FileHandle &handle, void *buffer, int64_t nr_bytes) override; - - unique_ptr MemoryMapFile(const OpenFileInfo &path, FileOpenFlags flags, - const MMapOptions &options, - optional_ptr opener = nullptr) override; - - int64_t GetFileSize(FileHandle &handle) override; - timestamp_t GetLastModifiedTime(FileHandle &handle) override; - string GetVersionTag(FileHandle &handle) override; - FileType GetFileType(FileHandle &handle) override; - FileMetadata Stats(FileHandle &handle) override; - optional GetStatsIfExists(const OpenFileInfo &file, - optional_ptr opener = nullptr) override; - - void Truncate(FileHandle &handle, int64_t new_size) override; - - void FileSync(FileHandle &handle) override; - - // need to look up correct fs for this - bool DirectoryExists(const string &directory, optional_ptr opener) override; - void CreateDirectory(const string &directory, optional_ptr opener) override; - bool CreateDirectoryExtended(const string &directory, const CreateDirectoryOptions &options, - optional_ptr opener = nullptr) override; - void CreateDirectoriesRecursive(const string &path, optional_ptr opener = nullptr) override; - - void RemoveDirectory(const string &directory, optional_ptr opener) override; - bool RemoveDirectoryExtended(const string &directory, const RemoveDirectoryOptions &options, - optional_ptr opener = nullptr) override; - - void MoveFile(const string &source, const string &target, optional_ptr opener) override; - - bool FileExists(const string &filename, optional_ptr opener) override; - - bool IsPipe(const string &filename, optional_ptr opener) override; - void RemoveFile(const string &filename, optional_ptr opener) override; - bool TryRemoveFile(const string &filename, optional_ptr opener) override; - void RemoveFiles(const vector &filenames, optional_ptr opener) override; - - void RegisterSubSystem(unique_ptr fs) override; - void RegisterCompressionFilesystem(unique_ptr fs) override; - void UnregisterSubSystem(const string &name) override; - unique_ptr ExtractSubSystem(const string &name) override; - - vector ListSubSystems() override; - - FileSystem &GetDefaultFileSystem(); - //! The local file system: the default file system if it is local, otherwise one owned by this VirtualFileSystem - FileSystem &GetLocalFileSystem(); - - std::string GetName() const override; - - void SetDisabledFileSystems(const vector &names) override; - vector GetDisabledFileSystems() override; - bool SubSystemIsDisabled(const string &name) override; - bool IsDisabledForPath(const string &path) override; - - string PathSeparator(const string &path) override; - - string CanonicalizePath(const string &path_p, optional_ptr opener) override; - -protected: - unique_ptr OpenFileExtended(const OpenFileInfo &file, FileOpenFlags flags, - optional_ptr opener) override; - bool SupportsOpenFileExtended() const override { - return true; - } - - bool ListFilesExtended(const string &directory, const std::function &callback, - optional_ptr opener) override; - - bool SupportsListFilesExtended() const override { - return true; - } - - unique_ptr GlobFilesExtended(const string &path, const FileGlobInput &input, - optional_ptr opener) override; - bool SupportsGlobExtended() const override { - return true; - } + DUCKDB_API VirtualFileSystem(); + DUCKDB_API explicit VirtualFileSystem(unique_ptr &&inner_file_system); + DUCKDB_API ~VirtualFileSystem(); + + //! The root file system of a database + DUCKDB_API static VirtualFileSystem &Get(DatabaseInstance &db); + DUCKDB_API static VirtualFileSystem &Get(ClientContext &context); + + //! Opens a file with the file system that handles the path, and applies compression and pipes on top of it + DUCKDB_API unique_ptr OpenFile(const OpenFileInfo &file, FileOpenFlags flags, + optional_ptr opener); + //! Applies compression and pipes on top of a handle that was opened uncompressed + DUCKDB_API unique_ptr WrapOpenedFile(unique_ptr handle, const OpenFileInfo &file, + const FileOpenFlags &flags, optional_ptr opener); + //! The file system that handles a path: a registered sub-system, or the default file system. Throws if it is + //! disabled. Loads the extension that provides the file system if there is one. + DUCKDB_API FileSystem &FindFileSystem(const string &path, optional_ptr opener); + + DUCKDB_API void RegisterSubSystem(unique_ptr fs); + DUCKDB_API void RegisterCompressionFilesystem(unique_ptr fs); + DUCKDB_API void UnregisterSubSystem(const string &name); + DUCKDB_API unique_ptr ExtractSubSystem(const string &name); + DUCKDB_API vector ListSubSystems(); + + DUCKDB_API void SetDisabledFileSystems(const vector &names); + DUCKDB_API vector GetDisabledFileSystems(); + DUCKDB_API bool SubSystemIsDisabled(const string &name); + DUCKDB_API bool IsDisabledForPath(const string &path); + + //! The file system of paths no sub-system handles. Does not check whether it is disabled. + DUCKDB_API FileSystem &GetDefaultFileSystem(); + + DUCKDB_API std::string GetName() const; private: - FileSystem &FindFileSystem(const string &path, optional_ptr file_opener); FileSystem &FindFileSystem(shared_ptr ®istry, const string &path, optional_ptr file_opener); optional_ptr FindFileSystemInternal(FileSystemRegistry ®istry, const string &path); @@ -118,8 +68,6 @@ class VirtualFileSystem : public FileSystem { bool for_writing); private: - //! Only set if the default file system is not local - unique_ptr owned_local_file_system; mutex registry_lock; shared_ptr file_system_registry; vector> unregistered_file_systems; diff --git a/src/duckdb/src/include/duckdb/execution/index/art/art.hpp b/src/duckdb/src/include/duckdb/execution/index/art/art.hpp index 1755ff8b3..90262448f 100644 --- a/src/duckdb/src/include/duckdb/execution/index/art/art.hpp +++ b/src/duckdb/src/include/duckdb/execution/index/art/art.hpp @@ -80,6 +80,7 @@ class ART : public BoundIndex { public: //! Try to initialize a scan on the ART with the given expression and filter. + //! The scan can return a superset of the rows matching the filter. unique_ptr TryInitializeScan(const Expression &expr, const Expression &filter_expr) const; //! Initializes a scan for multiple equality lookup values. unique_ptr InitializeBatchScan(unique_ptr key_columns) const; diff --git a/src/duckdb/src/include/duckdb/execution/join_hashtable.hpp b/src/duckdb/src/include/duckdb/execution/join_hashtable.hpp index 6f67b787f..7370caa1c 100644 --- a/src/duckdb/src/include/duckdb/execution/join_hashtable.hpp +++ b/src/duckdb/src/include/duckdb/execution/join_hashtable.hpp @@ -300,6 +300,13 @@ class JoinHashTable { Vector hashes; Vector ht_offsets_and_salts_v; Vector hashes_dense_v; + //! Rows that probe another entry, and rows that found their entry in the current round + SelectionVector rows_to_probe_sel; + SelectionVector rows_found_sel; + //! Loaded ht entry and probe flags per dense row + unsafe_unique_array dense_entries; + Vector is_match_v; + Vector needs_next_v; //! Executes the hash table's hash expression over the probe keys unique_ptr hash_executor; unique_ptr spill_hashes; @@ -710,6 +717,10 @@ class JoinHashTable { static constexpr double EXTERNAL_LOAD_FACTOR = 1.5; //! Minimum capacity of the pointer table static constexpr idx_t MINIMUM_CAPACITY = 16384; + //! Pointer tables above this capacity prefetch the entries the probe reads + static constexpr idx_t PREFETCH_MIN_CAPACITY = idx_t(1) << 20; + //! Vectors of at most this many rows probe row by row with branches; longer vectors probe branch-free + static constexpr idx_t BRANCHING_PROBE_MAX_COUNT = 32; double load_factor = DEFAULT_LOAD_FACTOR; diff --git a/src/duckdb/src/include/duckdb/execution/operator/csv_scanner/encode/csv_encoder.hpp b/src/duckdb/src/include/duckdb/execution/operator/csv_scanner/encode/csv_encoder.hpp index 81da5a1c2..391ace8c1 100644 --- a/src/duckdb/src/include/duckdb/execution/operator/csv_scanner/encode/csv_encoder.hpp +++ b/src/duckdb/src/include/duckdb/execution/operator/csv_scanner/encode/csv_encoder.hpp @@ -77,6 +77,8 @@ class CSVEncoder { DataChunk decode_input; //! The maximum number of input bytes that make up one character idx_t minimum_input_window = 1; + //! The maximum number of input bytes decoded per call, so the decoded string stays cache resident + static constexpr idx_t MAX_DECODE_SLICE = 64 * 1024; //! Pass-on Byte, used to check if we are done with the file, but must be appended to next buffer char pass_on_byte; bool has_pass_on_byte = false; @@ -85,7 +87,8 @@ class CSVEncoder { private: //! Decodes the encoded buffer into the output buffer until either one is exhausted idx_t DecodeBuffer(char *output_buffer, idx_t output_pos, idx_t output_size); - //! Runs the encoding's scalar function over the input, returns the number of bytes consumed - idx_t Decode(const char *input, idx_t input_size, bool is_last, string &decoded); + //! Runs the encoding's scalar function over the input, returns the number of bytes consumed. + //! The decoded string lives in the result vector. + idx_t Decode(const char *input, idx_t input_size, bool is_last, Vector &result, string_t &decoded); }; } // namespace duckdb diff --git a/src/duckdb/src/include/duckdb/execution/operator/filter/physical_top_key_filter.hpp b/src/duckdb/src/include/duckdb/execution/operator/filter/physical_top_key_filter.hpp new file mode 100644 index 000000000..70212826c --- /dev/null +++ b/src/duckdb/src/include/duckdb/execution/operator/filter/physical_top_key_filter.hpp @@ -0,0 +1,72 @@ +//===----------------------------------------------------------------------===// +// DuckDB +// +// duckdb/execution/operator/filter/physical_top_key_filter.hpp +// +// +//===----------------------------------------------------------------------===// + +#pragma once + +#include "duckdb/execution/physical_operator.hpp" +#include "duckdb/planner/bound_query_node.hpp" + +namespace duckdb { +struct DynamicFilterData; + +//! PhysicalTopKeyFilter is a streaming filter below a grouped aggregate whose Top-N orders by a prefix of the group +//! keys. Every thread keeps the smallest "limit" distinct key tuples that it has seen. The largest of them is not +//! smaller than the limit-th smallest distinct key tuple of the whole input, and neither is the smallest such bound of +//! all threads, which is shared (TopNBoundaryValue). A row is removed only if its key tuple sorts strictly after a +//! bound (ties pass), so that every group that the Top-N can return still receives all of its rows. +//! The pruning is conservative. The contract of the operator is: +//! * it never removes a row of a group whose key tuple is among the "limit" smallest distinct key tuples of its +//! input (the groups that the Top-N above the aggregate can return), and +//! * it may pass any other row. +//! Its output is therefore a superset of the rows that are needed, not the rows of exactly "limit" distinct keys: rows +//! pass unfiltered while a thread warms up, while no bound has been published, while a thread works with an older +//! (larger) bound than the current one, after a thread has stopped filtering, and the bound of a thread is only as +//! small as the keys that it has seen itself. The aggregate above can receive rows of - and build - groups that are +//! not part of the result, with a part of their rows only. Only the Top-N above the aggregate decides the result: the +//! groups it returns are complete, and a group that is incomplete sorts after "limit" complete ones. +//! The rows that pass keep their order, so that aggregates that depend on the order of their input see the rows in the +//! order in which they would see them without the filter. That is why this is not a caching operator: in a pipeline +//! that ends in a hash aggregate the cache holds back a small chunk while a later full chunk passes. +class PhysicalTopKeyFilter : public PhysicalOperator { +public: + static constexpr const PhysicalOperatorType TYPE = PhysicalOperatorType::TOP_KEY_FILTER; + +public: + PhysicalTopKeyFilter(PhysicalPlan &physical_plan, ClientContext &context, vector types, + vector orders, idx_t limit, shared_ptr dynamic_filter, + idx_t estimated_cardinality); + ~PhysicalTopKeyFilter() override; + + //! The keys and their order + vector orders; + //! NOT DISTINCT FROM comparison of the boundary value for every key + vector> not_distinct_from; + //! The number of smallest distinct key tuples whose rows are guaranteed to pass. Not an upper bound of the number + //! of distinct key tuples in the output. + idx_t limit; + //! Dynamic table filter on the first key (if any) + shared_ptr dynamic_filter; + +public: + void InitializeOutputChunk(Allocator &allocator, DataChunk &chunk) const override; + unique_ptr GetOperatorState(ExecutionContext &context) const override; + unique_ptr GetGlobalOperatorState(ClientContext &context) const override; + + bool ParallelOperator() const override { + return true; + } + PipelineExternalInputSupport GetExternalInputSupport() const override { + return PipelineExternalInputSupport::SUPPORTED; + } + + InsertionOrderPreservingMap ParamsToString() const override; + + OperatorResultType Execute(ExecutionContext &context, DataChunk &input, DataChunk &chunk, + GlobalOperatorState &gstate, OperatorState &state) const override; +}; +} // namespace duckdb diff --git a/src/duckdb/src/include/duckdb/execution/operator/helper/physical_update_extensions.hpp b/src/duckdb/src/include/duckdb/execution/operator/helper/physical_update_extensions.hpp index de2f2a67f..07e1bd612 100644 --- a/src/duckdb/src/include/duckdb/execution/operator/helper/physical_update_extensions.hpp +++ b/src/duckdb/src/include/duckdb/execution/operator/helper/physical_update_extensions.hpp @@ -15,10 +15,15 @@ namespace duckdb { struct UpdateExtensionsGlobalState : public GlobalSourceState { - UpdateExtensionsGlobalState() : offset(0) { + UpdateExtensionsGlobalState() : updates_scheduled(false), offset(0) { } + //! One entry per extension, pending updates fill in their entry when they are executed vector update_result_entries; + //! The extensions that need a download, executed concurrently as async tasks + vector pending_updates; + //! Whether the pending updates have been scheduled + bool updates_scheduled; idx_t offset; }; @@ -32,7 +37,7 @@ class PhysicalUpdateExtensions : public PhysicalOperator { idx_t estimated_cardinality) : PhysicalOperator(physical_plan, PhysicalOperatorType::UPDATE_EXTENSIONS, {LogicalType::VARCHAR, LogicalType::VARCHAR, LogicalType::VARCHAR, LogicalType::VARCHAR, - LogicalType::VARCHAR}, + LogicalType::VARCHAR, LogicalType::VARCHAR}, estimated_cardinality), info(std::move(info)) { } diff --git a/src/duckdb/src/include/duckdb/execution/operator/persistent/physical_update.hpp b/src/duckdb/src/include/duckdb/execution/operator/persistent/physical_update.hpp index 78ab8b18a..f161b4730 100644 --- a/src/duckdb/src/include/duckdb/execution/operator/persistent/physical_update.hpp +++ b/src/duckdb/src/include/duckdb/execution/operator/persistent/physical_update.hpp @@ -44,6 +44,9 @@ class PhysicalUpdate : public PhysicalOperator { //! Set to true, if we are updating an index column. bool index_update; +public: + InsertionOrderPreservingMap ParamsToString() const override; + public: // Source interface unique_ptr GetGlobalSourceState(ClientContext &context) const override; diff --git a/src/duckdb/src/include/duckdb/execution/operator/scan/physical_expression_scan.hpp b/src/duckdb/src/include/duckdb/execution/operator/scan/physical_expression_scan.hpp index f890bc159..218b4e56f 100644 --- a/src/duckdb/src/include/duckdb/execution/operator/scan/physical_expression_scan.hpp +++ b/src/duckdb/src/include/duckdb/execution/operator/scan/physical_expression_scan.hpp @@ -41,11 +41,7 @@ class PhysicalExpressionScan : public PhysicalOperator { public: bool IsFoldable() const; void EvaluateExpression(ClientContext &context, idx_t expression_idx, optional_ptr child_chunk, - DataChunk &result, optional_ptr temp_chunk_ptr = nullptr) const; - -private: - void EvaluateExpressionInternal(ClientContext &context, idx_t expression_idx, optional_ptr child_chunk, - DataChunk &result, DataChunk &temp_chunk) const; + DataChunk &result, DataChunk &temp_chunk) const; }; } // namespace duckdb diff --git a/src/duckdb/src/include/duckdb/execution/perfect_hash_join_table.hpp b/src/duckdb/src/include/duckdb/execution/perfect_hash_join_table.hpp index 69eecac92..f7d54f698 100644 --- a/src/duckdb/src/include/duckdb/execution/perfect_hash_join_table.hpp +++ b/src/duckdb/src/include/duckdb/execution/perfect_hash_join_table.hpp @@ -82,7 +82,7 @@ class PerfectHashJoinTable { return {reinterpret_cast *>(match_entries.get()), EntryCount()}; } - static constexpr idx_t MAX_BYTES = 8 * 1024 * 1024; + static constexpr idx_t MAX_BYTES = 8ULL * 1024 * 1024; HugeAllocation entries; mutable HugeAllocation match_entries; const bool nulls_equal; diff --git a/src/duckdb/src/include/duckdb/execution/physical_plan_generator.hpp b/src/duckdb/src/include/duckdb/execution/physical_plan_generator.hpp index 2b91ebebc..47cb0394d 100644 --- a/src/duckdb/src/include/duckdb/execution/physical_plan_generator.hpp +++ b/src/duckdb/src/include/duckdb/execution/physical_plan_generator.hpp @@ -155,6 +155,7 @@ class PhysicalPlanGenerator { PhysicalOperator &CreatePlan(LogicalMergeInto &op); PhysicalOperator &CreatePlan(LogicalOrder &op); PhysicalOperator &CreatePlan(LogicalTopN &op); + PhysicalOperator &CreatePlan(LogicalTopKeyFilter &op); PhysicalOperator &CreatePlan(LogicalPositionalJoin &op); PhysicalOperator &CreatePlan(LogicalProjection &op); PhysicalOperator &CreatePlan(LogicalInsert &op); diff --git a/src/duckdb/src/include/duckdb/execution/radix_ht_adaptivity.hpp b/src/duckdb/src/include/duckdb/execution/radix_ht_adaptivity.hpp index bc9120215..c31e498c3 100644 --- a/src/duckdb/src/include/duckdb/execution/radix_ht_adaptivity.hpp +++ b/src/duckdb/src/include/duckdb/execution/radix_ht_adaptivity.hpp @@ -28,9 +28,9 @@ class RadixHTAdaptivity { void Reset(); //! Minimum cumulative input before lookups may first be skipped - static constexpr idx_t MIN_INPUT_ROWS_BEFORE_LOOKUP_SKIP = 1024 * 1024; + static constexpr idx_t MIN_INPUT_ROWS_BEFORE_LOOKUP_SKIP = 1024ULL * 1024; //! Minimum input processed while skipping before retrying lookups - static constexpr idx_t MIN_LOOKUP_RETRY_ROWS = 128 * 1024; + static constexpr idx_t MIN_LOOKUP_RETRY_ROWS = 128ULL * 1024; private: //! Grow a profitable table within the memory budget, resuming lookups on success. @@ -41,8 +41,8 @@ class RadixHTAdaptivity { void MaybeResumeLookups(GroupedAggregateHashTable &ht) const; private: - static constexpr idx_t LOOKUP_HISTORY_DECAY_THRESHOLD_ROWS = 128 * 1024; - static constexpr idx_t MAX_LOOKUP_RETRY_ROWS = 1024 * 1024; + static constexpr idx_t LOOKUP_HISTORY_DECAY_THRESHOLD_ROWS = 128ULL * 1024; + static constexpr idx_t MAX_LOOKUP_RETRY_ROWS = 1024ULL * 1024; static constexpr idx_t LOOKUP_RETRY_MATERIALIZED_ROWS_DIVISOR = 8; static constexpr double GROWTH_DUPLICATE_BYTES_FACTOR = 1.0; static constexpr double MINIMUM_LOOKUP_REDUCTION = 0.05; diff --git a/src/duckdb/src/include/duckdb/execution/reservoir_sample.hpp b/src/duckdb/src/include/duckdb/execution/reservoir_sample.hpp index 51ecccf75..38d839140 100644 --- a/src/duckdb/src/include/duckdb/execution/reservoir_sample.hpp +++ b/src/duckdb/src/include/duckdb/execution/reservoir_sample.hpp @@ -117,6 +117,9 @@ class ReservoirSampler { } private: + ReservoirSampler() = default; + friend SAMPLER; + SAMPLER &Sampler() { return static_cast(*this); } diff --git a/src/duckdb/src/include/duckdb/function/arg_properties.hpp b/src/duckdb/src/include/duckdb/function/arg_properties.hpp index 84dad8e6b..024384538 100644 --- a/src/duckdb/src/include/duckdb/function/arg_properties.hpp +++ b/src/duckdb/src/include/duckdb/function/arg_properties.hpp @@ -22,10 +22,18 @@ enum class Monotonicity : uint8_t { STRICTLY_DECREASING, }; +//! Exact rounding of an argument to an integer, preserving NaN and infinities. +enum class IntegerRounding : uint8_t { UNKNOWN = 0, FLOOR, CEIL, TRUNCATE }; + //! Per-argument metadata for a scalar function. struct ArgProperties { Monotonicity monotonicity = Monotonicity::UNKNOWN; + IntegerRounding integer_rounding = IntegerRounding::UNKNOWN; + ArgProperties &RoundsToInteger(IntegerRounding rounding) { + integer_rounding = rounding; + return *this; + } ArgProperties &StrictlyIncreasing() { monotonicity = Monotonicity::STRICTLY_INCREASING; return *this; diff --git a/src/duckdb/src/include/duckdb/function/cast/variant/variant_to_variant.hpp b/src/duckdb/src/include/duckdb/function/cast/variant/variant_to_variant.hpp index 35a4123e0..d143abe90 100644 --- a/src/duckdb/src/include/duckdb/function/cast/variant/variant_to_variant.hpp +++ b/src/duckdb/src/include/duckdb/function/cast/variant/variant_to_variant.hpp @@ -144,8 +144,8 @@ struct VariantToVariantSizeAnalyzer { return VisitArray(variant, row, nested_data, depth, state); } - static uint32_t VisitDefault(VariantLogicalType type_id, const_data_ptr_t, AnalyzeState &) { - throw InternalException("Unrecognized VariantLogicalType: %s", EnumUtil::ToString(type_id)); + static uint32_t VisitDefault(const LogicalType &type, const_data_ptr_t, AnalyzeState &) { + throw InternalException("Unrecognized VariantLogicalType: %s", type.ToString()); } }; @@ -257,8 +257,8 @@ struct VariantToVariantDataWriter { return VisitArray(variant, row, nested_data, depth, state); } - static void VisitDefault(VariantLogicalType type_id, const_data_ptr_t, WriteState &) { - throw InternalException("Unrecognized VariantLogicalType: %s", EnumUtil::ToString(type_id)); + static void VisitDefault(const LogicalType &type, const_data_ptr_t, WriteState &) { + throw InternalException("Unrecognized VariantLogicalType: %s", type.ToString()); } }; diff --git a/src/duckdb/src/include/duckdb/function/scalar/system_functions.hpp b/src/duckdb/src/include/duckdb/function/scalar/system_functions.hpp index 774b6d2a3..e3ceb85ef 100644 --- a/src/duckdb/src/include/duckdb/function/scalar/system_functions.hpp +++ b/src/duckdb/src/include/duckdb/function/scalar/system_functions.hpp @@ -85,6 +85,16 @@ struct CurrentQueryId { static ScalarFunction GetFunction(); }; +struct ExtensionRepositoryUrl { + static constexpr const char *Name = "extension_repository_url"; + static constexpr const char *Parameters = "host"; + static constexpr const char *Description = "Returns the extension repository url that the given host publishes in its well-known metadata file, i.e., where CREATE EXTENSION REPOSITORY would install and load extensions from. Reads the host's metadata file over https and nothing else: no repository is created and no key is trusted"; + static constexpr const char *Example = "extension_repository_url('duckdb.org')"; + static constexpr const char *Categories = ""; + + static ScalarFunction GetFunction(); +}; + struct ParseLogMessage { static constexpr const char *Name = "parse_duckdb_log_message"; static constexpr const char *Parameters = "type,message"; diff --git a/src/duckdb/src/include/duckdb/function/scalar/variant_path_function.hpp b/src/duckdb/src/include/duckdb/function/scalar/variant_path_function.hpp index 2b8d3c485..af8e1dc33 100644 --- a/src/duckdb/src/include/duckdb/function/scalar/variant_path_function.hpp +++ b/src/duckdb/src/include/duckdb/function/scalar/variant_path_function.hpp @@ -143,7 +143,7 @@ struct VariantPathFunction { continue; } - if (node.GetTypeId() != VariantLogicalType::OBJECT) { + if (node.GetTypeId() != LogicalTypeId::STRUCT) { return {}; } diff --git a/src/duckdb/src/include/duckdb/function/variant/variant_normalize.hpp b/src/duckdb/src/include/duckdb/function/variant/variant_normalize.hpp index 443c45174..f0018d50b 100644 --- a/src/duckdb/src/include/duckdb/function/variant/variant_normalize.hpp +++ b/src/duckdb/src/include/duckdb/function/variant/variant_normalize.hpp @@ -90,7 +90,7 @@ struct VariantNormalizer { idx_t depth, VariantNormalizerState &state); static void VisitObject(const UnifiedVariantVectorData &variant, idx_t row, const VariantNestedData &nested_data, idx_t depth, VariantNormalizerState &state); - static void VisitDefault(VariantLogicalType type_id, const_data_ptr_t, VariantNormalizerState &state); + static void VisitDefault(const LogicalType &type, const_data_ptr_t, VariantNormalizerState &state); public: static void Normalize(const Vector &input, Vector &output); diff --git a/src/duckdb/src/include/duckdb/function/variant/variant_shredding.hpp b/src/duckdb/src/include/duckdb/function/variant/variant_shredding.hpp index 6fce1e628..7021f3772 100644 --- a/src/duckdb/src/include/duckdb/function/variant/variant_shredding.hpp +++ b/src/duckdb/src/include/duckdb/function/variant/variant_shredding.hpp @@ -120,7 +120,7 @@ struct VariantShreddingState { void SetShredded(uint32_t row, uint32_t values_index, uint32_t result_idx); //! The field names of the STRUCT type - the keys point into 'type' const string_set_t &ObjectFields() const; - virtual const unordered_set &GetVariantTypes() = 0; + virtual const unordered_set &GetVariantTypes() = 0; public: //! The type the field is shredded on diff --git a/src/duckdb/src/include/duckdb/function/variant/variant_value_convert.hpp b/src/duckdb/src/include/duckdb/function/variant/variant_value_convert.hpp index f9bab6099..cd441c1ef 100644 --- a/src/duckdb/src/include/duckdb/function/variant/variant_value_convert.hpp +++ b/src/duckdb/src/include/duckdb/function/variant/variant_value_convert.hpp @@ -136,8 +136,8 @@ struct ValueConverter { return Value::STRUCT(std::move(object_children)); } - static Value VisitDefault(VariantLogicalType type_id, const_data_ptr_t) { - throw InternalException("VariantLogicalType(%s) not handled", EnumUtil::ToString(type_id)); + static Value VisitDefault(const LogicalType &type, const_data_ptr_t) { + throw InternalException("VariantLogicalType(%s) not handled", type.ToString()); } }; diff --git a/src/duckdb/src/include/duckdb/function/window_function.hpp b/src/duckdb/src/include/duckdb/function/window_function.hpp index 98bcdbc81..91af726ac 100644 --- a/src/duckdb/src/include/duckdb/function/window_function.hpp +++ b/src/duckdb/src/include/duckdb/function/window_function.hpp @@ -190,6 +190,8 @@ class WindowFunctionProperties : public FunctionProperties { bool can_ignore_nulls = true; //! Does the function rank rows within the partition? bool is_ranking = false; + //! Does the function read the ORDER BY values, so that a redundant key must be kept? + bool requires_ordering = false; }; class BaseWindowFunction { @@ -228,6 +230,7 @@ class BaseWindowFunction { bool CanExclude() const { return properties.can_exclude; } bool CanIgnoreNulls() const { return properties.can_ignore_nulls; } bool IsRanking() const { return properties.is_ranking; } + bool RequiresOrdering() const { return properties.requires_ordering; } void SetCanDistinct(bool value) { properties.can_distinct = value; } void SetCanFilter(bool value) { properties.can_filter = value; } @@ -235,6 +238,7 @@ class BaseWindowFunction { void SetCanExclude(bool value) { properties.can_exclude = value; } void SetCanIgnoreNulls(bool value) { properties.can_ignore_nulls = value; } void SetIsRanking(bool value) { properties.is_ranking = value; } + void SetRequiresOrdering(bool value) { properties.requires_ordering = value; } public: // Callbacks diff --git a/src/duckdb/src/include/duckdb/main/capi_v2/capi_v2_internal.hpp b/src/duckdb/src/include/duckdb/main/capi_v2/capi_v2_internal.hpp index a85411631..3a5dd217e 100644 --- a/src/duckdb/src/include/duckdb/main/capi_v2/capi_v2_internal.hpp +++ b/src/duckdb/src/include/duckdb/main/capi_v2/capi_v2_internal.hpp @@ -304,6 +304,11 @@ class CV2InstanceFactory final : public CV2Factory { //! NotImplementedException when there is none. Defined in capi_v2_logical_type.cpp. auto ResolveCommonType(CV2Factory &factory, const vector &types) -> LogicalType; +//! Throws when the type holds a DECIMAL wider than the factory creates: the max_decimal_width setting of the factory's +//! client, or the default of the setting for a factory without one. The cost of a wide decimal grows with its width, +//! so a factory bounds the types and values it creates like a session bounds the ones it binds +void CheckDecimalWidthV2(CV2Factory &factory, const LogicalType &type); + //! The SQL ATTACH `(KEY value)` options of one attach, as the text values a quoted literal produces. Bound to the //! instance handle it was created from, which is what future per-instance resources (an allocator, say) would be //! taken from. 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 eed383294..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 @@ -218,7 +218,7 @@ typedef struct { (duckdb_v2_factory_handle factory, int32_t in_value, duckdb_v2_value_handle *out_value, duckdb_v2_error_info_handle *err); DUCKDB_V2_ERROR(*duckdb_v2_value_create_decimal) - (duckdb_v2_factory_handle factory, const duckdb_v2_hugeint_t *in_value, uint8_t width, uint8_t scale, + (duckdb_v2_factory_handle factory, const duckdb_v2_hugeint_t *in_value, uint32_t width, uint32_t scale, duckdb_v2_value_handle *out_value, duckdb_v2_error_info_handle *err); DUCKDB_V2_ERROR(*duckdb_v2_value_create_double) (duckdb_v2_factory_handle factory, double in_value, duckdb_v2_value_handle *out_value, @@ -323,7 +323,7 @@ typedef struct { DUCKDB_V2_ERROR(*duckdb_v2_value_get_date) (duckdb_v2_value_handle value, int32_t *out, duckdb_v2_error_info_handle *err); DUCKDB_V2_ERROR(*duckdb_v2_value_get_decimal) - (duckdb_v2_value_handle value, duckdb_v2_hugeint_t *out, uint8_t *out_width, uint8_t *out_scale, + (duckdb_v2_value_handle value, duckdb_v2_hugeint_t *out, uint32_t *out_width, uint32_t *out_scale, duckdb_v2_error_info_handle *err); DUCKDB_V2_ERROR(*duckdb_v2_value_get_double) (duckdb_v2_value_handle value, double *out, duckdb_v2_error_info_handle *err); @@ -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/main/client_data.hpp b/src/duckdb/src/include/duckdb/main/client_data.hpp index ce74627eb..3ce095f77 100644 --- a/src/duckdb/src/include/duckdb/main/client_data.hpp +++ b/src/duckdb/src/include/duckdb/main/client_data.hpp @@ -10,6 +10,7 @@ #include "duckdb/common/case_insensitive_map.hpp" #include "duckdb/common/common.hpp" +#include "duckdb/common/once_flag.hpp" namespace duckdb { @@ -17,6 +18,7 @@ class AttachedDatabase; class BufferedFileWriter; class ClientContext; class CatalogSearchPath; +class ExpressionRewriter; class FileOpener; class FileSystem; class QueryProfiler; @@ -44,6 +46,10 @@ struct ClientData { //! calls only affect new clients. Empty when there was none. Identifier default_database; + //! Owns the default expression rewrite rules, which are stateless and shared by every optimizer run of this client. + unique_ptr default_expression_rewriter; + OnceFlag default_expression_rewriter_once; + //! The writer used to log queries, if logging is enabled. //! DEPRECATED: Now, queries are written to the generic log. unique_ptr log_query_writer; diff --git a/src/duckdb/src/include/duckdb/main/config.hpp b/src/duckdb/src/include/duckdb/main/config.hpp index 54ffc68a2..4ad567636 100644 --- a/src/duckdb/src/include/duckdb/main/config.hpp +++ b/src/duckdb/src/include/duckdb/main/config.hpp @@ -22,6 +22,7 @@ #include "duckdb/common/enums/order_type.hpp" #include "duckdb/common/enums/set_scope.hpp" #include "duckdb/common/file_system.hpp" +#include "duckdb/common/virtual_file_system.hpp" #include "duckdb/common/set.hpp" #include "duckdb/common/types/value.hpp" #include "duckdb/common/vector.hpp" @@ -197,9 +198,9 @@ struct DBConfig { //! Replacement table scans are automatically attempted when a table name cannot be found in the schema ReplacementScanList replacement_scans; - //! The FileSystem to use, can be overwritten to allow for injecting custom file systems for testing purposes (e.g. - //! RamFS or something similar). Never null: defaults to a VirtualFileSystem. - unique_ptr file_system; + //! The root of the file systems. Never null. Custom file systems are registered on it as sub-systems, or passed as + //! its default file system. + unique_ptr file_system; //! Secret manager unique_ptr secret_manager; //! The allocator used by the system diff --git a/src/duckdb/src/include/duckdb/main/database_file_opener.hpp b/src/duckdb/src/include/duckdb/main/database_file_opener.hpp index 99a0fb1ef..04417b1cd 100644 --- a/src/duckdb/src/include/duckdb/main/database_file_opener.hpp +++ b/src/duckdb/src/include/duckdb/main/database_file_opener.hpp @@ -58,15 +58,14 @@ class DatabaseFileSystem : public OpenerFileSystem { explicit DatabaseFileSystem(DatabaseInstance &db_p) : db(db_p), database_opener(db_p) { } - FileSystem &GetFileSystem() const override { - auto &config = DBConfig::GetConfig(db); - return *config.file_system; +private: + VirtualFileSystem &GetFileSystem() const override { + return VirtualFileSystem::Get(db); } optional_ptr GetOpener() const override { return &database_opener; } -private: DatabaseInstance &db; mutable DatabaseFileOpener database_opener; }; @@ -75,14 +74,17 @@ class LocalDatabaseFileSystem : public OpenerFileSystem { public: explicit LocalDatabaseFileSystem(DatabaseInstance &db_p); - FileSystem &GetFileSystem() const override; +private: + VirtualFileSystem &GetFileSystem() const override; optional_ptr GetOpener() const override { return &database_opener; } + //! Every path is local: the default file system if it is local, otherwise the owned local file system + optional_ptr GetFixedFileSystem() const override; -private: - DatabaseInstance &db; - FileSystem &local_fs; + VirtualFileSystem &file_system; + //! Only set if the default file system is not local + unique_ptr owned_file_system; mutable DatabaseFileOpener database_opener; }; diff --git a/src/duckdb/src/include/duckdb/main/extension_helper.hpp b/src/duckdb/src/include/duckdb/main/extension_helper.hpp index 0e220a9c2..926358695 100644 --- a/src/duckdb/src/include/duckdb/main/extension_helper.hpp +++ b/src/duckdb/src/include/duckdb/main/extension_helper.hpp @@ -69,6 +69,8 @@ enum class ExtensionUpdateResultTag : uint8_t { REPOSITORY_NOT_TRUSTED = 7, // The file of the user-provided repository the extension was installed from could not be read REPOSITORY_UNREADABLE = 8, + // Downloading or installing the extension from its repository failed, see the error + UPDATE_FAILED = 9, // The extension was re-downloaded from the repository, but due to a lack of version information // its impossible to tell if the extension is actually updated @@ -86,6 +88,8 @@ struct ExtensionUpdateResult { string extension_version; string prev_version; string installed_version; + //! The error message when the tag is UPDATE_FAILED + string error; }; struct ExtensionInstallOptions { @@ -104,6 +108,19 @@ struct ExtensionInstallOptions { string extension_directory; }; +//! An installed extension that needs a download to be updated, prepared by PrepareExtensionUpdates +struct PendingExtensionUpdate { + //! Index of the entry in the results that this update fills in + idx_t result_index; + string extension_name; + //! The repository the extension is updated from + ExtensionRepository repository; + //! Whether the repository is the one the extension was installed from, so its ETag can be reused + bool use_etags; + //! The extension directory the extension is installed in + string extension_directory; +}; + struct InstalledExtensionDirectory { string path; //! The user-provided repository of a per-repository folder, empty for the flat folder @@ -152,6 +169,15 @@ class ExtensionHelper { static vector UpdateExtensions(ClientContext &context); //! Update a specific extension static ExtensionUpdateResult UpdateExtension(ClientContext &context, const string &extension_name); + //! Check all installed extensions: extensions that cannot be updated get a result, the others a pending update + static void PrepareExtensionUpdates(ClientContext &context, vector &results, + vector &pending); + //! Check a specific extension, as PrepareExtensionUpdates does; throws when it is not installed + static void PrepareExtensionUpdate(ClientContext &context, const string &extension_name, + vector &results, vector &pending); + //! Download and install a pending update, filling in its result; failures are reported as UPDATE_FAILED + static void ExecuteExtensionUpdate(ClientContext &context, const PendingExtensionUpdate &pending, + ExtensionUpdateResult &result); //! Get the extension directory base on the current config static string ExtensionDirectory(ClientContext &context); diff --git a/src/duckdb/src/include/duckdb/main/extension_repository_manager.hpp b/src/duckdb/src/include/duckdb/main/extension_repository_manager.hpp index 26abe8eb6..c1cf51a38 100644 --- a/src/duckdb/src/include/duckdb/main/extension_repository_manager.hpp +++ b/src/duckdb/src/include/duckdb/main/extension_repository_manager.hpp @@ -30,6 +30,10 @@ struct ExtensionRepositoryResolution { string url; }; +//! Who asked a host where its repository is, which decides how a failure is phrased: the statement can suggest +//! naming the location with WITH PREFIX instead, a plain lookup has nothing to suggest +enum class ExtensionRepositoryHostCaller : uint8_t { CREATE_STATEMENT, LOOKUP }; + class ExtensionRepositoryManager { public: //! The file extension used for the stored repository definitions @@ -103,14 +107,16 @@ class ExtensionRepositoryManager { //! Convert a compact public key back into the PEM representation used for signature verification static string ToPEMPublicKey(const string &compact_key); -private: //! Resolve `CREATE EXTENSION REPOSITORY ` (no prefix): the name is the publisher's host, and the metadata //! file it serves (https:///METADATA_FILE) names the repository url. Only the url is taken from the host; //! the keys come from the prefix, as with WITH PREFIX. Called by CreateRepository after the access and conflict - //! checks + //! checks, and by the extension_repository_url function, which answers where a host would send DuckDB without + //! creating anything. Nothing is trusted on the strength of this call alone: it only reads a public file static ExtensionRepositoryResolution - ResolveRepositoryFromHost(DatabaseInstance &db, optional_ptr context, const string &name); + ResolveRepositoryFromHost(DatabaseInstance &db, optional_ptr context, const string &name, + ExtensionRepositoryHostCaller caller = ExtensionRepositoryHostCaller::CREATE_STATEMENT); +private: //! Throws unless adding a repository is currently allowed (opt-in and configuration lock) static void CheckCanCreate(DatabaseInstance &db, const string &name, bool from_host); //! Throws if the configuration is locked, freezing the trust store diff --git a/src/duckdb/src/include/duckdb/main/http/http_util.hpp b/src/duckdb/src/include/duckdb/main/http/http_util.hpp index 04d350d90..ca6ef720b 100644 --- a/src/duckdb/src/include/duckdb/main/http/http_util.hpp +++ b/src/duckdb/src/include/duckdb/main/http/http_util.hpp @@ -135,7 +135,7 @@ struct HTTPClientInitializationOptions { struct HTTPHeaders { using header_values_t = vector; - using header_map_t = case_insensitive_map_t; + using header_map_t = multimap; public: HTTPHeaders() = default; @@ -143,14 +143,21 @@ struct HTTPHeaders { // Out-of-line so the symbol is emitted/exported for loadable (WASM side-module) extensions. DUCKDB_API ~HTTPHeaders(); - void Insert(string key, string value); + //! Insert only if the name is absent. + void InsertIfAbsent(string key, string value); + [[deprecated("Use InsertIfAbsent instead")]] void Insert(string key, string value); //! Append another field line without combining its value. void Append(string key, string value); + //! Replace all field lines with this name. + void Set(string key, string value); + //! Remove all field lines with this name. + void RemoveAll(const string &key); bool HasHeader(const string &key) const; //! Return the first field value. string GetHeaderValue(const string &key) const; header_values_t GetHeaderValues(const string &key) const; + //! Iteration visits every field line, in insertion order for each name. header_map_t::iterator begin() { // NOLINT: match stl API return headers.begin(); } @@ -169,14 +176,9 @@ struct HTTPHeaders { header_map_t::const_iterator cend() const { // NOLINT: match stl API return headers.end(); } - header_map_t::mapped_type &operator[](const header_map_t::key_type &key) { - return headers[key]; - } private: header_map_t headers; - //! HTTP responses can contain multiple field lines with the same name (i.e., Cache-Control). - case_insensitive_map_t repeated_headers; }; struct HTTPResponse { @@ -250,7 +252,7 @@ struct BaseRequest { static HTTPHeaders MergeHeaders(const HTTPHeaders &headers, HTTPParams ¶ms) { HTTPHeaders result = headers; for (const auto &header : params.extra_headers) { - result.Insert(header.first, header.second); + result.InsertIfAbsent(header.first, header.second); } return result; } diff --git a/src/duckdb/src/include/duckdb/main/settings.hpp b/src/duckdb/src/include/duckdb/main/settings.hpp index e03077c2c..cf61992d1 100644 --- a/src/duckdb/src/include/duckdb/main/settings.hpp +++ b/src/duckdb/src/include/duckdb/main/settings.hpp @@ -62,7 +62,7 @@ struct Settings { } //! The default of a setting with a constant default template - static typename OP::RETURN_TYPE GetDefault(const SOURCE &, long) { + static typename OP::RETURN_TYPE GetDefault(const SOURCE &, int64_t) { return FromDefault(OP::DefaultValue); } diff --git a/src/duckdb/src/include/duckdb/optimizer/expression_rewriter.hpp b/src/duckdb/src/include/duckdb/optimizer/expression_rewriter.hpp index c232538cf..caf9813ae 100644 --- a/src/duckdb/src/include/duckdb/optimizer/expression_rewriter.hpp +++ b/src/duckdb/src/include/duckdb/optimizer/expression_rewriter.hpp @@ -37,17 +37,18 @@ class ExpressionRewriter : public LogicalOperatorVisitor { Value value); private: - //! Returns the rewrite rules, constructing them on first access + //! Returns the custom rules if any were added, otherwise the default rules shared by the client context const vector> &GetRules(); + //! Creates the default rules, which only use the rewriter to reach its client context + static vector> CreateDefaultRules(ExpressionRewriter &rewriter); //! Apply a set of rules to a specific expression - static unique_ptr ApplyRules(LogicalOperator &op, const vector> &rules, + static unique_ptr ApplyRules(LogicalOperator &op, const vector> &rules, unique_ptr expr, bool &changes_made, bool is_root = false); //! The set of rules as known by the Expression Rewriter vector> rules; optional_ptr op; - vector> to_apply_rules; }; } // namespace duckdb diff --git a/src/duckdb/src/include/duckdb/optimizer/group_by_top_key.hpp b/src/duckdb/src/include/duckdb/optimizer/group_by_top_key.hpp new file mode 100644 index 000000000..13b9b5322 --- /dev/null +++ b/src/duckdb/src/include/duckdb/optimizer/group_by_top_key.hpp @@ -0,0 +1,77 @@ +//===----------------------------------------------------------------------===// +// DuckDB +// +// duckdb/optimizer/group_by_top_key.hpp +// +// +//===----------------------------------------------------------------------===// + +#pragma once + +#include "duckdb/planner/bound_query_node.hpp" +#include "duckdb/planner/logical_operator.hpp" + +namespace duckdb { + +class LogicalAggregate; +class Optimizer; + +//! Bounds the input of a grouped aggregate whose Top-N orders by a prefix of the group keys: +//! +//! TOP_N(n, ORDER BY k1 [, k2 ..] [, agg ..]) TOP_N(..) +//! PROJECTION* PROJECTION* +//! AGGREGATE(k1 .. km; aggs) ==> AGGREGATE(k1 .. km; aggs) +//! TOP_KEY_FILTER(n, keys: k1 [, k2 ..]) +//! (+ a dynamic filter on k1 in the scans) +//! +//! The filter keeps the n smallest distinct key tuples seen so far and removes rows that sort after the largest of +//! them. That bound is never smaller than the n-th smallest distinct key tuple of the whole input, so every group that +//! the Top-N can return still receives all of its rows and its aggregates are exact. The filter is conservative: it +//! may pass rows of other groups (see LogicalTopKeyFilter), so the aggregate can still produce more than n groups, +//! some of them incomplete, and the Top-N stays in the plan to pick the result. A prefix of the ORDER BY suffices +//! because the order is lexicographic. +//! +//! The filter computes a key for every input row, the Top-N for one row of a group. A key therefore has to be a group +//! key (through projections that preserve the order), or an expression over group keys that has the same value for all +//! rows of a group: one that cannot throw and only reads group keys whose equal values cannot be told apart (not +//! FLOAT / DOUBLE, where -0.0 = 0.0). Key types whose sort keys do not agree with their comparison are declined. +//! +//! A LIMIT without an ORDER BY over a grouped aggregate may return any n groups. It is turned into a Top-N on a group +//! key first, so that the aggregate only has to aggregate the n groups that are returned: +//! +//! LIMIT(n) PROJECTION* +//! PROJECTION* ==> TOP_N(n, ORDER BY k) +//! AGGREGATE(k1 .. km; aggs) AGGREGATE(k1 .. km; aggs) +//! +//! The projections must not be volatile or able to throw: above the Top-N they only see the rows that are returned. +class GroupByTopKey { +public: + explicit GroupByTopKey(Optimizer &optimizer); + + unique_ptr Optimize(unique_ptr op); + +private: + //! A matched TOP_N -> PROJECTION* -> AGGREGATE chain + struct TopKeyMatch { + //! LIMIT + OFFSET: the number of distinct key tuples that pass + idx_t limit = 0; + //! The number of projections between the Top-N and the aggregate + idx_t depth = 0; + //! The keys of the ORDER BY prefix as expressions over the input of the aggregate + vector prefix; + }; + +private: + //! LIMIT over a grouped aggregate -> Top-N over the aggregate + unique_ptr LimitToTopN(unique_ptr op); + bool TryMatch(LogicalOperator &op, TopKeyMatch &match); + void Rewrite(LogicalAggregate &aggregate, TopKeyMatch &match); + //! Computes the keys that are not columns of the input in a projection below the aggregate + unique_ptr MaterializeKeys(LogicalAggregate &aggregate, unique_ptr input, + vector &keys); + +private: + Optimizer &optimizer; +}; + +} // namespace duckdb diff --git a/src/duckdb/src/include/duckdb/optimizer/join_order/cardinality_value.hpp b/src/duckdb/src/include/duckdb/optimizer/join_order/cardinality_value.hpp index 917af4f00..6f1ee25fe 100644 --- a/src/duckdb/src/include/duckdb/optimizer/join_order/cardinality_value.hpp +++ b/src/duckdb/src/include/duckdb/optimizer/join_order/cardinality_value.hpp @@ -24,6 +24,14 @@ class CardinalityValue { return numerator.significand == 0; } + double GetLog() const { + if (IsZero()) { + return -std::numeric_limits::infinity(); + } + return std::log(numerator.significand) - std::log(denominator) + + static_cast(numerator.exponent) * std::log(2.0); + } + double GetDouble() const { if (IsZero()) { return 0; diff --git a/src/duckdb/src/include/duckdb/optimizer/join_order/cost_model.hpp b/src/duckdb/src/include/duckdb/optimizer/join_order/cost_model.hpp index e9cd817a1..f4bfebbd9 100644 --- a/src/duckdb/src/include/duckdb/optimizer/join_order/cost_model.hpp +++ b/src/duckdb/src/include/duckdb/optimizer/join_order/cost_model.hpp @@ -34,6 +34,8 @@ class CostModel { //! Compute work for the selected operator and its estimated output. double ComputeCost(const DPJoinNode &left, const DPJoinNode &right, optional_ptr join_operator, double output_rows); + //! Minimum work for either orientation, excluding nonnegative operator-specific work. + double ComputeCostLowerBound(const DPJoinNode &left, const DPJoinNode &right, double output_rows); CardinalityEstimator &GetCardinalityEstimator(); void InitializeRecursiveMemory(ClientContext &context, RelationManager &relations); void UpdateBuildMemory(DPJoinNode &result, const DPJoinNode &left, const DPJoinNode &right); diff --git a/src/duckdb/src/include/duckdb/optimizer/join_order/greedy_join_enumerator.hpp b/src/duckdb/src/include/duckdb/optimizer/join_order/greedy_join_enumerator.hpp index 08632728b..da426c6e1 100644 --- a/src/duckdb/src/include/duckdb/optimizer/join_order/greedy_join_enumerator.hpp +++ b/src/duckdb/src/include/duckdb/optimizer/join_order/greedy_join_enumerator.hpp @@ -21,8 +21,29 @@ class GreedyJoinEnumerator { bool Solve(JoinOrderPlanMap &plans); private: + struct Candidate { + idx_t left; + idx_t right; + JoinPlanCost cost; + }; + + idx_t AddGroup(JoinRelationSet &set); + vector GetConnectedGroups(idx_t group) const; + optional_ptr EmitOrientation(JoinOrderPlanMap &plans, idx_t left, idx_t right); + void EmitCandidate(JoinOrderPlanMap &plans, idx_t left, idx_t right); + void InitializeCandidates(JoinOrderPlanMap &plans); + bool TryCrossProduct(JoinOrderPlanMap &plans, idx_t &left, idx_t &right); + void MergeGroups(JoinOrderPlanMap &plans, idx_t left, idx_t right); + QueryGraphManager &query_graph_manager; JoinOrderCandidateEvaluator &evaluator; + + //! Group indexes are allocated in insertion order, preserving the greedy candidate tie order. + vector> groups; + vector active_groups; + //! The current group containing each original relation, including every member of a hyperedge endpoint. + vector group_for_relation; + vector candidates; }; } // namespace duckdb diff --git a/src/duckdb/src/include/duckdb/optimizer/join_order/join_order_candidate.hpp b/src/duckdb/src/include/duckdb/optimizer/join_order/join_order_candidate.hpp index 7b4986411..5134eaf74 100644 --- a/src/duckdb/src/include/duckdb/optimizer/join_order/join_order_candidate.hpp +++ b/src/duckdb/src/include/duckdb/optimizer/join_order/join_order_candidate.hpp @@ -23,19 +23,29 @@ class JoinOrderCandidateEvaluator { public: JoinOrderCandidateEvaluator(QueryGraphManager &graph, CostModel &cost_model, const QueryGraphEdges &edges); - void InitLeafPlans(JoinOrderPlanMap &plans); + bool PreferPlan(const DPJoinNode &candidate, const JoinOrderPlanMap &candidate_plans, const DPJoinNode &incumbent, + const JoinOrderPlanMap &incumbent_plans) const; + //! Conservative bound for either orientation; inputs and incumbent must be fully costed. + bool CanImprovePair(const JoinOrderPlanMap &plans, const DPJoinNode &left, const DPJoinNode &right, + const DPJoinNode &incumbent) const; + + void InitLeafPlans(JoinOrderPlanMap &plans, const vector &relation_stats); void InitInputPlan(JoinOrderPlanMap &plans); JoinPlanCost GetPlanCost(const DPJoinNode &node) const; - //! Connection vectors are borrowed from the cache and invalidated when either operation below changes the graph. + //! Borrowed vectors are invalidated by graph changes or ResetConnectionCache. const vector> &GetConnections(JoinRelationSet &left, JoinRelationSet &right); //! Create an edge, invalidate cached connections, and return fresh connections for this pair. const vector> &CreateCrossProduct(JoinRelationSet &left, JoinRelationSet &right); //! Invalidate cached connections if required cross-product edges are activated. bool ActivateRequiredCrossProducts(); + //! Release the previous search phase's connections after all borrowed vectors have expired. + void ResetConnectionCache(); //! Return the preferred plan for the union, or nullptr when the partition is invalid. optional_ptr EmitPair(JoinOrderPlanMap &plans, JoinRelationSet &left, JoinRelationSet &right, const vector> &connections); + optional_ptr EmitPair(JoinOrderPlanMap &plans, JoinRelationSet &set, JoinRelationSet &left, + JoinRelationSet &right, const vector> &connections); private: unique_ptr CreateJoinTree(JoinRelationSet &set, const vector> &connections, diff --git a/src/duckdb/src/include/duckdb/optimizer/join_order/join_order_linearizer.hpp b/src/duckdb/src/include/duckdb/optimizer/join_order/join_order_linearizer.hpp new file mode 100644 index 000000000..5842426dd --- /dev/null +++ b/src/duckdb/src/include/duckdb/optimizer/join_order/join_order_linearizer.hpp @@ -0,0 +1,50 @@ +//===----------------------------------------------------------------------===// +// DuckDB +// +// duckdb/optimizer/join_order/join_order_linearizer.hpp +// +//===----------------------------------------------------------------------===// + +#pragma once + +#include "duckdb/optimizer/join_order/join_order_rank.hpp" + +namespace duckdb { + +class CardinalityEstimator; +class QueryGraphManager; + +//! Minimum-selectivity spanning tree followed by rooted IK/KBZ chain normalization. +class JoinOrderLinearizer { +public: + JoinOrderLinearizer(QueryGraphManager &graph, CardinalityEstimator &estimator); + bool BuildTree(); + RankedJoinOrder GetOrder(RelationIndex root); + //! Compare every root using the tree proxy before choosing one order for interval DP. + vector GetBestOrder(); + +private: + struct Block { + Block(RelationIndex relation, double multiplier); + + vector relations; + JoinOrderRank rank; + }; + + struct Edge { + idx_t left; + idx_t right; + double log_selectivity; + }; + +private: + void Normalize(vector &chain); + +private: + QueryGraphManager &graph; + CardinalityEstimator &estimator; + vector cardinalities; + vector tree; +}; + +} // namespace duckdb diff --git a/src/duckdb/src/include/duckdb/optimizer/join_order/join_order_operator.hpp b/src/duckdb/src/include/duckdb/optimizer/join_order/join_order_operator.hpp index ee85b054f..32d9746bc 100644 --- a/src/duckdb/src/include/duckdb/optimizer/join_order/join_order_operator.hpp +++ b/src/duckdb/src/include/duckdb/optimizer/join_order/join_order_operator.hpp @@ -17,7 +17,7 @@ namespace duckdb { -enum class JoinOrderOperatorType : uint8_t { INNER, LEFT, SEMI, ANTI, CROSS_PRODUCT }; +enum class JoinOrderOperatorType : uint8_t { INNER, LEFT, SEMI, ANTI, MARK, CROSS_PRODUCT }; struct JoinOrderConflictRule { JoinOrderConflictRule(JoinRelationSet &trigger_p, JoinRelationSet &requirement_p) @@ -58,6 +58,8 @@ struct JoinOrderOperator { vector> right_operators; //! Complete semantic conditions owned by this operator occurrence. vector conditions; + TableIndex mark_index; + vector mark_types; //! Predicate copies used only for cardinality estimation and query-graph connectivity. vector costing_predicate_indices; //! LEFT ON residuals not covered by a costing predicate or an equivalent equality key. diff --git a/src/duckdb/src/include/duckdb/optimizer/join_order/join_order_plan.hpp b/src/duckdb/src/include/duckdb/optimizer/join_order/join_order_plan.hpp new file mode 100644 index 000000000..c34bb34f9 --- /dev/null +++ b/src/duckdb/src/include/duckdb/optimizer/join_order/join_order_plan.hpp @@ -0,0 +1,34 @@ +//===----------------------------------------------------------------------===// +// DuckDB +// +// duckdb/optimizer/join_order/join_order_plan.hpp +// +//===----------------------------------------------------------------------===// + +#pragma once + +#include "duckdb/optimizer/join_order/join_order_candidate.hpp" + +namespace duckdb { + +JoinOrderPlanMap CopyJoinOrderLeafPlans(const JoinOrderPlanMap &source); + +//! A complete closure for one explicit root, re-costed after capturing all its children. +class CapturedJoinOrderPlan { +public: + static unique_ptr Capture(const JoinOrderPlanMap &source, JoinRelationSet &root, + CostModel &cost_model); + JoinRelationSet &GetRoot() const; + const DPJoinNode &GetRootNode() const; + const JoinOrderPlanMap &GetPlans() const; + vector GetLeafOrder() const; + JoinOrderPlanMap TakePlans(); + +private: + CapturedJoinOrderPlan(JoinRelationSet &root, JoinOrderPlanMap plans); + + JoinRelationSet &root; + JoinOrderPlanMap plans; +}; + +} // namespace duckdb diff --git a/src/duckdb/src/include/duckdb/optimizer/join_order/join_order_precedence.hpp b/src/duckdb/src/include/duckdb/optimizer/join_order/join_order_precedence.hpp new file mode 100644 index 000000000..06dda0fbc --- /dev/null +++ b/src/duckdb/src/include/duckdb/optimizer/join_order/join_order_precedence.hpp @@ -0,0 +1,103 @@ +//===----------------------------------------------------------------------===// +// DuckDB +// +// duckdb/optimizer/join_order/join_order_precedence.hpp +// +//===----------------------------------------------------------------------===// + +#pragma once + +#include "duckdb/optimizer/join_order/join_order_plan.hpp" +#include "duckdb/optimizer/join_order/join_order_rank.hpp" + +namespace duckdb { + +//! Generalized ranking over a witnessed scaffold; candidate legality uses the complete query graph. +class JoinOrderPrecedence { +public: + JoinOrderPrecedence(QueryGraphManager &graph, CardinalityEstimator &estimator, + JoinOrderCandidateEvaluator &evaluator, const CapturedJoinOrderPlan &witness); + //! Build the scaffold and choose one rooted order with a legal prescribed construction. + //! Returns an empty order when the scaffold is not separable or no rooted construction succeeds. + vector GetBestOrder(); + +private: + using Mask = vector; + + struct Edge { + reference left; + reference right; + double log_selectivity; + }; + + struct Atom { + Atom(vector relations, double multiplier, double preparation, + idx_t group = DConstants::INVALID_INDEX); + + vector relations; + JoinOrderRank rank; + double log_preparation; + idx_t group; + }; + + struct Block { + Block(Atom atom, vector prerequisites); + + vector atoms; + JoinOrderRank rank; + vector prerequisites; + }; + + struct Node { + explicit Node(Block block); + + Block block; + vector children; + }; + + struct Group { + vector relations; + vector atoms; + double log_cardinality = 0; + double log_preparation = 0; + }; + + struct CachedGroup { + Mask component; + Mask group; + Group result; + }; + +private: + bool Build(); + RankedJoinOrder GetOrder(RelationIndex root); + static bool EndpointLess(const JoinRelationSet &left, const JoinRelationSet &right, + const JoinRelationSet &other_left, const JoinRelationSet &other_right); + static bool Contains(const Mask &mask, const JoinRelationSet &set); + static idx_t Count(const Mask &mask); + static idx_t FindRoot(vector &parents, idx_t node); + void Components(const Mask &component, idx_t omitted, vector &labels); + bool CheckComponent(const Mask &component); + static void Mark(const Block &block, Mask &mask); + static double TotalWork(const vector &chain); + idx_t SolveGroup(const JoinRelationSet &group, const Mask &component); + Group BuildGroup(vector &chain, const Mask &group_mask); + idx_t SolveForwardGroup(idx_t edge_idx, const JoinRelationSet &head, const Mask &component, const Mask &marked); + bool Visit(idx_t node_idx, const Mask &component, Mask &marked, Mask path, vector &nodes); + void Normalize(vector &chain); + vector Solve(RelationIndex root, const Mask &component); + vector MergeChildren(Node &node, vector> &chains); + optional_ptr Materialize(const vector &atoms, JoinOrderPlanMap &plans); + +private: + QueryGraphManager &graph; + CardinalityEstimator &estimator; + JoinOrderCandidateEvaluator &evaluator; + const CapturedJoinOrderPlan &witness; + vector cardinalities; + vector edges; + vector checked_components; + vector groups; +}; + +} // namespace duckdb diff --git a/src/duckdb/src/include/duckdb/optimizer/join_order/join_order_rank.hpp b/src/duckdb/src/include/duckdb/optimizer/join_order/join_order_rank.hpp new file mode 100644 index 000000000..6962b1265 --- /dev/null +++ b/src/duckdb/src/include/duckdb/optimizer/join_order/join_order_rank.hpp @@ -0,0 +1,36 @@ +//===----------------------------------------------------------------------===// +// DuckDB +// +// duckdb/optimizer/join_order/join_order_rank.hpp +// +//===----------------------------------------------------------------------===// + +#pragma once + +#include "duckdb/optimizer/join_order/relation_index.hpp" +#include "duckdb/common/vector.hpp" + +namespace duckdb { + +//! ASI ranking proxy (q, w), stored logarithmically. This is not the plan cost comparator. +struct JoinOrderRank { + explicit JoinOrderRank(double log_multiplier); + void Append(const JoinOrderRank &other); + void AddIndependentWork(double log_work); + bool operator<(const JoinOrderRank &other) const; + + double log_multiplier; + double log_work; + +private: + static double AddLogValues(double left, double right); + int32_t Sign() const; + double LogMagnitude() const; +}; + +struct RankedJoinOrder { + vector relations; + double log_cost; +}; + +} // namespace duckdb diff --git a/src/duckdb/src/include/duckdb/optimizer/join_order/join_order_source_stats.hpp b/src/duckdb/src/include/duckdb/optimizer/join_order/join_order_source_stats.hpp index be7602282..3163afd0c 100644 --- a/src/duckdb/src/include/duckdb/optimizer/join_order/join_order_source_stats.hpp +++ b/src/duckdb/src/include/duckdb/optimizer/join_order/join_order_source_stats.hpp @@ -25,7 +25,7 @@ struct JoinColumnSource { }; struct JoinColumnSources { - explicit JoinColumnSources(JoinColumnSource direct) : direct(std::move(direct)) { + explicit JoinColumnSources(JoinColumnSource direct) : direct(direct) { } JoinColumnSource direct; diff --git a/src/duckdb/src/include/duckdb/optimizer/join_order/join_relation_set.hpp b/src/duckdb/src/include/duckdb/optimizer/join_order/join_relation_set.hpp index ea1be0c96..88f169cc5 100644 --- a/src/duckdb/src/include/duckdb/optimizer/join_order/join_relation_set.hpp +++ b/src/duckdb/src/include/duckdb/optimizer/join_order/join_relation_set.hpp @@ -9,6 +9,7 @@ #pragma once #include "duckdb/common/common.hpp" +#include "duckdb/common/unordered_multimap.hpp" #include "duckdb/common/unordered_set.hpp" #include "duckdb/common/optional_ptr.hpp" #include "duckdb/optimizer/join_order/relation_index.hpp" @@ -31,19 +32,14 @@ struct JoinRelationSet { idx_t count; //! Bitmask over the relation indexes for fast subset/intersection checks vector bitmask; + +private: + //! First word containing a relation (zero for empty sets) + idx_t first_word = 0; }; -//! The JoinRelationTree is a structure holding all the created JoinRelationSet objects and allowing fast lookup on to -//! them +//! Owns and interns relation sets so equal sets always refer to the same object. class JoinRelationSetManager { -public: - //! Contains a node with a JoinRelationSet and child relations - // FIXME: this structure is inefficient, could use a bitmap for lookup instead (todo: profile) - struct JoinRelationTreeNode { - unique_ptr relation; - unordered_map> children; - }; - public: //! Get an empty JoinRelationSet JoinRelationSet &GetEmptyJoinRelationSet(); @@ -61,7 +57,8 @@ class JoinRelationSetManager { void Print(); private: - JoinRelationTreeNode root; + //! Hash collisions retain distinct sets; entries own the stable relation-set objects. + unordered_multimap> relation_sets; optional_ptr empty_relation_set; }; diff --git a/src/duckdb/src/include/duckdb/optimizer/join_order/linearized_plan_enumerator.hpp b/src/duckdb/src/include/duckdb/optimizer/join_order/linearized_plan_enumerator.hpp new file mode 100644 index 000000000..4ab748f8b --- /dev/null +++ b/src/duckdb/src/include/duckdb/optimizer/join_order/linearized_plan_enumerator.hpp @@ -0,0 +1,46 @@ +//===----------------------------------------------------------------------===// +// DuckDB +// +// duckdb/optimizer/join_order/linearized_plan_enumerator.hpp +// +//===----------------------------------------------------------------------===// + +#pragma once + +#include "duckdb/optimizer/join_order/join_order_plan.hpp" + +namespace duckdb { + +//! One interval trial owns its memo, initialized from immutable region inputs. +class IntervalJoinEnumerator { +public: + IntervalJoinEnumerator(QueryGraphManager &graph, JoinOrderCandidateEvaluator &evaluator, + const JoinOrderPlanMap &inputs); + bool Solve(const vector &order); + const JoinOrderPlanMap &GetPlans() const; + +private: + QueryGraphManager &query_graph_manager; + JoinOrderCandidateEvaluator &evaluator; + JoinOrderPlanMap plans; +}; + +//! Owns approximate-search policy and comparison of independently constructed complete plans. +class LinearizedPlanEnumerator { +public: + LinearizedPlanEnumerator(QueryGraphManager &graph, CostModel &cost_model, JoinOrderCandidateEvaluator &evaluator); + bool SolveApproximately(JoinOrderPlanMap &plans); + +private: + bool SolveGreedy(JoinOrderPlanMap &plans); + unique_ptr CaptureInputPlan(JoinOrderPlanMap &plans, JoinRelationSet &root); + unique_ptr CaptureGreedyPlan(JoinOrderPlanMap &plans, JoinRelationSet &root); + void OfferPlan(JoinRelationSet &root, unique_ptr candidate, + unique_ptr &incumbent); + + QueryGraphManager &query_graph_manager; + CostModel &cost_model; + JoinOrderCandidateEvaluator &evaluator; +}; + +} // namespace duckdb diff --git a/src/duckdb/src/include/duckdb/optimizer/join_order/plan_enumerator.hpp b/src/duckdb/src/include/duckdb/optimizer/join_order/plan_enumerator.hpp index 7d868ff61..ec50de5f5 100644 --- a/src/duckdb/src/include/duckdb/optimizer/join_order/plan_enumerator.hpp +++ b/src/duckdb/src/include/duckdb/optimizer/join_order/plan_enumerator.hpp @@ -28,6 +28,7 @@ class PlanEnumerator { private: QueryGraphManager &query_graph_manager; + CostModel &cost_model; const QueryGraphEdges &query_graph; JoinOrderCandidateEvaluator candidate_evaluator; //! Result storage also provides the initial leaves and outlives reconstruction. diff --git a/src/duckdb/src/include/duckdb/optimizer/join_order/query_graph.hpp b/src/duckdb/src/include/duckdb/optimizer/join_order/query_graph.hpp index 36a516d9a..c00cc28e5 100644 --- a/src/duckdb/src/include/duckdb/optimizer/join_order/query_graph.hpp +++ b/src/duckdb/src/include/duckdb/optimizer/join_order/query_graph.hpp @@ -43,6 +43,7 @@ class QueryGraphEdges { public: //! Contains a node with info about neighboring relations and child edge infos struct QueryEdge { + optional_ptr relations; vector> neighbors; unordered_map> children; }; @@ -59,6 +60,8 @@ class QueryGraphEdges { //! Enumerate all neighbors of a given JoinRelationSet node void EnumerateNeighbors(JoinRelationSet &node, const std::function &callback) const; + //! Visit active edges with their complete endpoints. Return true from the callback to stop. + void EnumerateEdges(const std::function &callback) const; //! Create an edge in the edge_set void CreateEdge(JoinRelationSet &left, JoinRelationSet &right, optional_ptr predicate, optional_ptr join_operator = nullptr, bool generated_cross_product = false); diff --git a/src/duckdb/src/include/duckdb/optimizer/join_order/query_graph_manager.hpp b/src/duckdb/src/include/duckdb/optimizer/join_order/query_graph_manager.hpp index 044d2bba4..2b3ab5662 100644 --- a/src/duckdb/src/include/duckdb/optimizer/join_order/query_graph_manager.hpp +++ b/src/duckdb/src/include/duckdb/optimizer/join_order/query_graph_manager.hpp @@ -83,12 +83,14 @@ class QueryGraphManager { void BuildLeftJoinPredicates(); void BuildInnerCompanionSets(); void ClearExtractedExpressions(); + vector> GetPendingFilters(JoinRelationSet &root) const; idx_t FindGraphComponent(RelationIndex relation); idx_t GetGraphComponent(RelationIndex relation) const; void ConnectGraphComponents(const JoinRelationSet &left, const JoinRelationSet &right); GenerateJoinRelation GenerateJoins(vector> &extracted_relations, JoinRelationSet &set, - const vector &relation_stats); + const vector &relation_stats, + const vector> &pending_filters); public: ClientContext &context; @@ -106,6 +108,8 @@ class QueryGraphManager { //! used by the cardinality estimator to estimate distinct counts vector> filters_and_bindings; vector> join_operators; + //! Only these operator occurrences can restrict a candidate join. + vector> candidate_constraints; unordered_set operator_costing_predicates; unordered_set reconstructed_operators; vector inner_companion_roots; diff --git a/src/duckdb/src/include/duckdb/optimizer/join_order/relation_manager.hpp b/src/duckdb/src/include/duckdb/optimizer/join_order/relation_manager.hpp index cb28deb6d..91ef7a6e0 100644 --- a/src/duckdb/src/include/duckdb/optimizer/join_order/relation_manager.hpp +++ b/src/duckdb/src/include/duckdb/optimizer/join_order/relation_manager.hpp @@ -94,6 +94,7 @@ class RelationManager { LogicalOperator &op; optional_ptr parent; bool optimize_as_leaf; + bool has_throwing_predicate; }; bool ExtractJoinRelation(JoinOrderOptimizer &optimizer, PendingRelation relation, @@ -113,6 +114,7 @@ class RelationManager { vector> relations; reference_map_t operator_relations; column_binding_map_t normalized_bindings; + unordered_map> marker_dependencies; unordered_set active_recursive_ctes; bool has_recursive_relations = false; bool stats_complete = true; diff --git a/src/duckdb/src/include/duckdb/optimizer/mark_join_simplifier.hpp b/src/duckdb/src/include/duckdb/optimizer/mark_join_simplifier.hpp index 51f98e0e9..c472ce337 100644 --- a/src/duckdb/src/include/duckdb/optimizer/mark_join_simplifier.hpp +++ b/src/duckdb/src/include/duckdb/optimizer/mark_join_simplifier.hpp @@ -20,11 +20,14 @@ class Optimizer; class MarkJoinSimplifier { public: explicit MarkJoinSimplifier(Optimizer &optimizer); + void OptimizeConstantInput(unique_ptr &plan); void Optimize(unique_ptr &plan); private: void Rewrite(unique_ptr &op, NotNullExpressionAnalyzer &nullability, - BindingReplacementGraph &replacements, vector> &ancestors); + BindingReplacementGraph &replacements, vector> &ancestors, + bool constant_input_only); + bool TrySimplifyConstantInput(unique_ptr &op, BindingReplacementGraph &replacements); bool TrySimplify(unique_ptr &op, NotNullExpressionAnalyzer &nullability, BindingReplacementGraph &replacements); diff --git a/src/duckdb/src/include/duckdb/optimizer/projection_pullup.hpp b/src/duckdb/src/include/duckdb/optimizer/projection_pullup.hpp index efee5c900..fa6fef96b 100644 --- a/src/duckdb/src/include/duckdb/optimizer/projection_pullup.hpp +++ b/src/duckdb/src/include/duckdb/optimizer/projection_pullup.hpp @@ -11,17 +11,24 @@ class LogicalOperator; class ProjectionPullup : public LogicalOperatorVisitor { public: - explicit ProjectionPullup(Optimizer &optimizer_p, unique_ptr &root) - : optimizer(optimizer_p), root(root) { - } - - void Optimize(unique_ptr &op); - void VisitOperator(unique_ptr &op) override; + //! Run a complete pass, applying all pending binding replacements before returning. + static void Optimize(Optimizer &optimizer, unique_ptr &op); private: + ProjectionPullup(Optimizer &optimizer_p, unique_ptr &root_p, + BindingReplacementGraph &replacements_p) + : optimizer(optimizer_p), root(root_p), replacements(replacements_p) { + } + Optimizer &optimizer; unique_ptr &root; + //! Borrowed from OptimizeSubtree and shared by nested pullup scopes within the same binding boundary. + BindingReplacementGraph &replacements; vector> parents; + static void OptimizeSubtree(Optimizer &optimizer, unique_ptr &root, + unique_ptr &op); + void VisitOperator(unique_ptr &op) override; + void FlushReplacements(); optional_ptr FindParent(LogicalOperator &target, LogicalOperator ¤t); void PopParents(const LogicalOperator &op); void InsertProjectionBelowOp(unique_ptr &op, unique_ptr &child, bool stop_at_op); diff --git a/src/duckdb/src/include/duckdb/optimizer/regex_range_filter.hpp b/src/duckdb/src/include/duckdb/optimizer/regex_range_filter.hpp index 36714f263..1d17d7a41 100644 --- a/src/duckdb/src/include/duckdb/optimizer/regex_range_filter.hpp +++ b/src/duckdb/src/include/duckdb/optimizer/regex_range_filter.hpp @@ -16,10 +16,13 @@ class Optimizer; class RegexRangeFilter { public: - RegexRangeFilter() { + explicit RegexRangeFilter(ClientContext &context) : context(context) { } //! Perform filter pushdown unique_ptr Rewrite(unique_ptr op); + +private: + ClientContext &context; }; } // namespace duckdb diff --git a/src/duckdb/src/include/duckdb/optimizer/row_number_rewriter.hpp b/src/duckdb/src/include/duckdb/optimizer/row_number_rewriter.hpp index 52a2050c6..0d237d327 100644 --- a/src/duckdb/src/include/duckdb/optimizer/row_number_rewriter.hpp +++ b/src/duckdb/src/include/duckdb/optimizer/row_number_rewriter.hpp @@ -20,9 +20,9 @@ class RowNumberRewriter { unique_ptr Optimize(unique_ptr op); private: - unique_ptr RewritePlan(unique_ptr op, ColumnBindingReplacer &replacer); + unique_ptr RewritePlan(unique_ptr op, BindingReplacementGraph &replacements); bool CanOptimize(LogicalOperator &op); - unique_ptr RewriteGet(unique_ptr op, ColumnBindingReplacer &replacer); + unique_ptr RewriteGet(unique_ptr op, BindingReplacementGraph &replacements); }; } // namespace duckdb diff --git a/src/duckdb/src/include/duckdb/optimizer/rule/monotone_preimage.hpp b/src/duckdb/src/include/duckdb/optimizer/rule/monotone_preimage.hpp index f864dd23f..e59c41141 100644 --- a/src/duckdb/src/include/duckdb/optimizer/rule/monotone_preimage.hpp +++ b/src/duckdb/src/include/duckdb/optimizer/rule/monotone_preimage.hpp @@ -13,10 +13,11 @@ namespace duckdb { //! Rewrites `f(col) OP const` into a direct range predicate on `col` when `f` is a monotone -//! (ArgProperties) unary function over an exact integer/date column. The preimage boundary is +//! (ArgProperties) unary function over an exact integer/decimal/date column. The preimage boundary is //! found by bisecting the column's value domain, generalizing the hand-written inverses in -//! move_constants / date_trunc_simplification / timestamp_comparison. Exact-or-bail: if an exact -//! boundary cannot be established the rule leaves the expression untouched. +//! move_constants / date_trunc_simplification / timestamp_comparison. floor/ceil/trunc over FLOAT and +//! DOUBLE are inverted in closed form. Exact-or-bail: if an exact boundary cannot be established the +//! rule leaves the expression untouched. class MonotonePreimageRule : public Rule { public: explicit MonotonePreimageRule(ExpressionRewriter &rewriter); diff --git a/src/duckdb/src/include/duckdb/optimizer/scalar_aggregate_merger.hpp b/src/duckdb/src/include/duckdb/optimizer/scalar_aggregate_merger.hpp index c802177fd..3cbe5dcb4 100644 --- a/src/duckdb/src/include/duckdb/optimizer/scalar_aggregate_merger.hpp +++ b/src/duckdb/src/include/duckdb/optimizer/scalar_aggregate_merger.hpp @@ -39,11 +39,15 @@ class ScalarAggregateMerger { struct MergeTarget; private: + class ConjunctIndex; + class ScanCollection; + void VisitOperator(unique_ptr &op); //! Merges the eligible leaves of the cross-product tree rooted at `op` void MergeCrossProduct(unique_ptr &op); - //! Appends `leaf` to `branches` when it has the shape of a branch - static void TryMatchBranch(unique_ptr &leaf, vector &branches); + //! Appends leaves[leaf_index] to branches when it has the shape of a branch + static void TryMatchBranch(const vector>> &leaves, idx_t leaf_index, + vector &branches); //! Whether the scans of `branch` cost enough for the merge to pay off: a table function (files, remote sources) //! or a table of at least scalar_aggregate_merge_threshold rows bool IsWorthMerging(const Branch &branch); @@ -53,7 +57,7 @@ class ScalarAggregateMerger { private: Optimizer &optimizer; //! The bindings of the branches that were merged away, pointed at the merged projection's columns - vector replacements; + BindingReplacementGraph replacements; }; } // namespace duckdb diff --git a/src/duckdb/src/include/duckdb/optimizer/topn_optimizer.hpp b/src/duckdb/src/include/duckdb/optimizer/topn_optimizer.hpp index 4a3a92c9a..f64ad981a 100644 --- a/src/duckdb/src/include/duckdb/optimizer/topn_optimizer.hpp +++ b/src/duckdb/src/include/duckdb/optimizer/topn_optimizer.hpp @@ -9,13 +9,18 @@ #pragma once #include "duckdb/common/constants.hpp" +#include "duckdb/common/enums/expression_type.hpp" #include "duckdb/common/optional_ptr.hpp" +#include "duckdb/common/shared_ptr.hpp" +#include "duckdb/common/types.hpp" +#include "duckdb/planner/column_binding.hpp" namespace duckdb { class ClientContext; class LogicalOperator; class LogicalTopN; class Optimizer; +struct DynamicFilterData; class TopN { public: @@ -25,6 +30,11 @@ class TopN { unique_ptr Optimize(unique_ptr op); //! Whether we can perform the optimization on this operator static bool CanOptimize(LogicalOperator &op, optional_ptr context = nullptr); + //! Pushes a dynamic filter "binding [boundary]" into the scans below the operator that produce + //! the column. Returns the filter, or nullptr if no scan can evaluate it. + static shared_ptr PushDynamicFilterIntoScans(ClientContext &context, LogicalOperator &child, + ColumnBinding binding, const LogicalType &type, + bool nulls_first, ExpressionType comparison_type); private: void PushdownDynamicFilters(LogicalTopN &op); diff --git a/src/duckdb/src/include/duckdb/optimizer/topn_window_elimination.hpp b/src/duckdb/src/include/duckdb/optimizer/topn_window_elimination.hpp index 9efb63ac4..cdd3adc63 100644 --- a/src/duckdb/src/include/duckdb/optimizer/topn_window_elimination.hpp +++ b/src/duckdb/src/include/duckdb/optimizer/topn_window_elimination.hpp @@ -67,6 +67,8 @@ class TopNWindowElimination : public LogicalOperatorVisitor { vector &new_bindings); unique_ptr CreateAggregateExpression(vector> aggregate_params, bool requires_arg, const TopNWindowEliminationParameters ¶ms) const; + bool AggregateKeepsZeroSign(const LogicalWindow &window, const vector> &payload, + const TopNWindowEliminationParameters ¶ms) const; unique_ptr CreateRowNumberGenerator(unique_ptr aggregate_column_ref) const; void AddStructExtractExprs(vector> &exprs, const LogicalType &struct_type, const unique_ptr &aggregate_column_ref) const; diff --git a/src/duckdb/src/include/duckdb/parallel/async_result.hpp b/src/duckdb/src/include/duckdb/parallel/async_result.hpp index 58fbf0be8..be5c9f972 100644 --- a/src/duckdb/src/include/duckdb/parallel/async_result.hpp +++ b/src/duckdb/src/include/duckdb/parallel/async_result.hpp @@ -21,6 +21,9 @@ class DataChunk; class InterruptState; class TaskExecutor; class Executor; +class ExecutionContext; +class StateWithBlockableTasks; +struct OperatorSourceInput; enum class AsyncResultsExecutionMode : uint8_t { SYNCHRONOUS, //! BLOCKED should not bubble up, and they should be executed synchronously @@ -60,6 +63,11 @@ class AsyncResult { //! Execute tasks synchronously at callsite, side by side on the result's pool: the calling thread works on them //! too and returns when all of them are done. Same preconditions and result as the overload above. void ExecuteTasksSynchronously(ClientContext &context); + //! For a source operator: schedules the tasks and returns BLOCKED when the pipeline can block (it can call back + //! and the state allows blocking), otherwise runs them synchronously, side by side, and returns HAVE_MORE_OUTPUT. + //! Needs to be called with non-empty async_tasks and from BLOCKED state; takes the state's lock. + SourceResultType ScheduleOrExecute(ExecutionContext &context, OperatorSourceInput &input, + StateWithBlockableTasks &state); static AsyncResultType GetAsyncResultType(SourceResultType s); //! Wraps tasks into a BLOCKED result, or HAVE_MORE_OUTPUT when there are none diff --git a/src/duckdb/src/include/duckdb/parallel/pipeline_broadcast_exchange.hpp b/src/duckdb/src/include/duckdb/parallel/pipeline_broadcast_exchange.hpp index 1198a19a6..a4825d5c9 100644 --- a/src/duckdb/src/include/duckdb/parallel/pipeline_broadcast_exchange.hpp +++ b/src/duckdb/src/include/duckdb/parallel/pipeline_broadcast_exchange.hpp @@ -60,6 +60,7 @@ class PipelineBroadcastExchangeLocalState { private: friend class PipelineBroadcastExchange; + PipelineExecutor &GetOrCreateDirectExecutor(idx_t index); SinkResultType Push(DataChunk &chunk, const SourcePartitionInfo &partition_info, const InterruptState &interrupt_state); SinkNextBatchType NextBatch(const SourcePartitionInfo &partition_info, const InterruptState &interrupt_state); @@ -72,6 +73,8 @@ class PipelineBroadcastExchangeLocalState { OperatorPartitionData GetSourcePartitionData(const SourcePartitionInfo &partition_info) const; optional_idx GetSourceMinBatchIndex(const SourcePartitionInfo &partition_info) const; + ClientContext &context; + vector> direct_pipeline_refs; vector> direct_executors; vector> direct_input_chunks; idx_t direct_idx = 0; diff --git a/src/duckdb/src/include/duckdb/planner/expression/bound_aggregate_expression.hpp b/src/duckdb/src/include/duckdb/planner/expression/bound_aggregate_expression.hpp index e129f7c8d..61d1801fe 100644 --- a/src/duckdb/src/include/duckdb/planner/expression/bound_aggregate_expression.hpp +++ b/src/duckdb/src/include/duckdb/planner/expression/bound_aggregate_expression.hpp @@ -19,6 +19,8 @@ class BoundAggregateExpression : public Expression { static constexpr const ExpressionClass TYPE = ExpressionClass::BOUND_AGGREGATE; //! Preserves the first argument's domain for singleton input when the second argument is non-NULL static constexpr const char *NON_NULL_SELECTOR_DOMAIN_PROPERTY = "duckdb.aggregate.non_null_selector_domain"; + //! Stores the returned first argument as a sort key, which does not keep the sign of a zero + static constexpr const char *ARG_STORED_AS_SORT_KEY_PROPERTY = "duckdb.aggregate.arg_stored_as_sort_key"; public: BoundAggregateExpression(BoundAggregateFunction function, vector> children, diff --git a/src/duckdb/src/include/duckdb/planner/logical_tokens.hpp b/src/duckdb/src/include/duckdb/planner/logical_tokens.hpp index c0ed45bfa..153429956 100644 --- a/src/duckdb/src/include/duckdb/planner/logical_tokens.hpp +++ b/src/duckdb/src/include/duckdb/planner/logical_tokens.hpp @@ -63,6 +63,7 @@ class LogicalUpdateExtensions; class LogicalVacuum; class LogicalSet; class LogicalReset; +class LogicalTopKeyFilter; class LogicalTopN; class LogicalUnnest; class LogicalUpdate; diff --git a/src/duckdb/src/include/duckdb/planner/operator/list.hpp b/src/duckdb/src/include/duckdb/planner/operator/list.hpp index 7df2c6522..5cbb9e42a 100644 --- a/src/duckdb/src/include/duckdb/planner/operator/list.hpp +++ b/src/duckdb/src/include/duckdb/planner/operator/list.hpp @@ -50,6 +50,7 @@ #include "duckdb/planner/operator/logical_load.hpp" #include "duckdb/planner/operator/logical_transaction.hpp" #include "duckdb/planner/operator/logical_update_extensions.hpp" +#include "duckdb/planner/operator/logical_top_key_filter.hpp" #include "duckdb/planner/operator/logical_top_n.hpp" #include "duckdb/planner/operator/logical_trigger.hpp" #include "duckdb/planner/operator/logical_unnest.hpp" diff --git a/src/duckdb/src/include/duckdb/planner/operator/logical_limit.hpp b/src/duckdb/src/include/duckdb/planner/operator/logical_limit.hpp index 9579f27da..8db7d7c49 100644 --- a/src/duckdb/src/include/duckdb/planner/operator/logical_limit.hpp +++ b/src/duckdb/src/include/duckdb/planner/operator/logical_limit.hpp @@ -36,6 +36,9 @@ class LogicalLimit : public LogicalOperator { void Serialize(Serializer &serializer) const override; static unique_ptr Deserialize(Deserializer &deserializer); + //! Warns that an OFFSET skips rows of an input whose row order is not guaranteed + static void WarnUnorderedOffset(ClientContext &context); + protected: void ResolveTypes() override; }; diff --git a/src/duckdb/src/include/duckdb/planner/operator/logical_top_key_filter.hpp b/src/duckdb/src/include/duckdb/planner/operator/logical_top_key_filter.hpp new file mode 100644 index 000000000..8f20a5640 --- /dev/null +++ b/src/duckdb/src/include/duckdb/planner/operator/logical_top_key_filter.hpp @@ -0,0 +1,63 @@ +//===----------------------------------------------------------------------===// +// DuckDB +// +// duckdb/planner/operator/logical_top_key_filter.hpp +// +// +//===----------------------------------------------------------------------===// + +#pragma once + +#include "duckdb/planner/bound_query_node.hpp" +#include "duckdb/planner/logical_operator.hpp" + +namespace duckdb { +struct DynamicFilterData; + +//! LogicalTopKeyFilter is a streaming filter below a grouped aggregate whose Top-N orders by a prefix of the group +//! keys. It removes rows whose key tuple sorts after a bound that is known to be at or after the "limit"-th smallest +//! distinct key tuple of its input, so that the aggregate does not have to aggregate most of the groups that the +//! Top-N discards.//! +//! The pruning is conservative. The contract of the operator is: +//! * it never removes a row of a group whose key tuple is among the "limit" smallest distinct key tuples of its +//! input (the groups that the Top-N above the aggregate can return), and +//! * it may pass any other row. +//! Its output is therefore a superset of the rows that are needed, not the rows of exactly "limit" distinct keys: rows +//! pass unfiltered while a thread warms up, while no bound has been published, while a thread works with an older +//! (larger) bound than the current one, after a thread has stopped filtering, and the bound of a thread is only as +//! small as the keys that it has seen itself. The aggregate above can receive rows of - and build - groups that are +//! not part of the result, with a part of their rows only. Only the Top-N above the aggregate decides the result: the +//! groups it returns are complete, and a group that is incomplete sorts after "limit" complete ones. +//! An optimizer that moves or copies this operator has to keep the Top-N on the same keys above it. +class LogicalTopKeyFilter : public LogicalOperator { +public: + static constexpr const LogicalOperatorType TYPE = LogicalOperatorType::LOGICAL_TOP_KEY_FILTER; + +public: + LogicalTopKeyFilter(vector orders, idx_t limit); + ~LogicalTopKeyFilter() override; + + //! The keys (expressions over the child) and their order + vector orders; + //! The number of smallest distinct key tuples whose rows are guaranteed to pass (LIMIT + OFFSET of the Top-N). Not + //! an upper bound of the number of distinct key tuples in the output. + idx_t limit; + //! Dynamic table filter on the first key (if any) + shared_ptr dynamic_filter; + +public: + vector GetColumnBindings() override { + return children[0]->GetColumnBindings(); + } + + InsertionOrderPreservingMap ParamsToString() const override; + + void Serialize(Serializer &serializer) const override; + static unique_ptr Deserialize(Deserializer &deserializer); + +protected: + void ResolveTypes() override { + types = children[0]->types; + } +}; +} // namespace duckdb diff --git a/src/duckdb/src/include/duckdb/storage/external_file_cache/caching_file_system_wrapper.hpp b/src/duckdb/src/include/duckdb/storage/external_file_cache/caching_file_system_wrapper.hpp index 1b860cc69..4fe386f54 100644 --- a/src/duckdb/src/include/duckdb/storage/external_file_cache/caching_file_system_wrapper.hpp +++ b/src/duckdb/src/include/duckdb/storage/external_file_cache/caching_file_system_wrapper.hpp @@ -103,11 +103,6 @@ class CachingFileSystemWrapper : public FileSystem, public enable_shared_from_th DUCKDB_API vector Glob(const string &path, FileOpener *opener = nullptr) override; - DUCKDB_API void RegisterSubSystem(unique_ptr sub_fs) override; - DUCKDB_API void RegisterCompressionFilesystem(unique_ptr fs) override; - DUCKDB_API void UnregisterSubSystem(const string &name) override; - DUCKDB_API unique_ptr ExtractSubSystem(const string &name) override; - DUCKDB_API vector ListSubSystems() override; DUCKDB_API bool CanHandleFile(const string &fpath) override; DUCKDB_API void Seek(FileHandle &handle, idx_t location) override; @@ -121,11 +116,6 @@ class CachingFileSystemWrapper : public FileSystem, public enable_shared_from_th DUCKDB_API unique_ptr OpenCompressedFile(QueryContext context, unique_ptr handle, bool write) override; - DUCKDB_API void SetDisabledFileSystems(const vector &names) override; - DUCKDB_API vector GetDisabledFileSystems() override; - DUCKDB_API bool SubSystemIsDisabled(const string &name) override; - DUCKDB_API bool IsDisabledForPath(const string &path) override; - protected: DUCKDB_API unique_ptr OpenFileExtended(const OpenFileInfo &path, FileOpenFlags flags, optional_ptr opener) override; diff --git a/src/duckdb/src/include/duckdb/storage/table/append_state.hpp b/src/duckdb/src/include/duckdb/storage/table/append_state.hpp index ae9956c9c..dc3921f79 100644 --- a/src/duckdb/src/include/duckdb/storage/table/append_state.hpp +++ b/src/duckdb/src/include/duckdb/storage/table/append_state.hpp @@ -127,7 +127,8 @@ struct ConstraintState { struct LocalAppendState { TableAppendState append_state; - LocalTableStorage *storage; + //! Keeps the storage alive: an ALTER of another connection can replace it in the local storage + shared_ptr storage; //! The context of the operation that appends (the local storage can outlive the connection that created it) optional_ptr context; unique_ptr constraint_state; diff --git a/src/duckdb/src/include/duckdb/storage/table/scan_state.hpp b/src/duckdb/src/include/duckdb/storage/table/scan_state.hpp index 169541687..7ad2bdc6d 100644 --- a/src/duckdb/src/include/duckdb/storage/table/scan_state.hpp +++ b/src/duckdb/src/include/duckdb/storage/table/scan_state.hpp @@ -325,6 +325,8 @@ class CollectionScanState { //! Optional state for custom row group ordering unique_ptr reorderer; + //! Keeps the transaction-local storage that is scanned alive (it can be replaced by an ALTER meanwhile) + shared_ptr local_storage; //! Keeps the transaction-local row groups from being replaced while they are scanned unique_ptr local_row_groups_lock; diff --git a/src/duckdb/src/include/duckdb/transaction/local_storage.hpp b/src/duckdb/src/include/duckdb/transaction/local_storage.hpp index 62b702b7c..79945fd50 100644 --- a/src/duckdb/src/include/duckdb/transaction/local_storage.hpp +++ b/src/duckdb/src/include/duckdb/transaction/local_storage.hpp @@ -39,17 +39,29 @@ struct ParallelCollectionScanState; struct TableAppendState; struct TransactionData; +//! The transaction-local indexes of a table: shared by the storages of the versions of the table (see ALTER) +struct LocalStorageIndexes { + //! The set of unique append indexes. + TableIndexList append_indexes; + //! The set of delete indexes. + TableIndexList delete_indexes; +}; + class LocalTableStorage : public enable_shared_from_this { public: // Create a new LocalTableStorage explicit LocalTableStorage(Context &context, DataTable &table); - //! Create a LocalTableStorage from an ALTER TYPE. + //! Create the LocalTableStorage of the new version of a table from an ALTER TYPE: the storage of the old version + //! is not modified (it can still be in use), the new one shares what can be shared with it. LocalTableStorage(ClientContext &context, DataTable &new_data_table, LocalTableStorage &parent, const idx_t alter_column_index, const LogicalType &target_type, const vector &bound_columns, Expression &cast_expr, TransactionData transaction); - //! Create a LocalTableStorage from a DROP COLUMN. - LocalTableStorage(DataTable &new_data_table, LocalTableStorage &parent, const idx_t drop_column_index); - // Create a LocalTableStorage from an ADD COLUMN + //! Create the LocalTableStorage of the new version of a table from a DROP COLUMN. + LocalTableStorage(ClientContext &context, DataTable &new_data_table, LocalTableStorage &parent, + const idx_t drop_column_index); + //! Create the LocalTableStorage of the new version of a table from an ADD CONSTRAINT (the row groups are shared) + LocalTableStorage(ClientContext &context, DataTable &new_data_table, LocalTableStorage &parent); + //! Create the LocalTableStorage of the new version of a table from an ADD COLUMN LocalTableStorage(ClientContext &context, DataTable &table, LocalTableStorage &parent, ColumnDefinition &new_column, ExpressionExecutor &default_executor); ~LocalTableStorage(); @@ -63,10 +75,6 @@ class LocalTableStorage : public enable_shared_from_this { Allocator &allocator; //! The main row group collection. unique_ptr row_groups; - //! The set of unique append indexes. - TableIndexList append_indexes; - //! The set of delete indexes. - TableIndexList delete_indexes; //! Set to INSERT_DUPLICATES, if we are skipping constraint checking during, e.g., WAL replay. IndexAppendMode index_append_mode = IndexAppendMode::DEFAULT; //! The number of deleted rows (parallel DELETEs update it concurrently) @@ -125,8 +133,16 @@ class LocalTableStorage : public enable_shared_from_this { RowGroupCollection &GetCollection(); OptimisticWriteCollection &GetPrimaryCollection(); + TableIndexList &GetAppendIndexes() const { + return indexes->append_indexes; + } + TableIndexList &GetDeleteIndexes() const { + return indexes->delete_indexes; + } private: + //! The transaction-local indexes, shared with the storage of the next version of the table after an ALTER + shared_ptr indexes; mutex collections_lock; }; @@ -135,8 +151,8 @@ class LocalTableManager { shared_ptr MoveEntry(DataTable &table); reference_map_t> MoveEntries(); vector> GetEntries() const; - optional_ptr GetStorage(const DataTable &table) const; - LocalTableStorage &GetOrCreateStorage(Context &context, DataTable &table); + shared_ptr GetStorage(const DataTable &table) const; + shared_ptr GetOrCreateStorage(Context &context, DataTable &table); idx_t EstimatedSize() const; bool IsEmpty() const; void InsertEntry(DataTable &table, shared_ptr entry); @@ -219,17 +235,17 @@ class LocalStorage { void AddColumn(ClientContext &context, DataTable &old_dt, DataTable &new_dt, ColumnDefinition &new_column, ExpressionExecutor &default_executor); - void DropColumn(DataTable &old_dt, DataTable &new_dt, const idx_t drop_column_index); + void DropColumn(ClientContext &context, DataTable &old_dt, DataTable &new_dt, const idx_t drop_column_index); void ChangeType(ClientContext &context, DataTable &old_dt, DataTable &new_dt, idx_t changed_idx, const LogicalType &target_type, const vector &bound_columns, Expression &cast_expr); - void MoveStorage(DataTable &old_dt, DataTable &new_dt); + void MoveStorage(ClientContext &context, DataTable &old_dt, DataTable &new_dt); void FetchChunk(DataTable &table, const Vector &row_ids, idx_t count, const vector &col_ids, DataChunk &chunk, ColumnFetchState &fetch_state); //! Returns true, if the local storage contains the row id. bool CanFetch(DataTable &table, const row_t row_id); TableIndexList &GetIndexes(Context &context, DataTable &table); - optional_ptr GetStorage(const DataTable &table); + shared_ptr GetStorage(const DataTable &table); void VerifyNewConstraint(Context &context, DataTable &parent, const BoundConstraint &constraint); diff --git a/src/duckdb/src/include/duckdb_extension_v2.h b/src/duckdb/src/include/duckdb_extension_v2.h index 851782c11..012074a33 100644 --- a/src/duckdb/src/include/duckdb_extension_v2.h +++ b/src/duckdb/src/include/duckdb_extension_v2.h @@ -292,7 +292,7 @@ typedef struct { (duckdb_v2_factory_handle factory, int32_t in_value, duckdb_v2_value_handle *out_value, duckdb_v2_error_info_handle *err); DUCKDB_V2_ERROR(*duckdb_v2_value_create_decimal) - (duckdb_v2_factory_handle factory, const duckdb_v2_hugeint_t *in_value, uint8_t width, uint8_t scale, + (duckdb_v2_factory_handle factory, const duckdb_v2_hugeint_t *in_value, uint32_t width, uint32_t scale, duckdb_v2_value_handle *out_value, duckdb_v2_error_info_handle *err); DUCKDB_V2_ERROR(*duckdb_v2_value_create_double) (duckdb_v2_factory_handle factory, double in_value, duckdb_v2_value_handle *out_value, @@ -397,7 +397,7 @@ typedef struct { DUCKDB_V2_ERROR(*duckdb_v2_value_get_date) (duckdb_v2_value_handle value, int32_t *out, duckdb_v2_error_info_handle *err); DUCKDB_V2_ERROR(*duckdb_v2_value_get_decimal) - (duckdb_v2_value_handle value, duckdb_v2_hugeint_t *out, uint8_t *out_width, uint8_t *out_scale, + (duckdb_v2_value_handle value, duckdb_v2_hugeint_t *out, uint32_t *out_width, uint32_t *out_scale, duckdb_v2_error_info_handle *err); DUCKDB_V2_ERROR(*duckdb_v2_value_get_double) (duckdb_v2_value_handle value, double *out, duckdb_v2_error_info_handle *err); @@ -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 35e3fb21a..7f0330ad6 100644 --- a/src/duckdb/src/include/duckdb_v2.h +++ b/src/duckdb/src/include/duckdb_v2.h @@ -11522,6 +11522,12 @@ DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_factory_create_type_from_id( * built-in kinds live. A qualified name is resolved exactly as written, with no system-catalog fallback, so it names * the type in that catalog or schema or fails. * + * The width of a DECIMAL, also one nested in another type, is bounded by the max_decimal_width setting of the factory's + * connection, and by the default of that setting, 1000000, for an instance's factory, which has no settings: the time + * and memory a wide decimal takes grow with its width. A wider type returns ERROR_INPUT_INVALID; create it with the + * factory of a connection that raised the setting. factory_create_type_from_id and factory_create_type_from_text apply + * the same bound. + * * Parameters are (name, value) pairs in two parallel arrays. param_names may be NULL to make every parameter * positional, and an empty entry makes that one parameter positional. Child types cross as TYPE values, built with * value_create_type. The built-in shapes are: decimal(width, scale); list(T); array(T, size); map(K, V); struct(fields, @@ -18066,8 +18072,10 @@ DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_value_get_uuid(duckdb_v2_value_handle val * storage tier the width selects. The integer getters convert, so a DECIMAL read through value_get_bigint is its * numeric value with the fraction dropped; this one always reports storage instead, together with the scale needed to * interpret it. A value of any other type id, and a NULL value, return ERROR_INPUT_INVALID. A DECIMAL wider than 38 - * digits (stored as BIGNUM) is reported the same way as long as its backing integer fits in 128 bits; beyond that the - * call fails and the exact storage is available through value_get_blob and bignum_decode, or through value_cast. + * digits (stored as BIGNUM) is reported the same way, whatever its width, as long as its backing integer fits in 128 + * bits. Beyond that the call fails, and the exact backing integer is read without a conversion: value_get_blob hands + * back the BIGNUM storage bytes, bignum_decode turns them into a sign and a big-endian magnitude, and the width and + * scale come from the value's logical type (value_get_logical_type and logical_type_get_param). * * history: * - unstable: v2.0.0 @@ -18080,7 +18088,7 @@ DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_value_get_uuid(duckdb_v2_value_handle val * @return DUCKDB_V2_ERROR */ DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_value_get_decimal(duckdb_v2_value_handle value, duckdb_v2_hugeint_t *out, - uint8_t *out_width, uint8_t *out_scale, + uint32_t *out_width, uint32_t *out_scale, duckdb_v2_error_info_handle *err); #endif @@ -18691,26 +18699,31 @@ DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_value_create_interval(duckdb_v2_factory_h /*! * Creates a DECIMAL value from its backing integer. * - * The value is scaled by 10^scale, so (18500, 18, 3) is 18.500. width is the total digit count and must be 1..255, the - * range of the uint8_t parameter; scale is the number of digits after the point and must not exceed width. Violating - * either returns ERROR_INPUT_INVALID, as does a value that does not fit in width digits. Widths above 38 build a wide - * decimal stored as BIGNUM, for which the 128-bit backing integer always fits. value_cast reaches decimals wider than - * 255 digits. + * The value is scaled by 10^scale, so (18500, 18, 3) is 18.500. width is the total digit count and must be at least 1; + * scale is the number of digits after the point and must not exceed width. Violating either returns + * ERROR_INPUT_INVALID, as does a value that does not fit in width digits. Widths above 38 build a wide decimal stored + * as BIGNUM, for which the 128-bit backing integer always fits; a wide decimal whose backing integer needs more than + * 128 bits is built through value_cast. + * + * The width is bounded like the width of a DECIMAL type the factory creates (see factory_create_type_from_name): by the + * max_decimal_width setting of the factory's connection, and by the default of that setting, 1000000, for an instance's + * factory. A wider width returns ERROR_INPUT_INVALID; use the factory of a connection that raised the setting. * * history: * - unstable: v2.0.0 * * @param factory The factory to create with. * @param in_value The backing integer, scaled by 10^scale. - * @param width Total digit count, 1..255 (the range of the uint8_t). + * @param width Total digit count, at least 1 and at most the factory's maximum DECIMAL width; widths above 38 are wide + * decimals. * @param scale Digits after the decimal point; must not exceed width. * @param out_value Receives the new DECIMAL 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_create_decimal(duckdb_v2_factory_handle factory, - const duckdb_v2_hugeint_t *in_value, uint8_t width, - uint8_t scale, duckdb_v2_value_handle *out_value, + const duckdb_v2_hugeint_t *in_value, uint32_t width, + uint32_t scale, duckdb_v2_value_handle *out_value, duckdb_v2_error_info_handle *err); #endif @@ -18977,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/logging/log_manager.cpp b/src/duckdb/src/logging/log_manager.cpp index 83e79c360..a6c0e0b86 100644 --- a/src/duckdb/src/logging/log_manager.cpp +++ b/src/duckdb/src/logging/log_manager.cpp @@ -235,8 +235,7 @@ void LogManager::SetLogSinkInternal(DatabaseInstance &db, LogConfig &new_config, } if (sink_name_to_lower == LogConfig::FILE_STORAGE_NAME) { - auto &fs = FileSystem::GetFileSystem(db); - if (fs.SubSystemIsDisabled("LocalFileSystem")) { + if (VirtualFileSystem::Get(db).SubSystemIsDisabled("LocalFileSystem")) { throw InvalidConfigurationException("Can not enable file logging with the LocalFileSystem disabled"); } } diff --git a/src/duckdb/src/logging/log_types.cpp b/src/duckdb/src/logging/log_types.cpp index 74a0bd9f6..c8d4d8961 100644 --- a/src/duckdb/src/logging/log_types.cpp +++ b/src/duckdb/src/logging/log_types.cpp @@ -221,7 +221,12 @@ static Value CreateHTTPHeadersValue(const HTTPHeaders &headers, const case_insen bool redact_http_logs) { vector keys; vector values; + case_insensitive_set_t seen; for (const auto &header : headers) { + const bool first_occurrence = seen.insert(header.first).second; + if (!first_occurrence) { + continue; + } keys.emplace_back(header.first); const bool allow_value = !redact_http_logs || allow_list.find(header.first) != allow_list.end(); values.emplace_back(allow_value ? header.second : HTTPLogType::REDACTED_VALUE); diff --git a/src/duckdb/src/main/capi/v2/capi_v2_logical_type.cpp b/src/duckdb/src/main/capi/v2/capi_v2_logical_type.cpp index 34aba23b2..5c09938e3 100644 --- a/src/duckdb/src/main/capi/v2/capi_v2_logical_type.cpp +++ b/src/duckdb/src/main/capi/v2/capi_v2_logical_type.cpp @@ -5,6 +5,8 @@ #include "duckdb/catalog/catalog_entry_retriever.hpp" #include "duckdb/common/enum_util.hpp" #include "duckdb/common/logical_type_info.hpp" +#include "duckdb/common/type_visitor.hpp" +#include "duckdb/common/types/decimal.hpp" #include "duckdb/common/types/geometry_crs.hpp" #include "duckdb/common/types/string_type.hpp" #include "duckdb/common/types/vector.hpp" @@ -140,11 +142,13 @@ LogicalType BindBuiltinTypeV2(const QualifiedName &name, const vector &args) { + LogicalType result; if (!factory.TryGetClientContext()) { - return BindBuiltinTypeV2(name, args); + result = BindBuiltinTypeV2(name, args); + } else { + factory.WithTransaction([&](ClientContext &context) { result = BindTypeByNameV2(context, name, args); }); } - LogicalType result; - factory.WithTransaction([&](ClientContext &context) { result = BindTypeByNameV2(context, name, args); }); + CheckDecimalWidthV2(factory, result); return result; } @@ -217,6 +221,27 @@ Value TypeParamValue(const LogicalType &type, idx_t index, std::string_view &out } // anonymous namespace +void CheckDecimalWidthV2(CV2Factory &factory, const LogicalType &type) { + auto context = factory.TryGetClientContext(); + const uint32_t limit = context ? DecimalWidthLimit::FromSetting(context).width : Decimal::DEFAULT_MAX_WIDTH; + TypeVisitor::Contains(type, [&](const LogicalType &child) { + if (child.id() != LogicalTypeId::DECIMAL || DecimalType::GetWidth(child) <= limit) { + return false; + } + if (context) { + throw InvalidInputException( + "DECIMAL width %u exceeds the maximum DECIMAL width of %u (SET max_decimal_width to allow wider " + "decimals)", + DecimalType::GetWidth(child), limit); + } + throw InvalidInputException( + "DECIMAL width %u exceeds the maximum DECIMAL width of %u: a factory without a connection creates decimals " + "up to the default of max_decimal_width, use the factory of a connection that raised the setting for wider " + "decimals", + DecimalType::GetWidth(child), limit); + }); +} + auto ResolveCommonType(CV2Factory &factory, const vector &types) -> LogicalType { D_ASSERT(!types.empty()); auto context = factory.TryGetClientContext(); @@ -309,13 +334,14 @@ static void CreateLogicalTypeFromTextV2(CV2Factory &factory, std::string_view te *out_type = nullptr; // Parse and bind errors propagate. auto string = duckdb::string(text); + duckdb::LogicalType parsed; if (!factory.TryGetClientContext()) { - *out_type = Convert(duckdb::TypeManager::Get(factory.GetDatabase()).ParseLogicalType(string)); - return; + parsed = duckdb::TypeManager::Get(factory.GetDatabase()).ParseLogicalType(string); + } else { + factory.WithTransaction( + [&](duckdb::ClientContext &context) { parsed = duckdb::TransformStringToLogicalType(string, context); }); } - duckdb::LogicalType parsed; - factory.WithTransaction( - [&](duckdb::ClientContext &context) { parsed = duckdb::TransformStringToLogicalType(string, context); }); + CheckDecimalWidthV2(factory, parsed); *out_type = Convert(std::move(parsed)); } 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 f90c79071..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 @@ -106,15 +107,19 @@ LogicalType RequireValueType(duckdb_v2_logical_type_handle type) { // The DECIMAL storage tier follows from the width, and the engine's hugeint // constructor covers only the widest one, so the narrower tiers go through the // int64 form. Width, scale and the value's digit count are gated here: either -// would otherwise build a broken value. The uint8_t parameters reach widths -// up to 255; wider decimals are built through value_cast. -Value BuildDecimal(const duckdb_v2_hugeint_t *in_value, uint8_t width, uint8_t scale) { +// would otherwise build a broken value. The width is the uint32_t of the +// engine, bounded by the factory like the types it creates: a value of a huge +// width takes time and memory in proportion to the width wherever it is +// formatted or cast. A wide decimal whose backing integer needs more than +// 128 bits is built through value_cast. +Value BuildDecimal(CV2Factory &factory, const duckdb_v2_hugeint_t *in_value, uint32_t width, uint32_t scale) { if (width < 1) { throw InvalidInputException(": DECIMAL width must be at least 1"); } if (scale > width) { throw InvalidInputException(": DECIMAL scale cannot exceed the width"); } + CheckDecimalWidthV2(factory, LogicalType::DECIMAL(width, scale)); auto value = Convert(in_value); // a 128-bit value has at most 39 digits, so only narrower widths can be exceeded if (width < Hugeint::CACHED_POWERS_OF_TEN && @@ -338,8 +343,8 @@ DUCKDB_V2_ERROR duckdb_v2_value_get_uuid(duckdb_v2_value_handle value, duckdb_v2 }); } -DUCKDB_V2_ERROR duckdb_v2_value_get_decimal(duckdb_v2_value_handle value, duckdb_v2_hugeint_t *out, uint8_t *out_width, - uint8_t *out_scale, duckdb_v2_error_info_handle *err) { +DUCKDB_V2_ERROR duckdb_v2_value_get_decimal(duckdb_v2_value_handle value, duckdb_v2_hugeint_t *out, uint32_t *out_width, + uint32_t *out_scale, duckdb_v2_error_info_handle *err) { DUCKDB_CHECK_ARG(out); DUCKDB_CHECK_ARG(out_width); DUCKDB_CHECK_ARG(out_scale); @@ -347,14 +352,8 @@ DUCKDB_V2_ERROR duckdb_v2_value_get_decimal(duckdb_v2_value_handle value, duckdb RequireTypedValue(value, duckdb::LogicalTypeId::DECIMAL); auto &v = *Convert(value); auto &type = v.type(); - if (duckdb::DecimalType::GetWidth(type) > duckdb::NumericLimits::Maximum()) { - throw duckdb::OutOfRangeException( - "duckdb_v2_value_get_decimal: the width of %s does not fit the uint8_t of the API; read its storage " - "with value_get_blob and bignum_decode, or convert it with value_cast", - type.ToString()); - } - *out_width = duckdb::NumericCast(duckdb::DecimalType::GetWidth(type)); - *out_scale = duckdb::NumericCast(duckdb::DecimalType::GetScale(type)); + *out_width = duckdb::DecimalType::GetWidth(type); + *out_scale = duckdb::DecimalType::GetScale(type); // The storage tier follows from the width; widen it to the one form the // caller always gets back. switch (type.InternalType()) { @@ -373,8 +372,10 @@ DUCKDB_V2_ERROR duckdb_v2_value_get_decimal(duckdb_v2_value_handle value, duckdb if (!duckdb::DecimalHelper::TryToHugeint(v.GetValueUnsafe(), unscaled)) { throw duckdb::OutOfRangeException( - "duckdb_v2_value_get_decimal: the value does not fit in 128 bits; read its storage with " - "value_get_blob and bignum_decode, or convert it with value_cast"); + "duckdb_v2_value_get_decimal: the backing integer of this %s value does not fit in 128 bits; " + "read it exactly with duckdb_v2_value_get_blob (the BIGNUM storage bytes of the backing integer) " + "and duckdb_v2_bignum_decode (its sign and big-endian magnitude)", + type.ToString()); } *out = Convert(unscaled); break; @@ -724,12 +725,12 @@ DUCKDB_V2_ERROR duckdb_v2_value_create_interval(duckdb_v2_factory_handle factory // --------------------------------------------------------------------------- DUCKDB_V2_ERROR duckdb_v2_value_create_decimal(duckdb_v2_factory_handle factory, const duckdb_v2_hugeint_t *in_value, - uint8_t width, uint8_t scale, duckdb_v2_value_handle *out_value, + uint32_t width, uint32_t scale, duckdb_v2_value_handle *out_value, duckdb_v2_error_info_handle *err) { DUCKDB_CHECK_ARG(factory); DUCKDB_CHECK_ARG(out_value); *out_value = nullptr; - return WithErrorHandler(err, [&]() { *out_value = Emit(BuildDecimal(in_value, width, scale)); }); + return WithErrorHandler(err, [&]() { *out_value = Emit(BuildDecimal(*Convert(factory), in_value, width, scale)); }); } DUCKDB_V2_ERROR duckdb_v2_value_create_uuid(duckdb_v2_factory_handle factory, const duckdb_v2_hugeint_t *in_value, @@ -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/src/main/client_data.cpp b/src/duckdb/src/main/client_data.cpp index d24a9a8d2..9caedfa85 100644 --- a/src/duckdb/src/main/client_data.cpp +++ b/src/duckdb/src/main/client_data.cpp @@ -13,6 +13,7 @@ #include "duckdb/main/database.hpp" #include "duckdb/main/database_manager.hpp" #include "duckdb/main/query_profiler.hpp" +#include "duckdb/optimizer/expression_rewriter.hpp" namespace duckdb { diff --git a/src/duckdb/src/main/client_verify.cpp b/src/duckdb/src/main/client_verify.cpp index 81aee9c96..b458dad39 100644 --- a/src/duckdb/src/main/client_verify.cpp +++ b/src/duckdb/src/main/client_verify.cpp @@ -14,6 +14,7 @@ #include "duckdb/common/serializer/binary_serializer.hpp" #include "duckdb/common/serializer/memory_stream.hpp" #include "duckdb/common/types/uuid.hpp" +#include "duckdb/parser/expression/function_expression.hpp" #include "duckdb/parser/expression/parameter_expression.hpp" #include "duckdb/parser/expression/subquery_expression.hpp" #include "duckdb/parser/parsed_expression_iterator.hpp" @@ -32,6 +33,18 @@ struct PreparedStatementVerification { identifier_map_t> values; }; +//! The offset of a MATCH_RECOGNIZE navigation (FIRST, LAST, PREV or NEXT), which must stay a constant +static optional_ptr> MatchRecognizeNavigationOffset(FunctionExpression &function) { + if (function.GetArguments().size() != 2 || function.GetQualifiedName().Path().size() > 1) { + return nullptr; + } + auto name = StringUtil::Upper(function.FunctionName().GetIdentifierName()); + if (name != "FIRST" && name != "LAST" && name != "PREV" && name != "NEXT") { + return nullptr; + } + return &function.GetArgumentsMutable()[1].GetExpressionMutable(); +} + void PreparedStatementVerification::ConvertConstants(QueryNode &node) { ParsedExpressionIterator::EnumerateQueryNodeChildren( node, [&](unique_ptr &child) { ConvertConstants(child); }); @@ -67,8 +80,15 @@ void PreparedStatementVerification::ConvertConstants(unique_ptrCast().Subquery(); ConvertConstants(*subquery->node); } - ParsedExpressionIterator::EnumerateChildren(*expr, - [&](unique_ptr &child) { ConvertConstants(child); }); + optional_ptr> constant_child; + if (expr->GetExpressionClass() == ExpressionClass::FUNCTION) { + constant_child = MatchRecognizeNavigationOffset(expr->Cast()); + } + ParsedExpressionIterator::EnumerateChildren(*expr, [&](unique_ptr &child) { + if (&child != constant_child.get()) { + ConvertConstants(child); + } + }); } //! Swap in a statement produced by verification, carrying over the source text of the statement the user diff --git a/src/duckdb/src/main/config.cpp b/src/duckdb/src/main/config.cpp index 7fc2fe478..e80ad301d 100644 --- a/src/duckdb/src/main/config.cpp +++ b/src/duckdb/src/main/config.cpp @@ -1029,9 +1029,10 @@ const ExtensionCallbackManager &DBConfig::GetCallbackManager() const { } string DBConfig::SanitizeAllowedPath(const string &path_p, optional_ptr opener) const { - auto result = file_system->CanonicalizePath(FileSystem::ExpandPath(path_p, opener)); + auto &fs = file_system->FindFileSystem(path_p, opener); + auto result = fs.CanonicalizePath(FileSystem::ExpandPath(path_p, opener), opener); // allowed_directories/allowed_path always uses forward slashes regardless of the OS - auto path_sep = file_system->PathSeparator(path_p); + auto path_sep = fs.PathSeparator(path_p); if (path_sep != "/") { result = StringUtil::Replace(result, path_sep, "/"); } diff --git a/src/duckdb/src/main/context.cpp b/src/duckdb/src/main/context.cpp index 0ffa64af4..1d385560d 100644 --- a/src/duckdb/src/main/context.cpp +++ b/src/duckdb/src/main/context.cpp @@ -24,16 +24,15 @@ class ClientFileSystem : public OpenerFileSystem { explicit ClientFileSystem(ClientContext &context_p) : context(context_p) { } - FileSystem &GetFileSystem() const override { - auto &config = DBConfig::GetConfig(context); - return *config.file_system; +private: + VirtualFileSystem &GetFileSystem() const override { + return VirtualFileSystem::Get(context); } optional_ptr GetOpener() const override { return context.GetContext().TryGetFileOpener(); } -private: ClientContext &context; }; diff --git a/src/duckdb/src/main/database.cpp b/src/duckdb/src/main/database.cpp index 88085e2b8..7f405ef51 100644 --- a/src/duckdb/src/main/database.cpp +++ b/src/duckdb/src/main/database.cpp @@ -164,6 +164,14 @@ Catalog &Catalog::GetCatalog(AttachedDatabase &db) { return db.GetCatalog(); } +VirtualFileSystem &VirtualFileSystem::Get(DatabaseInstance &db) { + return *db.config.file_system; +} + +VirtualFileSystem &VirtualFileSystem::Get(ClientContext &context) { + return Get(*context.db); +} + FileSystem &FileSystem::GetFileSystem(DatabaseInstance &db) { return db.GetFileSystem(); } @@ -399,7 +407,7 @@ void DatabaseInstance::InitializeInstance(const char *database_path, DBConfig *u // if we are opening an extension database - load the extension auto storage_extension = StorageExtension::Find(config, config.options.database_type); if (!storage_extension) { - ExtensionHelper::LoadExternalExtension(*this, *config.file_system, {config.options.database_type}); + ExtensionHelper::LoadExternalExtension(*this, GetFileSystem(), {config.options.database_type}); } } @@ -473,16 +481,20 @@ FileSystem &DatabaseInstance::GetLocalFileSystem() { return *local_db_file_system; } -static FileSystem &ResolveLocalFileSystem(DatabaseInstance &db) { - return static_cast(*db.config.file_system).GetLocalFileSystem(); +LocalDatabaseFileSystem::LocalDatabaseFileSystem(DatabaseInstance &db_p) + : file_system(VirtualFileSystem::Get(db_p)), database_opener(db_p) { + if (!file_system.GetDefaultFileSystem().IsLocalFileSystem()) { + owned_file_system = make_uniq(); + } } -LocalDatabaseFileSystem::LocalDatabaseFileSystem(DatabaseInstance &db_p) - : db(db_p), local_fs(ResolveLocalFileSystem(db_p)), database_opener(db_p) { +VirtualFileSystem &LocalDatabaseFileSystem::GetFileSystem() const { + return file_system; } -FileSystem &LocalDatabaseFileSystem::GetFileSystem() const { - if (db.config.file_system->SubSystemIsDisabled(local_fs.GetName())) { +optional_ptr LocalDatabaseFileSystem::GetFixedFileSystem() const { + auto &local_fs = owned_file_system ? *owned_file_system : file_system.GetDefaultFileSystem(); + if (file_system.SubSystemIsDisabled(local_fs.GetName())) { throw PermissionException("File system %s has been disabled by configuration", local_fs.GetName()); } return local_fs; diff --git a/src/duckdb/src/main/db_instance_cache.cpp b/src/duckdb/src/main/db_instance_cache.cpp index a2ae4ba5c..3b672ce75 100644 --- a/src/duckdb/src/main/db_instance_cache.cpp +++ b/src/duckdb/src/main/db_instance_cache.cpp @@ -13,7 +13,7 @@ DatabaseCacheEntry::DatabaseCacheEntry(const shared_ptr &insta DatabaseCacheEntry::~DatabaseCacheEntry() { } -static string GetDBAbsolutePath(const string &database_p, FileSystem &fs) { +static string GetDBAbsolutePath(const string &database_p, VirtualFileSystem &fs) { auto database = FileSystem::ExpandPath(database_p, nullptr); if (database.empty()) { return IN_MEMORY_PATH; @@ -27,7 +27,7 @@ static string GetDBAbsolutePath(const string &database_p, FileSystem &fs) { return database; } // canonicalize the path - return fs.CanonicalizePath(database); + return fs.FindFileSystem(database, nullptr).CanonicalizePath(database, nullptr); } static string GetCacheKey(const string &database_p, const DBConfig &config) { diff --git a/src/duckdb/src/main/extension/extension_helper.cpp b/src/duckdb/src/main/extension/extension_helper.cpp index b8afd2273..88d380a8f 100644 --- a/src/duckdb/src/main/extension/extension_helper.cpp +++ b/src/duckdb/src/main/extension/extension_helper.cpp @@ -250,22 +250,23 @@ bool ExtensionHelper::TryAutoLoadAvailableExtension(DatabaseInstance &instance, } } -static ExtensionUpdateResult UpdateExtensionInternal(ClientContext &context, DatabaseInstance &db, FileSystem &fs, - const string &full_extension_path, const string &extension_name, - const string &extension_directory) { - ExtensionUpdateResult result; +//! Checks an installed extension: returns true when it needs a download, which is described in pending +static bool PrepareExtensionUpdateInternal(ClientContext &context, DatabaseInstance &db, FileSystem &fs, + const string &full_extension_path, const string &extension_name, + const string &extension_directory, ExtensionUpdateResult &result, + PendingExtensionUpdate &pending) { result.extension_name = extension_name; if (!fs.FileExists(full_extension_path)) { result.tag = ExtensionUpdateResultTag::NOT_INSTALLED; - return result; + return false; } // Extension exists, check for .info file const string info_file_path = full_extension_path + ".info"; if (!fs.FileExists(info_file_path)) { result.tag = ExtensionUpdateResultTag::MISSING_INSTALL_INFO; - return result; + return false; } // Parse the version of the extension before updating @@ -286,14 +287,14 @@ static ExtensionUpdateResult UpdateExtensionInternal(ClientContext &context, Dat // Early out: no info file found if (extension_install_info->mode == ExtensionInstallMode::UNKNOWN) { result.tag = ExtensionUpdateResultTag::MISSING_INSTALL_INFO; - return result; + return false; } // Early out: we can only update extensions from repositories if (extension_install_info->mode != ExtensionInstallMode::REPOSITORY) { result.tag = ExtensionUpdateResultTag::NOT_A_REPOSITORY; result.installed_version = result.prev_version; - return result; + return false; } // update the extension from the repository it was installed from @@ -315,34 +316,63 @@ static ExtensionUpdateResult UpdateExtensionInternal(ClientContext &context, Dat } catch (std::exception &) { result.tag = ExtensionUpdateResultTag::REPOSITORY_UNREADABLE; result.installed_version = result.prev_version; - return result; + return false; } if (!repository_found) { result.tag = ExtensionUpdateResultTag::REPOSITORY_NOT_FOUND; result.installed_version = result.prev_version; - return result; + return false; } if (!ExtensionRepositoryManager::TrustsRepository(db, user_repository)) { result.tag = ExtensionUpdateResultTag::REPOSITORY_NOT_TRUSTED; result.installed_version = result.prev_version; - return result; + return false; } repository_from_info = user_repository; } + pending.extension_name = extension_name; + pending.use_etags = repository_from_info.path == extension_install_info->repository_url; + pending.repository = std::move(repository_from_info); + pending.extension_directory = extension_directory; + return true; +} + +//! Checks an installed extension, appending its result and - when it needs a download - its pending update +static void PrepareExtensionUpdateEntry(ClientContext &context, DatabaseInstance &db, FileSystem &fs, + const string &full_extension_path, const string &extension_name, + const string &extension_directory, vector &results, + vector &pending) { + ExtensionUpdateResult result; + PendingExtensionUpdate pending_update; + auto needs_download = PrepareExtensionUpdateInternal(context, db, fs, full_extension_path, extension_name, + extension_directory, result, pending_update); + if (needs_download) { + pending_update.result_index = results.size(); + pending.push_back(std::move(pending_update)); + } + results.push_back(std::move(result)); +} + +void ExtensionHelper::ExecuteExtensionUpdate(ClientContext &context, const PendingExtensionUpdate &pending, + ExtensionUpdateResult &result) { // Force install from the repository + auto repository = pending.repository; ExtensionInstallOptions options; - options.repository = repository_from_info; + options.repository = repository; options.force_install = true; - options.use_etags = repository_from_info.path == extension_install_info->repository_url; - options.extension_directory = extension_directory; + options.use_etags = pending.use_etags; + options.extension_directory = pending.extension_directory; unique_ptr install_result; try { - install_result = ExtensionHelper::InstallExtension(context, extension_name, options); + install_result = ExtensionHelper::InstallExtension(context, pending.extension_name, options); } catch (std::exception &e) { ErrorData error(e); - error.Throw("Extension updating failed when trying to install '" + extension_name + "', original error: "); + result.tag = ExtensionUpdateResultTag::UPDATE_FAILED; + result.installed_version = result.prev_version; + result.error = error.Message(); + return; } result.installed_version = install_result->version; @@ -354,19 +384,14 @@ static ExtensionUpdateResult UpdateExtensionInternal(ClientContext &context, Dat } else { result.tag = ExtensionUpdateResultTag::NO_UPDATE_AVAILABLE; } - - return result; } -vector ExtensionHelper::UpdateExtensions(ClientContext &context) { +void ExtensionHelper::PrepareExtensionUpdates(ClientContext &context, vector &results, + vector &pending) { +#ifndef WASM_LOADABLE_EXTENSIONS auto &fs = FileSystem::GetFileSystem(context); - - vector result; DatabaseInstance &db = DatabaseInstance::GetDatabase(context); -#ifndef WASM_LOADABLE_EXTENSIONS - identifier_set_t seen_extensions; - // scan the install directories for installed extensions, each is updated in the directory it was found in for (auto &ext_directory : ExtensionHelper::GetInstalledExtensionDirectories(db, fs)) { fs.ListFiles(ext_directory.path, [&](const string &path, bool is_directory) { @@ -377,33 +402,54 @@ vector ExtensionHelper::UpdateExtensions(ClientContext &c auto extension_file_name = StringUtil::GetFileName(path); auto extension_name = StringUtil::Split(extension_file_name, ".")[0]; - seen_extensions.insert(Identifier(extension_name)); - - result.push_back(UpdateExtensionInternal(context, db, fs, fs.JoinPath(ext_directory.path, path), - extension_name, ext_directory.extension_directory)); + PrepareExtensionUpdateEntry(context, db, fs, fs.JoinPath(ext_directory.path, path), extension_name, + ext_directory.extension_directory, results, pending); }); } #endif - - return result; } -ExtensionUpdateResult ExtensionHelper::UpdateExtension(ClientContext &context, const string &extension_name) { +void ExtensionHelper::PrepareExtensionUpdate(ClientContext &context, const string &extension_name, + vector &results, + vector &pending) { auto &fs = FileSystem::GetFileSystem(context); DatabaseInstance &db = DatabaseInstance::GetDatabase(context); auto ext_directory = ExtensionHelper::ExtensionDirectory(db, fs); auto full_extension_path = fs.JoinPath(ext_directory, extension_name + ".duckdb_extension"); - auto update_result = UpdateExtensionInternal(context, db, fs, full_extension_path, extension_name, ext_directory); + PrepareExtensionUpdateEntry(context, db, fs, full_extension_path, extension_name, ext_directory, results, pending); - if (update_result.tag == ExtensionUpdateResultTag::NOT_INSTALLED) { + auto &result = results.back(); + if (result.tag == ExtensionUpdateResultTag::NOT_INSTALLED) { throw InvalidInputException("Failed to update the extension '%s', the extension is not installed!", extension_name); - } else if (update_result.tag == ExtensionUpdateResultTag::UNKNOWN) { - throw InternalException("Failed to update extension '%s', an unknown error occurred", extension_name); } - return update_result; +} + +//! Runs the pending updates one after the other +static vector ExecuteExtensionUpdates(ClientContext &context, + vector results, + const vector &pending) { + for (auto &pending_update : pending) { + ExtensionHelper::ExecuteExtensionUpdate(context, pending_update, results[pending_update.result_index]); + } + return results; +} + +vector ExtensionHelper::UpdateExtensions(ClientContext &context) { + vector results; + vector pending; + PrepareExtensionUpdates(context, results, pending); + return ExecuteExtensionUpdates(context, std::move(results), pending); +} + +ExtensionUpdateResult ExtensionHelper::UpdateExtension(ClientContext &context, const string &extension_name) { + vector results; + vector pending; + PrepareExtensionUpdate(context, extension_name, results, pending); + results = ExecuteExtensionUpdates(context, std::move(results), pending); + return std::move(results[0]); } void ExtensionHelper::AutoLoadExtension(ClientContext &context, const string &extension_name) { diff --git a/src/duckdb/src/main/extension/extension_install_dynamic.cpp b/src/duckdb/src/main/extension/extension_install_dynamic.cpp index f675ee67b..339b3c3ca 100644 --- a/src/duckdb/src/main/extension/extension_install_dynamic.cpp +++ b/src/duckdb/src/main/extension/extension_install_dynamic.cpp @@ -274,7 +274,7 @@ InstallFromHttpUrl(DatabaseInstance &db, const string &url, const string &extens HTTPHeaders headers(db); if (options.use_etags && install_info && !install_info->etag.empty()) { - headers.Insert("If-None-Match", StringUtil::Format("%s", install_info->etag)); + headers.InsertIfAbsent("If-None-Match", StringUtil::Format("%s", install_info->etag)); } string download_url = url; diff --git a/src/duckdb/src/main/extension/extension_repository_manager.cpp b/src/duckdb/src/main/extension/extension_repository_manager.cpp index e88a2bf19..477e8a622 100644 --- a/src/duckdb/src/main/extension/extension_repository_manager.cpp +++ b/src/duckdb/src/main/extension/extension_repository_manager.cpp @@ -552,22 +552,45 @@ static yyjson_val *ReadVersionedObject(RepositoryJSONDocument &document, const s return root; } -ExtensionRepositoryResolution ExtensionRepositoryManager::ResolveRepositoryFromHost(DatabaseInstance &db, - optional_ptr context, - const string &name_p) { - // called by CreateRepository once the access check and the conflict check have passed +//! How a failed resolution opens, naming what cannot be done: the statement creates a repository, the +//! extension_repository_url function only looks one up +static string ResolutionFailure(ExtensionRepositoryHostCaller caller, const string &name) { + if (caller == ExtensionRepositoryHostCaller::CREATE_STATEMENT) { + return StringUtil::Format("Cannot create extension repository '%s'", name); + } + return StringUtil::Format("Cannot resolve the extension repository of host '%s'", name); +} + +//! What else the user can do, for the caller that has an alternative: the statement can name the location itself +static string ResolutionHint(ExtensionRepositoryHostCaller caller, const char *hint) { + if (caller == ExtensionRepositoryHostCaller::CREATE_STATEMENT) { + return hint; + } + return string(); +} + +ExtensionRepositoryResolution +ExtensionRepositoryManager::ResolveRepositoryFromHost(DatabaseInstance &db, optional_ptr context, + const string &name_p, ExtensionRepositoryHostCaller caller) { + // called by CreateRepository once the access check and the conflict check have passed, and by + // extension_repository_url, which reads the same public file without creating or trusting anything auto name = NormalizeRepositoryName(name_p); // only a name that is a host on the public internet is reached: a single word would resolve through search // domains to a host the user did not name, an IP literal or localhost is nobody's statement if (!IsHostName(name)) { - throw InvalidInputException("Cannot create extension repository '%s': '%s' is not a host name. A host has two " - "or more labels separated by " - "dots, each label words of letters and digits joined by single dashes (or a " - "punycode label, 'xn--...'), the " - "last label letters only, and is not localhost\nUse `WITH PREFIX ''` to name " - "the repository's location " - "directly", - name_p, name); + throw InvalidInputException( + "%s: '%s' is not a host name. A host has two or more labels separated by " + "dots, each label words of letters and digits joined by single dashes (or a " + "punycode label, 'xn--...'), the last label letters only, and is not localhost%s", + ResolutionFailure(caller, name_p), name, + ResolutionHint(caller, "\nUse `WITH PREFIX ''` to name the repository's location directly")); + } + // reading the host is an external access: refused up front, as LOAD refuses, rather than as a read error from + // the file system once the request is attempted + if (!Settings::Get(db)) { + throw PermissionException("%s: reading the host's metadata file is an external access, which is disabled " + "through configuration (enable_external_access)", + ResolutionFailure(caller, name)); } ExtensionRepositoryResolution resolution; resolution.host = name; @@ -587,11 +610,11 @@ ExtensionRepositoryResolution ExtensionRepositoryManager::ResolveRepositoryFromH // the inner message already names the file and the reason ("Failed to read the host's metadata file '': // HTTP 404 Not Found"); say what it means for the statement, and what else can be done ErrorData error(ex); - throw IOException( - "Cannot create extension repository '%s': %s\nA repository is resolved from its host through " - "https:///.well-known/duckdb-extension-repo.json; use `WITH PREFIX ''` to name the " - "repository's location directly", - name, error.RawMessage()); + throw IOException("%s: %s\nA repository is resolved from its host through " + "https:///.well-known/duckdb-extension-repo.json%s", + ResolutionFailure(caller, name), error.RawMessage(), + ResolutionHint(caller, "; use `WITH PREFIX ''` to name the repository's " + "location directly")); } RepositoryJSONDocument document(yyjson_read(contents.c_str(), contents.size(), 0)); auto root = ReadVersionedObject(document, metadata_path); @@ -605,10 +628,10 @@ ExtensionRepositoryResolution ExtensionRepositoryManager::ResolveRepositoryFromH StringUtil::RTrim(resolution.url, "/"); // the keys are fetched from the prefix next: over anything but https they could be anyone's if (!StringUtil::StartsWith(resolution.url, "https://")) { - throw InvalidInputException("Cannot create extension repository '%s': the host names the repository at '%s', " + throw InvalidInputException("%s: the host names the repository at '%s', " "but a repository resolved from its host must be served over https, so that its " "signing keys are fetched from where the host says they are", - name, resolution.url); + ResolutionFailure(caller, name), resolution.url); } return resolution; } diff --git a/src/duckdb/src/main/http/http_client_httplib.cpp b/src/duckdb/src/main/http/http_client_httplib.cpp index c33a66018..fe70bfb7f 100644 --- a/src/duckdb/src/main/http/http_client_httplib.cpp +++ b/src/duckdb/src/main/http/http_client_httplib.cpp @@ -46,7 +46,7 @@ class HTTPLibClient : public HTTPClient { } } unique_ptr Get(GetRequestInfo &info) override { - auto headers = TransformHeaders(info.headers, info.params); + duckdb_httplib::Headers headers(info.headers.begin(), info.headers.end()); if (!info.response_handler && !info.content_handler) { return TransformResult(client->Get(info.path, headers)); } else { @@ -84,14 +84,6 @@ class HTTPLibClient : public HTTPClient { unique_ptr client; private: - duckdb_httplib::Headers TransformHeaders(const HTTPHeaders &header_map, const HTTPParams ¶ms) { - duckdb_httplib::Headers headers; - for (auto &entry : header_map) { - headers.insert(entry); - } - return headers; - } - unique_ptr TransformResponse(const duckdb_httplib::Response &response) { auto status_code = HTTPUtil::ToStatusCode(response.status); auto result = make_uniq(status_code); diff --git a/src/duckdb/src/main/http/http_util.cpp b/src/duckdb/src/main/http/http_util.cpp index 901fcc114..90c4c8ae1 100644 --- a/src/duckdb/src/main/http/http_util.cpp +++ b/src/duckdb/src/main/http/http_util.cpp @@ -39,47 +39,56 @@ void HTTPParams::RequireServerCertificateVerification() { } HTTPHeaders::HTTPHeaders(DatabaseInstance &db) { - headers.insert({"User-Agent", StringUtil::Format("%s %s", db.config.UserAgent(), DuckDB::SourceID())}); + Append("User-Agent", StringUtil::Format("%s %s", db.config.UserAgent(), DuckDB::SourceID())); } HTTPHeaders::~HTTPHeaders() = default; void HTTPHeaders::Insert(string key, string value) { - headers.insert(make_pair(std::move(key), std::move(value))); + InsertIfAbsent(std::move(key), std::move(value)); } -void HTTPHeaders::Append(string key, string value) { - auto entry = headers.find(key); - if (entry == headers.end()) { - headers.insert(make_pair(std::move(key), std::move(value))); - return; - } - auto repeated_entry = repeated_headers.find(key); - if (repeated_entry == repeated_headers.end()) { - repeated_headers.insert(make_pair(std::move(key), header_values_t {entry->second, std::move(value)})); - } else { - repeated_entry->second.push_back(std::move(value)); +void HTTPHeaders::InsertIfAbsent(string key, string value) { + if (!HasHeader(key)) { + Append(std::move(key), std::move(value)); } } +void HTTPHeaders::Append(string key, string value) { + headers.emplace(std::move(key), std::move(value)); +} + +void HTTPHeaders::Set(string key, string value) { + RemoveAll(key); + Append(std::move(key), std::move(value)); +} + +void HTTPHeaders::RemoveAll(const string &key) { + headers.erase(key); +} + bool HTTPHeaders::HasHeader(const string &key) const { return headers.find(key) != headers.end(); } string HTTPHeaders::GetHeaderValue(const string &key) const { - auto entry = headers.find(key); - if (entry == headers.end()) { + auto range = headers.equal_range(key); + if (range.first == range.second) { throw InternalException("Header value not found"); } - return entry->second; + return range.first->second; } HTTPHeaders::header_values_t HTTPHeaders::GetHeaderValues(const string &key) const { - auto repeated_entry = repeated_headers.find(key); - if (repeated_entry != repeated_headers.end()) { - return repeated_entry->second; + auto range = headers.equal_range(key); + if (range.first == range.second) { + throw InternalException("Header value not found"); + } + header_values_t values; + for (auto it = range.first; it != range.second; ++it) { + values.push_back(it->second); } - return {GetHeaderValue(key)}; + return values; } HTTPResponse::HTTPResponse(HTTPStatusCode code) : status(code) { @@ -437,7 +446,7 @@ static unique_ptr ResponseFromError(const ErrorData &error) { } else if (entry.first == "reason") { response->reason = entry.second; } else if (StringUtil::StartsWith(entry.first, "header_")) { - response->headers.Insert(entry.first.substr(7), entry.second); + response->headers.InsertIfAbsent(entry.first.substr(7), entry.second); } } return response; diff --git a/src/duckdb/src/main/secret/secret_storage.cpp b/src/duckdb/src/main/secret/secret_storage.cpp index e47c0eee2..7db38640e 100644 --- a/src/duckdb/src/main/secret/secret_storage.cpp +++ b/src/duckdb/src/main/secret/secret_storage.cpp @@ -297,7 +297,7 @@ LocalFileSecretStorage::LocalFileSecretStorage(SecretManager &manager, DatabaseI } } catch (PermissionException &ex) { // If LocalFileSystem is specifically disabled (not all external access), skip loading persistent secrets - if (!DBConfig::GetConfig(db).file_system->SubSystemIsDisabled("LocalFileSystem")) { + if (!VirtualFileSystem::Get(db).SubSystemIsDisabled("LocalFileSystem")) { throw; } } diff --git a/src/duckdb/src/main/settings/custom_settings.cpp b/src/duckdb/src/main/settings/custom_settings.cpp index 517f096d8..8a47eaea1 100644 --- a/src/duckdb/src/main/settings/custom_settings.cpp +++ b/src/duckdb/src/main/settings/custom_settings.cpp @@ -635,7 +635,7 @@ void DisabledCompressionMethodsSetting::OnSet(SettingCallbackInfo &info, Value & //===----------------------------------------------------------------------===// void DisabledFilesystemsSetting::SetGlobal(DatabaseInstance *db_p, DBConfig &config, const Value &input) { auto &db = GetDB(db_p); - auto &fs = FileSystem::GetFileSystem(db); + auto &fs = VirtualFileSystem::Get(db); auto list = StringUtil::Split(input.ToString(), ","); for (auto &entry : list) { StringUtil::Trim(entry); @@ -645,13 +645,11 @@ void DisabledFilesystemsSetting::SetGlobal(DatabaseInstance *db_p, DBConfig &con void DisabledFilesystemsSetting::ResetGlobal(DatabaseInstance *db_p, DBConfig &config) { auto &db = GetDB(db_p); - auto &fs = FileSystem::GetFileSystem(db); - fs.SetDisabledFileSystems(vector()); + VirtualFileSystem::Get(db).SetDisabledFileSystems(vector()); } Value DisabledFilesystemsSetting::GetSetting(const ClientContext &context) { - auto &fs = FileSystem::GetFileSystem(*context.db); - return Value(StringUtil::Join(fs.GetDisabledFileSystems(), ",")); + return Value(StringUtil::Join(VirtualFileSystem::Get(*context.db).GetDisabledFileSystems(), ",")); } //===----------------------------------------------------------------------===// @@ -1154,17 +1152,9 @@ void ForceCompressionSetting::OnSet(SettingCallbackInfo &info, Value &input) { // Home Directory //===----------------------------------------------------------------------===// void HomeDirectorySetting::OnSet(SettingCallbackInfo &info, Value &input) { - optional_ptr fs; - if (info.context) { - fs = FileSystem::GetFileSystem(*info.context); - } else if (info.db) { - fs = FileSystem::GetFileSystem(*info.db); - } else { - fs = info.config.file_system.get(); - } - if (fs && !input.IsNull()) { + if (!input.IsNull()) { auto new_home_directory = input.ToString(); - if (fs->IsRemoteFile(new_home_directory)) { + if (FileSystem::IsRemoteFile(new_home_directory)) { throw InvalidInputException("Cannot set the home directory to a remote path"); } } diff --git a/src/duckdb/src/optimizer/apply_functional_dependencies.cpp b/src/duckdb/src/optimizer/apply_functional_dependencies.cpp index 0f6b65bc0..8994029b3 100644 --- a/src/duckdb/src/optimizer/apply_functional_dependencies.cpp +++ b/src/duckdb/src/optimizer/apply_functional_dependencies.cpp @@ -1,5 +1,6 @@ #include "duckdb/optimizer/apply_functional_dependencies.hpp" +#include "duckdb/function/window_function.hpp" #include "duckdb/planner/column_binding_map.hpp" #include "duckdb/planner/expression/bound_columnref_expression.hpp" #include "duckdb/planner/expression/bound_window_expression.hpp" @@ -140,6 +141,11 @@ void ApplyFunctionalDependencies::VisitWindowExpression(BoundWindowExpression &w if (range_offset(wexpr.WindowStart()) || range_offset(wexpr.WindowEnd())) { return; } + // Some functions read the ORDER BY values, unless they have an argument ordering of their own. + auto &window_function = wexpr.WindowFunction(); + if (window_function && window_function->GetDefinition()->RequiresOrdering() && wexpr.ArgOrders().empty()) { + return; + } if (!partition_bys.empty() && order_bys.size() == 1) { vector> refs; for (auto &arg : partition_bys) { diff --git a/src/duckdb/src/optimizer/duplicate_eliminated_domain_optimizer.cpp b/src/duckdb/src/optimizer/duplicate_eliminated_domain_optimizer.cpp index 751459449..af8e6ebe4 100644 --- a/src/duckdb/src/optimizer/duplicate_eliminated_domain_optimizer.cpp +++ b/src/duckdb/src/optimizer/duplicate_eliminated_domain_optimizer.cpp @@ -1901,7 +1901,7 @@ bool DuplicateEliminatedDomainOptimizer::TryPullUpOuterDomainJoin(unique_ptrRemove(); } diff --git a/src/duckdb/src/optimizer/expression_rewriter.cpp b/src/duckdb/src/optimizer/expression_rewriter.cpp index d343f2504..11fae120b 100644 --- a/src/duckdb/src/optimizer/expression_rewriter.cpp +++ b/src/duckdb/src/optimizer/expression_rewriter.cpp @@ -6,6 +6,7 @@ #include "duckdb/planner/operator/logical_filter.hpp" #include "duckdb/function/scalar/generic_functions.hpp" #include "duckdb/function/scalar/generic_common.hpp" +#include "duckdb/main/client_data.hpp" #include "duckdb/optimizer/rule/contains_to_in_clause.hpp" #include "duckdb/optimizer/rule/distinct_aggregate_optimizer.hpp" #include "duckdb/optimizer/rule/empty_needle_removal.hpp" @@ -19,49 +20,47 @@ namespace duckdb { -const vector> &ExpressionRewriter::GetRules() { - if (!rules.empty()) { - return rules; - } - rules.push_back(make_uniq(*this)); - rules.push_back(make_uniq(*this)); - rules.push_back(make_uniq(*this)); - rules.push_back(make_uniq(*this)); - rules.push_back(make_uniq(*this)); - rules.push_back(make_uniq(*this)); - rules.push_back(make_uniq(*this)); - rules.push_back(make_uniq(*this)); - rules.push_back(make_uniq(*this)); - rules.push_back(make_uniq(*this)); - rules.push_back(make_uniq(*this)); - rules.push_back(make_uniq(*this)); - rules.push_back(make_uniq(*this)); - rules.push_back(make_uniq(*this)); - rules.push_back(make_uniq(*this)); - rules.push_back(make_uniq(*this)); - rules.push_back(make_uniq(*this)); - rules.push_back(make_uniq(*this)); - rules.push_back(make_uniq(*this)); - rules.push_back(make_uniq(*this)); - rules.push_back(make_uniq(*this)); - rules.push_back(make_uniq(*this)); - rules.push_back(make_uniq(*this)); - rules.push_back(make_uniq(*this)); - rules.push_back(make_uniq(*this)); - rules.push_back(make_uniq(*this)); - rules.push_back(make_uniq(*this)); - rules.push_back(make_uniq(*this)); - rules.push_back(make_uniq(*this)); - rules.push_back(make_uniq(*this)); - rules.push_back(make_uniq(*this)); - rules.push_back(make_uniq(*this)); - rules.push_back(make_uniq(*this)); - rules.push_back(make_uniq(*this)); - rules.push_back(make_uniq(*this)); - rules.push_back(make_uniq(*this)); - rules.push_back(make_uniq(*this)); - rules.push_back(make_uniq(*this)); - rules.push_back(make_uniq(*this)); +vector> ExpressionRewriter::CreateDefaultRules(ExpressionRewriter &rewriter) { + vector> rules; + rules.push_back(make_uniq(rewriter)); + rules.push_back(make_uniq(rewriter)); + rules.push_back(make_uniq(rewriter)); + rules.push_back(make_uniq(rewriter)); + rules.push_back(make_uniq(rewriter)); + rules.push_back(make_uniq(rewriter)); + rules.push_back(make_uniq(rewriter)); + rules.push_back(make_uniq(rewriter)); + rules.push_back(make_uniq(rewriter)); + rules.push_back(make_uniq(rewriter)); + rules.push_back(make_uniq(rewriter)); + rules.push_back(make_uniq(rewriter)); + rules.push_back(make_uniq(rewriter)); + rules.push_back(make_uniq(rewriter)); + rules.push_back(make_uniq(rewriter)); + rules.push_back(make_uniq(rewriter)); + rules.push_back(make_uniq(rewriter)); + rules.push_back(make_uniq(rewriter)); + rules.push_back(make_uniq(rewriter)); + rules.push_back(make_uniq(rewriter)); + rules.push_back(make_uniq(rewriter)); + rules.push_back(make_uniq(rewriter)); + rules.push_back(make_uniq(rewriter)); + rules.push_back(make_uniq(rewriter)); + rules.push_back(make_uniq(rewriter)); + rules.push_back(make_uniq(rewriter)); + rules.push_back(make_uniq(rewriter)); + rules.push_back(make_uniq(rewriter)); + rules.push_back(make_uniq(rewriter)); + rules.push_back(make_uniq(rewriter)); + rules.push_back(make_uniq(rewriter)); + rules.push_back(make_uniq(rewriter)); + rules.push_back(make_uniq(rewriter)); + rules.push_back(make_uniq(rewriter)); + rules.push_back(make_uniq(rewriter)); + rules.push_back(make_uniq(rewriter)); + rules.push_back(make_uniq(rewriter)); + rules.push_back(make_uniq(rewriter)); + rules.push_back(make_uniq(rewriter)); #ifdef DEBUG for (auto &rule : rules) { @@ -72,6 +71,19 @@ const vector> &ExpressionRewriter::GetRules() { return rules; } +const vector> &ExpressionRewriter::GetRules() { + if (!rules.empty()) { + return rules; + } + auto &client_data = ClientData::Get(context); + CallOnce(client_data.default_expression_rewriter_once, [&]() { + auto default_rewriter = make_uniq(context); + default_rewriter->rules = CreateDefaultRules(*default_rewriter); + client_data.default_expression_rewriter = std::move(default_rewriter); + }); + return client_data.default_expression_rewriter->rules; +} + void ExpressionRewriter::AddRule(unique_ptr rule) { D_ASSERT(rule->root); rules.push_back(std::move(rule)); @@ -83,18 +95,18 @@ struct RewriteFrame { bool children_visited; }; -static unique_ptr ApplyRule(LogicalOperator &op, const vector> &rules, +static unique_ptr ApplyRule(LogicalOperator &op, const vector> &rules, unique_ptr expr, bool &changes_made, bool is_root) { for (auto &rule : rules) { vector> bindings; - if (rule.get().root->Match(*expr, bindings)) { + if (rule->root->Match(*expr, bindings)) { // the rule matches! try to apply it bool rule_made_change = false; auto alias = expr->GetAlias(); #ifdef D_ASSERT_IS_ENABLED auto return_type = expr->GetReturnType(); #endif - auto result = rule.get().Apply(op, bindings, rule_made_change, is_root); + auto result = rule->Apply(op, bindings, rule_made_change, is_root); if (result) { D_ASSERT(result->GetReturnType() != return_type || result->GetReturnType().EqualsIncludingCollation(return_type)); @@ -120,7 +132,7 @@ static void CollectChildren(Expression &expr, vector &child) { children.push_back(child); }); } -unique_ptr ExpressionRewriter::ApplyRules(LogicalOperator &op, const vector> &rules, +unique_ptr ExpressionRewriter::ApplyRules(LogicalOperator &op, const vector> &rules, unique_ptr expr, bool &changes_made, bool is_root) { vector stack; vector>> children; @@ -175,11 +187,6 @@ void ExpressionRewriter::VisitOperator(LogicalOperator &op) { VisitOperatorChildren(op); this->op = &op; - to_apply_rules.clear(); - for (auto &rule : GetRules()) { - to_apply_rules.push_back(*rule); - } - if (op.type == LogicalOperatorType::LOGICAL_FILTER) { // For FILTER we want to ensure we always visit the split predicates // Rewrites can add more predicates, so we need to loop @@ -198,7 +205,7 @@ void ExpressionRewriter::VisitOperator(LogicalOperator &op) { void ExpressionRewriter::VisitExpression(unique_ptr *expression) { bool changes_made = false; - *expression = ExpressionRewriter::ApplyRules(*op, to_apply_rules, std::move(*expression), changes_made, true); + *expression = ExpressionRewriter::ApplyRules(*op, GetRules(), std::move(*expression), changes_made, true); } ClientContext &Rule::GetContext() const { diff --git a/src/duckdb/src/optimizer/group_by_top_key.cpp b/src/duckdb/src/optimizer/group_by_top_key.cpp new file mode 100644 index 000000000..1c2fc7757 --- /dev/null +++ b/src/duckdb/src/optimizer/group_by_top_key.cpp @@ -0,0 +1,532 @@ +#include "duckdb/optimizer/group_by_top_key.hpp" + +#include "duckdb/optimizer/column_binding_replacer.hpp" +#include "duckdb/optimizer/expression_heuristics.hpp" +#include "duckdb/optimizer/optimizer.hpp" +#include "duckdb/optimizer/topn_optimizer.hpp" +#include "duckdb/planner/binder.hpp" +#include "duckdb/planner/expression/bound_aggregate_expression.hpp" +#include "duckdb/planner/expression/bound_cast_expression.hpp" +#include "duckdb/planner/expression/bound_columnref_expression.hpp" +#include "duckdb/planner/expression/bound_function_expression.hpp" +#include "duckdb/planner/expression_iterator.hpp" +#include "duckdb/planner/operator/logical_aggregate.hpp" +#include "duckdb/planner/operator/logical_limit.hpp" +#include "duckdb/planner/operator/logical_projection.hpp" +#include "duckdb/planner/operator/logical_top_key_filter.hpp" +#include "duckdb/planner/operator/logical_top_n.hpp" + +namespace duckdb { + +namespace { + +//! The largest LIMIT + OFFSET of the rewrite: every thread keeps that many distinct keys +constexpr idx_t MAX_TOP_KEYS = 10000; + +//! The largest cost of a key that is an expression over the group keys (ORDER BY k + 1): the filter evaluates it for +//! every input row, whereas the query evaluates it once per group. A key that is a group key costs nothing extra. +constexpr idx_t MAX_DERIVED_KEY_COST = 50; + +//! The dynamic filter in the scans only pays off if it removes most rows: the limit has to be a small part of the +//! groups. Without it the filter operator sees every row and stops filtering on its own if too many rows pass. +constexpr idx_t MIN_GROUPS_PER_KEY = 8; + +//! Whether the limit is a small part of the estimated number of groups of the aggregate +bool LimitIsSelective(const LogicalAggregate &aggregate, idx_t limit) { + if (!aggregate.has_estimated_cardinality) { + return true; + } + return limit <= aggregate.estimated_cardinality / MIN_GROUPS_PER_KEY; +} + +bool IsInputColumn(const Expression &expr) { + return expr.GetExpressionClass() == ExpressionClass::BOUND_COLUMN_REF && + expr.Cast().Depth() == 0; +} + +//! Whether the expression has the same value whenever it is evaluated on the same input +bool IsDeterministic(const Expression &expr) { + return !expr.IsVolatile() && expr.IsConsistent() && !expr.HasSubquery() && !expr.IsAggregate() && + !expr.IsWindow() && !expr.HasParameter(); +} + +//! Whether the aggregate groups by all of its group keys as one set +bool IsSingleGroupingSet(const LogicalAggregate &aggregate) { + if (aggregate.grouping_sets.empty()) { + return true; + } + return aggregate.grouping_sets.size() == 1 && aggregate.grouping_sets[0].size() == aggregate.groups.size(); +} + +bool IsPlainGroupedAggregate(const LogicalAggregate &aggregate) { + return !aggregate.groups.empty() && IsSingleGroupingSet(aggregate) && aggregate.grouping_functions.empty(); +} + +//! Whether an aggregate function of the aggregate can throw. The groups after the bound lose rows to the filter and +//! are updated, combined and finalized before the Top-N drops them, so sum(DECIMAL(38,0)) overflows on a group whose +//! cancelling rows are gone and histogram(v, bins) takes its bins from a row that was not the first before. The +//! arguments of the aggregates are not checked, they see unchanged input rows, only fewer of them. +bool AggregateFunctionCanThrow(const LogicalAggregate &aggregate) { + for (auto &expr : aggregate.expressions) { + auto &aggr = expr->Cast(); + if (aggr.Function().GetErrorMode() == FunctionErrors::CAN_THROW_RUNTIME_ERROR) { + return true; + } + } + return false; +} + +//! Whether the aggregate evaluates a volatile expression: an aggregate function, one of its arguments, a FILTER or a +//! group expression. The filter below the aggregate evaluates them for fewer rows, which a side effect (a sequence) +//! would show. +bool AggregateIsVolatile(const LogicalAggregate &aggregate) { + for (auto &expr : aggregate.expressions) { + if (expr->IsVolatile()) { + return true; + } + } + for (auto &group : aggregate.groups) { + if (group->IsVolatile()) { + return true; + } + } + return false; +} + +//! Whether the filter can compare keys of this type. It keeps the distinct keys of a thread as sort keys and compares +//! rows with the bound that it decodes from one, so (1) values that the aggregate puts into one group need the same +//! sort key, and (2) the order of the sort keys has to be the order of the comparison operators. Both hold for the +//! types below. FLOAT and DOUBLE are among them (-0.0 and 0.0, and all NaNs, have one sort key each), but they are not +//! "exact": values that are equal can still be told apart by an expression (1 / -0.0 is not 1 / 0.0). INTERVAL is not +//! supported: equal values (1 month and 30 days) have different sort keys. Types that are not listed are declined. +bool IsSupportedKeyType(const LogicalType &type, bool exact) { + switch (type.id()) { + case LogicalTypeId::BOOLEAN: + case LogicalTypeId::TINYINT: + case LogicalTypeId::SMALLINT: + case LogicalTypeId::INTEGER: + case LogicalTypeId::BIGINT: + case LogicalTypeId::UTINYINT: + case LogicalTypeId::USMALLINT: + case LogicalTypeId::UINTEGER: + case LogicalTypeId::UBIGINT: + case LogicalTypeId::HUGEINT: + case LogicalTypeId::UHUGEINT: + case LogicalTypeId::DECIMAL: + case LogicalTypeId::DATE: + case LogicalTypeId::TIME: + case LogicalTypeId::TIMESTAMP_SEC: + case LogicalTypeId::TIMESTAMP_MS: + case LogicalTypeId::TIMESTAMP: + case LogicalTypeId::TIMESTAMP_NS: + case LogicalTypeId::TIMESTAMP_TZ: + case LogicalTypeId::VARCHAR: + case LogicalTypeId::BLOB: + case LogicalTypeId::UUID: + case LogicalTypeId::ENUM: + return true; + case LogicalTypeId::FLOAT: + case LogicalTypeId::DOUBLE: + return !exact; + case LogicalTypeId::STRUCT: + for (auto &child : StructType::GetChildTypes(type)) { + if (!IsSupportedKeyType(child.second, exact)) { + return false; + } + } + return true; + case LogicalTypeId::LIST: + return IsSupportedKeyType(ListType::GetChildType(type), exact); + case LogicalTypeId::ARRAY: + return IsSupportedKeyType(ArrayType::GetChildType(type), exact); + default: + return false; + } +} + +//! The column that a projection expression forwards in a way that preserves its order: the column itself, an integral +//! cast of it or the decompression of a compressed materialization (which preserves the order) +bool TryGetForwardedColumn(const Expression &expr, ColumnBinding &result) { + if (IsInputColumn(expr)) { + result = expr.Cast().Binding(); + return true; + } + if (expr.GetExpressionClass() != ExpressionClass::BOUND_FUNCTION) { + return false; + } + auto &function = expr.Cast(); + if (BoundCastExpression::IsCast(expr)) { + if (BoundCastExpression::IsTryCast(function) || !BoundCastExpression::SourceType(function).IsIntegral() || + !BoundCastExpression::TargetType(function).IsIntegral()) { + return false; + } + } else if (!StringUtil::StartsWith(function.Function().GetName().GetIdentifierName(), "__internal_decompress_")) { + return false; + } + if (function.GetChildren().empty() || !IsInputColumn(*function.GetChildren()[0])) { + return false; + } + result = function.GetChildren()[0]->Cast().Binding(); + return true; +} + +//! The group key that the binding - an output column of the aggregate - is, as an expression over the input of the +//! aggregate +unique_ptr GetGroupKey(const LogicalAggregate &aggregate, const ColumnBinding &binding) { + if (binding.table_index != aggregate.group_index || binding.column_index.GetIndex() >= aggregate.groups.size()) { + return nullptr; + } + auto &group = *aggregate.groups[binding.column_index.GetIndex()]; + if (!IsInputColumn(group) && !IsDeterministic(group)) { + return nullptr; + } + return group.Copy(); +} + +//! The group key that the binding - an output column of projections[level] - forwards through order-preserving +//! projection expressions only +unique_ptr ResolveColumn(ColumnBinding binding, idx_t level, + const vector> &projections, + const LogicalAggregate &aggregate) { + for (idx_t i = level; i < projections.size(); i++) { + auto &projection = projections[i].get().Cast(); + if (binding.table_index != projection.table_index || + binding.column_index.GetIndex() >= projection.expressions.size()) { + return nullptr; + } + if (!TryGetForwardedColumn(*projection.expressions[binding.column_index.GetIndex()], binding)) { + return nullptr; + } + } + return GetGroupKey(aggregate, binding); +} + +//! The expression - over the output of projections[level] - as an expression over the input of the aggregate: a column +//! is replaced by the deterministic projection expression that computes it and, at the aggregate, by its group key. +//! exact_group_keys is cleared if a group key that the expression reads has a type whose equal values can differ. +unique_ptr Substitute(const Expression &expr, idx_t level, + const vector> &projections, + const LogicalAggregate &aggregate, bool &exact_group_keys) { + if (expr.GetExpressionClass() == ExpressionClass::BOUND_COLUMN_REF) { + auto &colref = expr.Cast(); + if (colref.Depth() != 0) { + return nullptr; + } + auto &binding = colref.Binding(); + if (level >= projections.size()) { + auto key = GetGroupKey(aggregate, binding); + if (key && !IsSupportedKeyType(key->GetReturnType(), true)) { + exact_group_keys = false; + } + return key; + } + auto &projection = projections[level].get().Cast(); + if (binding.table_index != projection.table_index || + binding.column_index.GetIndex() >= projection.expressions.size()) { + return nullptr; + } + auto &computed = *projection.expressions[binding.column_index.GetIndex()]; + if (!IsDeterministic(computed)) { + return nullptr; + } + return Substitute(computed, level + 1, projections, aggregate, exact_group_keys); + } + if (!IsDeterministic(expr)) { + return nullptr; + } + auto result = expr.Copy(); + bool resolved = true; + ExpressionIterator::EnumerateChildren(*result, [&](unique_ptr &child) { + if (!resolved) { + return; + } + auto key = Substitute(*child, level, projections, aggregate, exact_group_keys); + if (!key) { + resolved = false; + return; + } + child = std::move(key); + }); + return resolved ? std::move(result) : nullptr; +} + +} // namespace + +GroupByTopKey::GroupByTopKey(Optimizer &optimizer) : optimizer(optimizer) { +} + +//===--------------------------------------------------------------------===// +// LIMIT over a grouped aggregate +//===--------------------------------------------------------------------===// +unique_ptr GroupByTopKey::LimitToTopN(unique_ptr op) { + auto &limit = op->Cast(); + if (limit.limit_val.Type() != LimitNodeType::CONSTANT_VALUE) { + return op; + } + idx_t offset_value = 0; + if (limit.offset_val.Type() == LimitNodeType::CONSTANT_VALUE) { + offset_value = limit.offset_val.GetConstantValue(); + } else if (limit.offset_val.Type() != LimitNodeType::UNSET) { + return op; + } + const auto limit_value = limit.limit_val.GetConstantValue(); + if (limit_value == 0 || limit_value > MAX_TOP_KEYS || offset_value > MAX_TOP_KEYS - limit_value) { + return op; + } + // the projections down to the aggregate: a filter (HAVING) or anything else ends the match + // The projections move above the Top-N, where they only see the rows that are returned: an expression that is + // volatile (a sequence has to advance for the rows that the OFFSET skips, as in the limit pushdown) or that can + // throw has to stay below the LIMIT. + reference child = *op->children[0]; + while (child.get().type == LogicalOperatorType::LOGICAL_PROJECTION) { + for (auto &expr : child.get().expressions) { + if (expr->IsVolatile() || expr->CanThrow()) { + return op; + } + } + child = *child.get().children[0]; + } + if (child.get().type != LogicalOperatorType::LOGICAL_AGGREGATE_AND_GROUP_BY) { + return op; + } + auto &aggregate = child.get().Cast(); + // an aggregate without aggregate functions is a DISTINCT: the LIMIT stops it early + if (!IsPlainGroupedAggregate(aggregate) || aggregate.expressions.empty() || + aggregate.children[0]->type == LogicalOperatorType::LOGICAL_TOP_KEY_FILTER || + AggregateFunctionCanThrow(aggregate) || AggregateIsVolatile(aggregate)) { + return op; + } + // order by the first group key that is a column, preferring one that the scans can filter on + optional_idx key_idx; + for (idx_t group_idx = 0; group_idx < aggregate.groups.size(); group_idx++) { + auto &group = *aggregate.groups[group_idx]; + if (!IsInputColumn(group)) { + continue; + } + auto &type = group.GetReturnType(); + if (!IsSupportedKeyType(type, false)) { + continue; + } + if (TypeIsNumeric(type.InternalType()) || type.id() == LogicalTypeId::VARCHAR) { + key_idx = group_idx; + break; + } + if (!key_idx.IsValid()) { + key_idx = group_idx; + } + } + if (!key_idx.IsValid()) { + return op; + } + if (offset_value > 0) { + // the query does not order the groups that its OFFSET skips, and the row order of a grouped aggregate is never + // guaranteed: the LIMIT warns about that when it is planned, so the Top-N that replaces it has to as well + LogicalLimit::WarnUnorderedOffset(optimizer.context); + } + + // detach the projections and the aggregate + vector> projections; + auto node = std::move(op->children[0]); + while (node->type == LogicalOperatorType::LOGICAL_PROJECTION) { + auto next = std::move(node->children[0]); + projections.push_back(std::move(node)); + node = std::move(next); + } + vector orders; + orders.emplace_back( + OrderType::ASCENDING, OrderByNullType::NULLS_LAST, + make_uniq(aggregate.groups[key_idx.GetIndex()]->GetReturnType(), + ColumnBinding(aggregate.group_index, ProjectionIndex(key_idx.GetIndex())))); + auto topn = make_uniq(std::move(orders), limit_value, offset_value); + topn->unpruned_offset = limit.unpruned_offset; + auto cardinality = limit_value; + if (node->has_estimated_cardinality && node->estimated_cardinality < limit_value) { + cardinality = node->estimated_cardinality; + } + topn->AddChild(std::move(node)); + topn->SetEstimatedCardinality(cardinality); + unique_ptr result = std::move(topn); + // the projections are one row in, one row out: they move above the Top-N + while (!projections.empty()) { + auto projection = std::move(projections.back()); + projections.pop_back(); + projection->children[0] = std::move(result); + result = std::move(projection); + } + return result; +} + +//===--------------------------------------------------------------------===// +// Top-N over a grouped aggregate +//===--------------------------------------------------------------------===// +bool GroupByTopKey::TryMatch(LogicalOperator &op, TopKeyMatch &match) { + auto &topn = op.Cast(); + if (topn.orders.empty() || topn.limit == 0 || topn.limit > MAX_TOP_KEYS || + topn.offset > MAX_TOP_KEYS - topn.limit) { + return false; + } + match.limit = topn.limit + topn.offset; + // the projections down to the aggregate: a filter (HAVING) or anything else ends the match + vector> projections; + reference child = *op.children[0]; + while (child.get().type == LogicalOperatorType::LOGICAL_PROJECTION) { + projections.push_back(child); + child = *child.get().children[0]; + } + if (child.get().type != LogicalOperatorType::LOGICAL_AGGREGATE_AND_GROUP_BY) { + return false; + } + auto &aggregate = child.get().Cast(); + if (!IsPlainGroupedAggregate(aggregate) || + aggregate.children[0]->type == LogicalOperatorType::LOGICAL_TOP_KEY_FILTER || + AggregateFunctionCanThrow(aggregate) || AggregateIsVolatile(aggregate)) { + return false; + } + // the groups after the bound are incomplete until the Top-N drops them, and the projections and the ORDER BY are + // evaluated on them first: an expression that can throw (sum(v)::TINYINT) must not see their partial aggregates + for (auto &projection : projections) { + for (auto &expr : projection.get().expressions) { + if (expr->CanThrow()) { + return false; + } + } + } + for (auto &order : topn.orders) { + if (order.expression->CanThrow()) { + return false; + } + } + // the longest prefix of the ORDER BY that consists of keys over the group keys + for (auto &order : topn.orders) { + unique_ptr key; + if (IsInputColumn(*order.expression)) { + // forwarded by order-preserving projections only: the group key itself, in the order of the Top-N + key = + ResolveColumn(order.expression->Cast().Binding(), 0, projections, aggregate); + } + bool exact_group_keys = true; + if (!key) { + key = Substitute(*order.expression, 0, projections, aggregate, exact_group_keys); + } + if (!key || !IsSupportedKeyType(key->GetReturnType(), false)) { + break; + } + bool is_group_key = false; + for (auto &group : aggregate.groups) { + is_group_key = is_group_key || group->Equals(*key); + } + if (!is_group_key) { + // an expression over the group keys. The filter evaluates it for every input row and the Top-N for one + // row of the group, so it has to have one value for all rows of a group: the group keys it reads must not + // have equal values that an expression can tell apart. It also must not throw (the filter and the dynamic + // filter in the scans change the rows that it is evaluated for), and it has to be cheap. + if (!exact_group_keys || key->CanThrow() || ExpressionHeuristics::Cost(*key) > MAX_DERIVED_KEY_COST) { + break; + } + } + const auto order_type = order.type == OrderType::DESCENDING ? OrderType::DESCENDING : OrderType::ASCENDING; + const auto null_order = order.null_order == OrderByNullType::NULLS_FIRST ? OrderByNullType::NULLS_FIRST + : OrderByNullType::NULLS_LAST; + match.prefix.emplace_back(order_type, null_order, std::move(key)); + } + match.depth = projections.size(); + return !match.prefix.empty(); +} + +unique_ptr GroupByTopKey::MaterializeKeys(LogicalAggregate &aggregate, + unique_ptr input, + vector &keys) { + const auto projection_index = optimizer.binder.GenerateTableIndex(); + input->ResolveOperatorTypes(); + const auto input_bindings = input->GetColumnBindings(); + D_ASSERT(input_bindings.size() == input->types.size()); + // forward every column of the input + vector> expressions; + ColumnBindingReplacer replacer; + for (idx_t i = 0; i < input_bindings.size(); i++) { + expressions.push_back(make_uniq(input->types[i], input_bindings[i])); + replacer.replacement_bindings.emplace_back(input_bindings[i], + ColumnBinding(projection_index, ProjectionIndex(i))); + } + // append the keys that are expressions + for (auto &key : keys) { + if (IsInputColumn(*key.expression)) { + replacer.VisitExpression(&key.expression); + continue; + } + ColumnBinding key_binding(projection_index, ProjectionIndex(expressions.size())); + auto key_ref = make_uniq(key.expression->GetReturnType(), key_binding); + // a group key that is the same expression reads the column instead of computing it a second time + for (auto &group : aggregate.groups) { + if (group->Equals(*key.expression)) { + group = key_ref->Copy(); + } + } + expressions.push_back(std::move(key.expression)); + key.expression = std::move(key_ref); + } + // the aggregate reads the columns of the projection + replacer.VisitOperatorBindings(aggregate); + auto projection = make_uniq(projection_index, std::move(expressions)); + if (input->has_estimated_cardinality) { + projection->SetEstimatedCardinality(input->estimated_cardinality); + } + projection->children.push_back(std::move(input)); + projection->ResolveOperatorTypes(); + return std::move(projection); +} + +void GroupByTopKey::Rewrite(LogicalAggregate &aggregate, TopKeyMatch &match) { + auto input = std::move(aggregate.children[0]); + bool needs_projection = false; + for (auto &key : match.prefix) { + needs_projection = needs_projection || !IsInputColumn(*key.expression); + } + if (needs_projection) { + input = MaterializeKeys(aggregate, std::move(input), match.prefix); + } + input->ResolveOperatorTypes(); + + auto filter = make_uniq(std::move(match.prefix), match.limit); + if (input->has_estimated_cardinality) { + filter->SetEstimatedCardinality(input->estimated_cardinality); + } + filter->children.push_back(std::move(input)); + filter->ResolveOperatorTypes(); + + // the dynamic filter on the first key: for the types that the Top-N supports + auto &first = filter->orders[0]; + auto &type = first.expression->GetReturnType(); + if (LimitIsSelective(aggregate, filter->limit) && + (TypeIsNumeric(type.InternalType()) || type.id() == LogicalTypeId::VARCHAR)) { + // the bound is the n-th key itself and the rows of its group pass: always <= (>= if descending) + const auto comparison_type = first.type == OrderType::ASCENDING ? ExpressionType::COMPARE_LESSTHANOREQUALTO + : ExpressionType::COMPARE_GREATERTHANOREQUALTO; + filter->dynamic_filter = TopN::PushDynamicFilterIntoScans( + optimizer.context, *filter->children[0], first.expression->Cast().Binding(), type, + first.null_order == OrderByNullType::NULLS_FIRST, comparison_type); + } + aggregate.children[0] = std::move(filter); +} + +unique_ptr GroupByTopKey::Optimize(unique_ptr op) { + if (op->type == LogicalOperatorType::LOGICAL_LIMIT) { + op = LimitToTopN(std::move(op)); + } + if (op->type == LogicalOperatorType::LOGICAL_TOP_N) { + TopKeyMatch match; + if (TryMatch(*op, match)) { + reference aggregate = *op->children[0]; + for (idx_t i = 0; i < match.depth; i++) { + aggregate = *aggregate.get().children[0]; + } + Rewrite(aggregate.get().Cast(), match); + } + } + for (auto &child : op->children) { + child = Optimize(std::move(child)); + } + return op; +} + +} // namespace duckdb diff --git a/src/duckdb/src/optimizer/join_order/cardinality_estimator.cpp b/src/duckdb/src/optimizer/join_order/cardinality_estimator.cpp index 2c0a0ef4f..2a1f50011 100644 --- a/src/duckdb/src/optimizer/join_order/cardinality_estimator.cpp +++ b/src/duckdb/src/optimizer/join_order/cardinality_estimator.cpp @@ -202,8 +202,14 @@ struct LogicalJoinStats { }; struct CardinalityEstimatorState { + void InitializeEdgeIndex(); + bool TryGetCandidateEdges(const JoinRelationSet &set, vector &candidates) const; + vector relation_set_stats; vector edges; + //! Each edge is indexed by one of the relations required by its filter. + vector> edges_by_relation; + vector unscoped_edges; vector leaf_cardinalities; //! Per relation, the columns that together identify a row (empty if unknown). vector> unique_keys; @@ -250,6 +256,45 @@ JoinPredicate &FilterInfoWithTotalDomains::GetPredicate() const { return predicate.get(); } +void CardinalityEstimatorState::InitializeEdgeIndex() { + edges_by_relation.resize(leaf_cardinalities.size()); + for (idx_t i = 0; i < edges.size(); i++) { + auto &scope = edges[i].GetFilter().set.get(); + if (scope.Empty()) { + unscoped_edges.push_back(i); + continue; + } + auto anchor = scope.relations[0].index; + for (idx_t j = 1; j < scope.count; j++) { + auto relation = scope.relations[j].index; + if (edges_by_relation[relation].size() < edges_by_relation[anchor].size()) { + anchor = relation; + } + } + edges_by_relation[anchor].push_back(i); + } +} + +bool CardinalityEstimatorState::TryGetCandidateEdges(const JoinRelationSet &set, vector &candidates) const { + idx_t count = unscoped_edges.size(); + for (idx_t i = 0; i < set.count; i++) { + count += edges_by_relation[set.relations[i].index].size(); + } + // Collecting and sorting most edges costs more than scanning them in place. + if (count >= edges.size() / 2) { + return false; + } + candidates.reserve(count); + candidates.insert(candidates.end(), unscoped_edges.begin(), unscoped_edges.end()); + for (idx_t i = 0; i < set.count; i++) { + auto &entries = edges_by_relation[set.relations[i].index]; + candidates.insert(candidates.end(), entries.begin(), entries.end()); + } + // Each edge occurs once. Restore the estimator's order before applying any selectivity. + std::sort(candidates.begin(), candidates.end()); + return true; +} + // The filter was made on top of a logical sample or other projection, // but no specific columns are referenced. See issue 4978 number 4. bool CardinalityEstimator::EmptyFilter(const FilterInfo &filter_info) { @@ -600,6 +645,9 @@ bool CardinalityEstimator::ApplyCompositeJoinPairCaps( CardinalityValue &target_selectivity, JoinRelationSet &scope, reference_map_t &join_pair_stats, reference_set_t &capped_join_pairs) { + if (capped_join_pairs.size() == join_pair_stats.size()) { + return false; + } bool applied = false; for (auto &entry : join_pair_stats) { auto &join_pair = entry.first.get(); @@ -791,12 +839,22 @@ void CardinalityEstimator::MergeDisconnectedSelectivitySubgraphs(SelectivityStat CardinalityValue CardinalityEstimator::GetSelectivity(JoinRelationSet &set) { SelectivityState selectivity_state; - for (auto &edge : state->edges) { + auto process_edge = [&](FilterInfoWithTotalDomains &edge) { auto &filter = edge.GetFilter(); if (edge.GetPredicate().GetJoinType() == JoinType::INNER && filter.left_set != filter.right_set && IsFilterApplicable(filter, set) && !IsResidualFilter(filter)) { ProcessSelectivityEdge(edge, set, selectivity_state); } + }; + vector candidates; + if (state->TryGetCandidateEdges(set, candidates)) { + for (auto index : candidates) { + process_edge(state->edges[index]); + } + } else { + for (auto &edge : state->edges) { + process_edge(edge); + } } MergeDisconnectedSelectivitySubgraphs(selectivity_state); auto result = @@ -871,6 +929,8 @@ CardinalityValue CardinalityEstimator::EstimateCardinality(JoinRelationSet &set) auto right_rows = EstimateCardinality(right); if (op.type == JoinOrderOperatorType::LEFT) { result = MaxValue(left_rows, left_rows * right_rows * boundary->selectivity); + } else if (op.type == JoinOrderOperatorType::MARK) { + result = left_rows; } else { auto type = op.type == JoinOrderOperatorType::SEMI ? JoinType::SEMI : JoinType::ANTI; result = RelationStatisticsHelper::EstimateSemiAntiJoinFallbackCardinality( @@ -975,6 +1035,20 @@ void CardinalityEstimator::Initialize(const vector &relations, state->cardinalities.emplace(set_manager.GetJoinRelation(RelationIndex(i)), cardinality); UpdateTotalDomains(RelationIndex(i), stats, sources); } + for (auto &op : operators) { + if (op->type != JoinOrderOperatorType::MARK) { + continue; + } + D_ASSERT(op->right_relations.get().count == 1); + auto rhs = op->right_relations.get().relations[0]; + // The marker's synthetic slot follows the RHS columns but is produced by the join. + auto key = ColumnBinding(TableIndex(rhs.index), ProjectionIndex(relations[rhs.index].columns.size())); + for (auto &domain : state->relation_set_stats) { + if (domain.equivalent_relations.count(key)) { + domain.domain_estimate.Update(key, DistinctCount(3, DistinctCountSource::CARDINALITY), nullptr); + } + } + } RestrictFilterDomains(relations); for (auto &domain : state->relation_set_stats) { for (auto &predicate : domain.predicates) { @@ -982,6 +1056,7 @@ void CardinalityEstimator::Initialize(const vector &relations, } } std::stable_sort(state->edges.begin(), state->edges.end(), SortEdges); + state->InitializeEdgeIndex(); for (auto &op : operators) { D_ASSERT(op->index == state->operators.size()); state->operators.push_back(*op); diff --git a/src/duckdb/src/optimizer/join_order/cost_model.cpp b/src/duckdb/src/optimizer/join_order/cost_model.cpp index e0b8e2390..dccbc0d53 100644 --- a/src/duckdb/src/optimizer/join_order/cost_model.cpp +++ b/src/duckdb/src/optimizer/join_order/cost_model.cpp @@ -22,6 +22,10 @@ double CostModel::ComputeCost(const DPJoinNode &left, const DPJoinNode &right, return left.cost + right.cost + input_cost + output_rows; } +double CostModel::ComputeCostLowerBound(const DPJoinNode &left, const DPJoinNode &right, double output_rows) { + return ComputeCost(left, right, nullptr, output_rows); +} + void CostModel::InitializeRecursiveMemory(ClientContext &context, RelationManager &relations) { if (!relations.HasRecursiveRelations() || Settings::Get(context)) { return; diff --git a/src/duckdb/src/optimizer/join_order/greedy_join_enumerator.cpp b/src/duckdb/src/optimizer/join_order/greedy_join_enumerator.cpp index 11c80d036..e888b8642 100644 --- a/src/duckdb/src/optimizer/join_order/greedy_join_enumerator.cpp +++ b/src/duckdb/src/optimizer/join_order/greedy_join_enumerator.cpp @@ -2,132 +2,167 @@ #include "duckdb/optimizer/join_order/query_graph_manager.hpp" +#include + namespace duckdb { GreedyJoinEnumerator::GreedyJoinEnumerator(QueryGraphManager &graph, JoinOrderCandidateEvaluator &evaluator) : query_graph_manager(graph), evaluator(evaluator) { } -bool GreedyJoinEnumerator::Solve(JoinOrderPlanMap &plans) { - // at this point, we exited the dynamic programming but did not compute the final join order because it took too - // long instead, we use a greedy heuristic to obtain a join ordering now we use Greedy Operator Ordering to - // construct the result tree first we start out with all the base relations (the to-be-joined relations) - vector> join_relations; // T in the paper - for (idx_t i = 0; i < query_graph_manager.relation_manager.NumRelations(); i++) { - join_relations.push_back(query_graph_manager.set_manager.GetJoinRelation(RelationIndex(i))); +idx_t GreedyJoinEnumerator::AddGroup(JoinRelationSet &set) { + auto group = groups.size(); + groups.push_back(set); + active_groups.push_back(group); + for (idx_t i = 0; i < set.count; i++) { + group_for_relation[set.relations[i].index] = group; } + return group; +} - // in every step of the algorithm, we greedily pick the join between the to-be-joined relations that has the - // smallest cost. Pair costs are deterministic while the query graph is unchanged, so we evaluate each pair once - // and keep the viable candidates in a list, instead of re-emitting every pair in every step - struct GreedyCandidate { - optional_ptr left; - optional_ptr right; - JoinPlanCost cost; - }; - vector candidates; - auto EmitOrientation = [&](JoinRelationSet &left, JoinRelationSet &right) -> optional_ptr { - auto &connection = evaluator.GetConnections(left, right); - if (connection.empty()) { - return nullptr; - } - return evaluator.EmitPair(plans, left, right, connection); - }; - auto EmitCandidate = [&](JoinRelationSet &left, JoinRelationSet &right) { - // non-commutative joins (e.g. LEFT, SEMI, ANTI) are only valid in one orientation - auto node = EmitOrientation(left, right); - if (!node) { - node = EmitOrientation(right, left); +vector GreedyJoinEnumerator::GetConnectedGroups(idx_t group) const { + unordered_set connected_groups; + auto &set = groups[group].get(); + query_graph_manager.GetQueryGraphEdges().EnumerateNeighbors(set, [&](NeighborInfo &connection) { + D_ASSERT(connection.neighbor && !connection.neighbor->Empty()); + auto &neighbor = *connection.neighbor; + auto other_group = group_for_relation[neighbor.relations[0].index]; + if (other_group != group && JoinRelationSet::IsSubset(groups[other_group].get(), neighbor)) { + connected_groups.insert(other_group); } - if (node) { - candidates.push_back({&left, &right, evaluator.GetPlanCost(*node)}); - } - }; - auto InitializeCandidates = [&]() { - candidates.clear(); - for (idx_t i = 0; i < join_relations.size(); i++) { - for (idx_t j = i + 1; j < join_relations.size(); j++) { - EmitCandidate(join_relations[i], join_relations[j]); - } - } - }; - InitializeCandidates(); + return false; + }); + vector result(connected_groups.begin(), connected_groups.end()); + // The graph traversal order is unspecified. Keep the same order as the active-group list. + std::sort(result.begin(), result.end()); + return result; +} - while (join_relations.size() > 1) { - optional_ptr best_left; - optional_ptr best_right; - JoinPlanCost best_cost {NumericLimits::Maximum(), NumericLimits::Maximum()}; - for (auto &candidate : candidates) { - if (!best_left || candidate.cost < best_cost) { - best_cost = candidate.cost; - best_left = candidate.left; - best_right = candidate.right; +optional_ptr GreedyJoinEnumerator::EmitOrientation(JoinOrderPlanMap &plans, idx_t left, idx_t right) { + auto &connections = evaluator.GetConnections(groups[left], groups[right]); + if (connections.empty()) { + return nullptr; + } + return evaluator.EmitPair(plans, groups[left], groups[right], connections); +} + +void GreedyJoinEnumerator::EmitCandidate(JoinOrderPlanMap &plans, idx_t left, idx_t right) { + // Non-commutative joins (e.g. LEFT, SEMI, ANTI) are only valid in one orientation. + auto node = EmitOrientation(plans, left, right); + if (!node) { + node = EmitOrientation(plans, right, left); + } + if (node) { + candidates.push_back({left, right, evaluator.GetPlanCost(*node)}); + } +} + +void GreedyJoinEnumerator::InitializeCandidates(JoinOrderPlanMap &plans) { + candidates.clear(); + for (auto group : active_groups) { + for (auto other_group : GetConnectedGroups(group)) { + if (other_group > group) { + EmitCandidate(plans, group, other_group); } } - if (!best_left) { - if (evaluator.ActivateRequiredCrossProducts()) { - // the query graph gained edges, which invalidates the evaluated candidates - InitializeCandidates(); + } +} + +bool GreedyJoinEnumerator::TryCrossProduct(JoinOrderPlanMap &plans, idx_t &left, idx_t &right) { + optional_idx best_left; + optional_idx best_right; + JoinPlanCost best_cost {NumericLimits::Maximum(), NumericLimits::Maximum()}; + // Optimizer-introduced cross products are valid only inside an inner-join companion set (Section 6.2). + for (idx_t i = 0; i < active_groups.size(); i++) { + auto left_group = active_groups[i]; + auto &left_set = groups[left_group].get(); + for (idx_t j = i + 1; j < active_groups.size(); j++) { + auto right_group = active_groups[j]; + auto &right_set = groups[right_group].get(); + if (!query_graph_manager.CanCreateCrossProduct(left_set, right_set)) { continue; } - // Optimizer-introduced cross products are valid only inside an inner-join companion set (Section 6.2). - for (idx_t i = 0; i < join_relations.size(); i++) { - auto &left = join_relations[i].get(); - for (idx_t j = i + 1; j < join_relations.size(); j++) { - auto &right = join_relations[j].get(); - if (!query_graph_manager.CanCreateCrossProduct(left, right)) { - continue; - } - auto left_plan = plans.find(left); - auto right_plan = plans.find(right); - D_ASSERT(left_plan != plans.end() && right_plan != plans.end()); - auto left_cost = evaluator.GetPlanCost(*left_plan->second); - auto right_cost = evaluator.GetPlanCost(*right_plan->second); - JoinPlanCost cost {left_cost.work + right_cost.work, - MaxValue(left_cost.memory_excess, right_cost.memory_excess)}; - if (!best_left || cost < best_cost) { - best_cost = cost; - best_left = left; - best_right = right; - } - } + auto left_plan = plans.find(left_set); + auto right_plan = plans.find(right_set); + D_ASSERT(left_plan != plans.end() && right_plan != plans.end()); + auto left_cost = evaluator.GetPlanCost(*left_plan->second); + auto right_cost = evaluator.GetPlanCost(*right_plan->second); + JoinPlanCost cost {left_cost.work + right_cost.work, + MaxValue(left_cost.memory_excess, right_cost.memory_excess)}; + if (!best_left.IsValid() || cost < best_cost) { + best_cost = cost; + best_left = optional_idx(left_group); + best_right = optional_idx(right_group); } - if (!best_left) { - return false; - } - // create a cross product edge (i.e. edge with empty filter) between these two sets in the query graph - auto &connections = evaluator.CreateCrossProduct(*best_left, *best_right); - // the new edge only connects this pair, which is merged below, so the other candidates remain valid - // now emit the pair and continue with the algorithm - D_ASSERT(!connections.empty()); + } + } + if (!best_left.IsValid()) { + return false; + } + left = best_left.GetIndex(); + right = best_right.GetIndex(); + // This new edge only connects the pair merged next, so the other candidates remain valid. + auto &connections = evaluator.CreateCrossProduct(groups[left], groups[right]); + D_ASSERT(!connections.empty()); + return evaluator.EmitPair(plans, groups[left], groups[right], connections) != nullptr; +} - auto cross_product = evaluator.EmitPair(plans, *best_left, *best_right, connections); - if (!cross_product) { - return false; - } +void GreedyJoinEnumerator::MergeGroups(JoinOrderPlanMap &plans, idx_t left, idx_t right) { + auto &new_set = query_graph_manager.set_manager.Union(groups[left], groups[right]); + auto removed = [&](idx_t group) { + return group == left || group == right; + }; + active_groups.erase(std::remove_if(active_groups.begin(), active_groups.end(), removed), active_groups.end()); + idx_t kept_candidates = 0; + for (idx_t i = 0; i < candidates.size(); i++) { + auto &candidate = candidates[i]; + if (!removed(candidate.left) && !removed(candidate.right)) { + candidates[kept_candidates++] = candidate; } - // now update the to-be-checked pairs: remove left and right, and add the combination - auto &new_set = query_graph_manager.set_manager.Union(*best_left, *best_right); - for (idx_t i = join_relations.size(); i > 0; i--) { - auto &relation = join_relations[i - 1].get(); - if (&relation == best_left.get() || &relation == best_right.get()) { - join_relations.erase(join_relations.begin() + NumericCast(i - 1)); + } + candidates.resize(kept_candidates); + auto new_group = AddGroup(new_set); + // Graph construction inserts both edge orientations. Visiting the new group also finds hyperedges with an + // endpoint completed by this merge; full-endpoint containment is checked before evaluation. + for (auto other_group : GetConnectedGroups(new_group)) { + EmitCandidate(plans, other_group, new_group); + } +} + +bool GreedyJoinEnumerator::Solve(JoinOrderPlanMap &plans) { + groups.clear(); + active_groups.clear(); + candidates.clear(); + group_for_relation.resize(query_graph_manager.relation_manager.NumRelations()); + for (idx_t i = 0; i < group_for_relation.size(); i++) { + AddGroup(query_graph_manager.set_manager.GetJoinRelation(RelationIndex(i))); + } + InitializeCandidates(plans); + + // Pair costs are deterministic while the graph is unchanged. Keep viable candidates until an input is merged. + while (active_groups.size() > 1) { + optional_idx best; + for (idx_t i = 0; i < candidates.size(); i++) { + if (!best.IsValid() || candidates[i].cost < candidates[best.GetIndex()].cost) { + best = optional_idx(i); } } - idx_t kept_candidates = 0; - for (idx_t candidate_idx = 0; candidate_idx < candidates.size(); candidate_idx++) { - auto &candidate = candidates[candidate_idx]; - if (candidate.left == best_left || candidate.left == best_right || candidate.right == best_left || - candidate.right == best_right) { + idx_t left; + idx_t right; + if (best.IsValid()) { + left = candidates[best.GetIndex()].left; + right = candidates[best.GetIndex()].right; + } else { + if (evaluator.ActivateRequiredCrossProducts()) { + // The graph gained edges, invalidating evaluated candidates. + InitializeCandidates(plans); continue; } - candidates[kept_candidates++] = candidate; - } - candidates.resize(kept_candidates); - for (auto &relation : join_relations) { - EmitCandidate(relation, new_set); + if (!TryCrossProduct(plans, left, right)) { + return false; + } } - join_relations.push_back(new_set); + MergeGroups(plans, left, right); } return true; } diff --git a/src/duckdb/src/optimizer/join_order/join_order_candidate.cpp b/src/duckdb/src/optimizer/join_order/join_order_candidate.cpp index e374e88d3..e0ae79957 100644 --- a/src/duckdb/src/optimizer/join_order/join_order_candidate.cpp +++ b/src/duckdb/src/optimizer/join_order/join_order_candidate.cpp @@ -122,8 +122,14 @@ JoinOrderCandidateEvaluator::CreateJoinTree(JoinRelationSet &set, optional_ptr JoinOrderCandidateEvaluator::EmitPair(JoinOrderPlanMap &plans, JoinRelationSet &left, JoinRelationSet &right, - const vector> &info) { + const vector> &connections) { auto &set = query_graph_manager.set_manager.Union(left, right); + return EmitPair(plans, set, left, right, connections); +} + +optional_ptr JoinOrderCandidateEvaluator::EmitPair(JoinOrderPlanMap &plans, JoinRelationSet &set, + JoinRelationSet &left, JoinRelationSet &right, + const vector> &connections) { // get the left and right join plans auto left_plan = plans.find(left); auto right_plan = plans.find(right); @@ -131,7 +137,7 @@ optional_ptr JoinOrderCandidateEvaluator::EmitPair(JoinOrderPlanMap throw InternalException("No left or right plan: internal error in join order optimizer"); } // create the join tree based on combining the two plans - return ConsiderJoinTree(plans, CreateJoinTree(set, info, *left_plan->second, *right_plan->second)); + return ConsiderJoinTree(plans, CreateJoinTree(set, connections, *left_plan->second, *right_plan->second)); } optional_ptr JoinOrderCandidateEvaluator::ConsiderJoinTree(JoinOrderPlanMap &plans, @@ -142,37 +148,61 @@ optional_ptr JoinOrderCandidateEvaluator::ConsiderJoinTree(JoinOrder auto &new_set = new_plan->set; // check if this plan is the optimal plan we found for this set of relations auto entry = plans.find(new_set); - auto new_cost = GetPlanCost(*new_plan); - JoinPlanCost old_cost {NumericLimits::Maximum(), NumericLimits::Maximum()}; - if (entry != plans.end()) { - old_cost = GetPlanCost(*entry->second); - } - if (entry == plans.end() || new_cost < old_cost) { - // the new plan costs less than the old plan. Update our DP table. + if (entry == plans.end() || PreferPlan(*new_plan, plans, *entry->second, plans)) { plans[new_set] = std::move(new_plan); return plans[new_set].get(); } + return entry->second.get(); +} + +bool JoinOrderCandidateEvaluator::PreferPlan(const DPJoinNode &candidate, const JoinOrderPlanMap &candidate_plans, + const DPJoinNode &incumbent, + const JoinOrderPlanMap &incumbent_plans) const { + auto new_cost = cost_model.GetCost(candidate); + auto old_cost = cost_model.GetCost(incumbent); + if (new_cost < old_cost) { + return true; + } // Tiebreaker for equal-cost plans: needed for LEFT JOINs, // because all orderings preserve the LHS cardinality and always tie. // This tiebreaker causes less joins to be flipped from LEFT to RIGHT // later by the BuildProbeSideOptimizer, and we strongly prefer LEFT - if (new_cost == old_cost) { - auto new_right_cardinality = plans.at(new_plan->right_set)->cardinality; - auto existing_right = plans.find(entry->second->right_set); - if (existing_right != plans.end()) { + if (new_cost == old_cost && !candidate.is_leaf) { + auto new_right_cardinality = candidate_plans.at(candidate.right_set)->cardinality; + auto existing_right = incumbent_plans.find(incumbent.right_set); + if (existing_right != incumbent_plans.end()) { auto old_right_cardinality = existing_right->second->cardinality; if (new_right_cardinality > old_right_cardinality) { - plans[new_set] = std::move(new_plan); - return plans[new_set].get(); + return true; } } } - // Create join node from the plan currently in the DP table. - return entry->second.get(); + return false; } -void JoinOrderCandidateEvaluator::InitLeafPlans(JoinOrderPlanMap &plans) { - auto relation_stats = query_graph_manager.relation_manager.GetRelationStats(); +bool JoinOrderCandidateEvaluator::CanImprovePair(const JoinOrderPlanMap &plans, const DPJoinNode &left, + const DPJoinNode &right, const DPJoinNode &incumbent) const { + auto incumbent_cost = cost_model.GetCost(incumbent); + if (incumbent_cost.memory_excess > 0) { + return true; + } + auto minimum_work = cost_model.ComputeCostLowerBound(left, right, incumbent.cardinality.GetDouble()); + if (minimum_work > incumbent_cost.work) { + return false; + } + if (minimum_work != incumbent_cost.work) { + return true; + } + auto incumbent_right = plans.find(incumbent.right_set); + if (incumbent_right == plans.end()) { + return true; + } + // Equal work can still win PreferPlan's right-cardinality tiebreaker. + return left.cardinality > incumbent_right->second->cardinality || + right.cardinality > incumbent_right->second->cardinality; +} + +void JoinOrderCandidateEvaluator::InitLeafPlans(JoinOrderPlanMap &plans, const vector &relation_stats) { auto &estimator = cost_model.GetCardinalityEstimator(); estimator.Initialize(relation_stats, query_graph_manager.GetJoinOperators(), query_graph_manager.relation_manager.GetColumnSources()); @@ -222,4 +252,8 @@ const vector> &JoinOrderCandidateEvaluator::CreateCrossP return GetConnections(left, right); } +void JoinOrderCandidateEvaluator::ResetConnectionCache() { + connection_cache.clear(); +} + } // namespace duckdb diff --git a/src/duckdb/src/optimizer/join_order/join_order_linearizer.cpp b/src/duckdb/src/optimizer/join_order/join_order_linearizer.cpp new file mode 100644 index 000000000..97dff0e52 --- /dev/null +++ b/src/duckdb/src/optimizer/join_order/join_order_linearizer.cpp @@ -0,0 +1,207 @@ +#include "duckdb/optimizer/join_order/join_order_linearizer.hpp" + +#include "duckdb/common/limits.hpp" +#include "duckdb/main/client_context.hpp" +#include "duckdb/optimizer/join_order/query_graph_manager.hpp" + +#include +#include + +namespace duckdb { + +JoinOrderLinearizer::JoinOrderLinearizer(QueryGraphManager &graph, CardinalityEstimator &estimator) + : graph(graph), estimator(estimator) { +} + +bool JoinOrderLinearizer::BuildTree() { + for (auto &op : graph.GetJoinOperators()) { + if (op->type != JoinOrderOperatorType::INNER && op->type != JoinOrderOperatorType::CROSS_PRODUCT) { + return false; + } + } + auto count = graph.relation_manager.NumRelations(); + for (idx_t i = 0; i < count; i++) { + graph.context.InterruptCheck(); + auto &set = graph.set_manager.GetJoinRelation(RelationIndex(i)); + cardinalities.push_back(estimator.EstimateCardinality(set).GetLog()); + } + vector edges; + bool edges_complete = true; + graph.GetQueryGraphEdges().EnumerateEdges([&](JoinRelationSet &left, NeighborInfo &edge) { + graph.context.InterruptCheck(); + auto &right = *edge.neighbor; + if (left.count != 1 || right.count != 1) { + edges_complete = false; + return true; + } + auto lhs = left.relations[0].index; + auto rhs = right.relations[0].index; + auto &set = graph.set_manager.Union(left, right); + double selectivity = 0; + if (std::isfinite(cardinalities[lhs]) && std::isfinite(cardinalities[rhs])) { + selectivity = estimator.EstimateCardinality(set).GetLog() - cardinalities[lhs] - cardinalities[rhs]; + } + edges.push_back({MinValue(lhs, rhs), MaxValue(lhs, rhs), selectivity}); + return false; + }); + if (!edges_complete) { + return false; + } + vector parent; + for (idx_t i = 0; i < count; i++) { + parent.push_back(i); + } + auto find_root = [&](idx_t node) { + while (parent[node] != node) { + parent[node] = parent[parent[node]]; + node = parent[node]; + } + return node; + }; + // Check active ordinary-edge connectivity before constructing the ranking tree. Missing connections must + // still go through the existing cross-product-capable search, not an arbitrary spanning forest order. + idx_t components = count; + for (auto &edge : edges) { + graph.context.InterruptCheck(); + auto left = find_root(edge.left); + auto right = find_root(edge.right); + if (left != right) { + parent[right] = left; + components--; + } + } + if (components != 1) { + return false; + } + for (idx_t i = 0; i < count; i++) { + parent[i] = i; + } + std::sort(edges.begin(), edges.end(), [](const Edge &left, const Edge &right) { + if (left.log_selectivity != right.log_selectivity) { + return left.log_selectivity < right.log_selectivity; + } + return left.left != right.left ? left.left < right.left : left.right < right.right; + }); + for (auto &edge : edges) { + graph.context.InterruptCheck(); + auto left = find_root(edge.left); + auto right = find_root(edge.right); + if (left != right) { + tree.push_back(edge); + parent[right] = left; + } + } + D_ASSERT(tree.size() + 1 == count); + return true; +} + +JoinOrderLinearizer::Block::Block(RelationIndex relation, double multiplier) : relations {relation}, rank(multiplier) { +} + +void JoinOrderLinearizer::Normalize(vector &chain) { + vector normalized; + for (auto &block : chain) { + graph.context.InterruptCheck(); + normalized.push_back(std::move(block)); + while (normalized.size() > 1 && normalized.back().rank < normalized[normalized.size() - 2].rank) { + auto &left = normalized[normalized.size() - 2]; + auto &right = normalized.back(); + left.rank.Append(right.rank); + left.relations.insert(left.relations.end(), right.relations.begin(), right.relations.end()); + normalized.pop_back(); + } + } + chain = std::move(normalized); +} + +RankedJoinOrder JoinOrderLinearizer::GetOrder(RelationIndex root) { + auto count = cardinalities.size(); + D_ASSERT(root.index < count); + vector>> adjacency(count); + for (auto &edge : tree) { + adjacency[edge.left].emplace_back(edge.right, edge.log_selectivity); + adjacency[edge.right].emplace_back(edge.left, edge.log_selectivity); + } + vector parent(count, DConstants::INVALID_INDEX); + vector multiplier(count); + vector preorder {root.index}; + parent[root.index] = root.index; + multiplier[root.index] = cardinalities[root.index]; + for (idx_t i = 0; i < preorder.size(); i++) { + auto node = preorder[i]; + for (auto &edge : adjacency[node]) { + graph.context.InterruptCheck(); + if (parent[edge.first] != DConstants::INVALID_INDEX) { + continue; + } + parent[edge.first] = node; + multiplier[edge.first] = cardinalities[edge.first] + edge.second; + preorder.push_back(edge.first); + } + } + D_ASSERT(preorder.size() == count); + vector> chains(count); + for (idx_t i = preorder.size(); i > 0; i--) { + auto node = preorder[i - 1]; + auto &chain = chains[node]; + chain.emplace_back(RelationIndex(node), multiplier[node]); + vector children; + for (auto &edge : adjacency[node]) { + if (parent[edge.first] == node && edge.first != root.index) { + Normalize(chains[edge.first]); + children.push_back(edge.first); + } + } + vector positions(children.size(), 0); + while (true) { + idx_t best = DConstants::INVALID_INDEX; + for (idx_t child = 0; child < children.size(); child++) { + graph.context.InterruptCheck(); + auto &child_chain = chains[children[child]]; + if (positions[child] == child_chain.size()) { + continue; + } + if (best == DConstants::INVALID_INDEX) { + best = child; + continue; + } + auto &candidate = child_chain[positions[child]]; + auto &incumbent = chains[children[best]][positions[best]]; + if (candidate.rank < incumbent.rank || + (!(incumbent.rank < candidate.rank) && candidate.relations[0] < incumbent.relations[0])) { + best = child; + } + } + if (best == DConstants::INVALID_INDEX) { + break; + } + chain.push_back(std::move(chains[children[best]][positions[best]++])); + } + } + RankedJoinOrder result; + JoinOrderRank cost(multiplier[root.index]); + // Leaves have no join cost; only the subsequent compound blocks contribute work. + cost.log_work = -std::numeric_limits::infinity(); + for (idx_t i = 1; i < chains[root.index].size(); i++) { + cost.Append(chains[root.index][i].rank); + } + result.log_cost = cost.log_work; + for (auto &block : chains[root.index]) { + result.relations.insert(result.relations.end(), block.relations.begin(), block.relations.end()); + } + return result; +} + +vector JoinOrderLinearizer::GetBestOrder() { + D_ASSERT(!cardinalities.empty()); + auto best = GetOrder(RelationIndex(0)); + for (idx_t root = 1; root < cardinalities.size(); root++) { + auto candidate = GetOrder(RelationIndex(root)); + if (candidate.log_cost < best.log_cost) { + best = std::move(candidate); + } + } + return std::move(best.relations); +} + +} // namespace duckdb diff --git a/src/duckdb/src/optimizer/join_order/join_order_operator.cpp b/src/duckdb/src/optimizer/join_order/join_order_operator.cpp index 095dad670..6dd690e8c 100644 --- a/src/duckdb/src/optimizer/join_order/join_order_operator.cpp +++ b/src/duckdb/src/optimizer/join_order/join_order_operator.cpp @@ -146,8 +146,12 @@ static bool IsAssociative(const JoinOrderOperator &left, const JoinOrderOperator } static bool IsLeftAssociativeCommutative(const JoinOrderOperator &left, const JoinOrderOperator &right) { - (void)left; - (void)right; + if (left.type == JoinOrderOperatorType::MARK || right.type == JoinOrderOperatorType::MARK) { + auto supported = [](JoinOrderOperatorType type) { + return AlgebraicType(type) == JoinOrderOperatorType::INNER || type == JoinOrderOperatorType::MARK; + }; + return supported(left.type) && supported(right.type); + } // For INNER, LEFT OUTER, ANTI, and SEMI joins every left associative-commutative entry in Table 3 is true. return true; } diff --git a/src/duckdb/src/optimizer/join_order/join_order_plan.cpp b/src/duckdb/src/optimizer/join_order/join_order_plan.cpp new file mode 100644 index 000000000..0acb6741c --- /dev/null +++ b/src/duckdb/src/optimizer/join_order/join_order_plan.cpp @@ -0,0 +1,80 @@ +#include "duckdb/optimizer/join_order/join_order_plan.hpp" + +namespace duckdb { + +JoinOrderPlanMap CopyJoinOrderLeafPlans(const JoinOrderPlanMap &source) { + JoinOrderPlanMap result; + for (auto &entry : source) { + if (entry.second->is_leaf) { + result.emplace(entry.first, make_uniq(*entry.second)); + } + } + return result; +} + +CapturedJoinOrderPlan::CapturedJoinOrderPlan(JoinRelationSet &root, JoinOrderPlanMap plans) + : root(root), plans(std::move(plans)) { +} + +unique_ptr CapturedJoinOrderPlan::Capture(const JoinOrderPlanMap &source, JoinRelationSet &root, + CostModel &cost_model) { + vector> pending {root}; + vector> preorder; + while (!pending.empty()) { + // Missing children are a broken closure invariant, not an ordinary failed trial. + auto &node = *source.at(pending.back()); + pending.pop_back(); + preorder.push_back(node); + if (!node.is_leaf) { + pending.push_back(node.left_set); + pending.push_back(node.right_set); + } + } + JoinOrderPlanMap result; + for (idx_t i = preorder.size(); i > 0; i--) { + auto node = make_uniq(preorder[i - 1].get()); + if (!node->is_leaf) { + auto &left = *result.at(node->left_set); + auto &right = *result.at(node->right_set); + node->cost = cost_model.ComputeCost(left, right, node->join_operator, node->cardinality.GetDouble()); + cost_model.UpdateBuildMemory(*node, left, right); + } + result.emplace(node->set, std::move(node)); + } + return unique_ptr(new CapturedJoinOrderPlan(root, std::move(result))); +} + +JoinRelationSet &CapturedJoinOrderPlan::GetRoot() const { + return root; +} + +const DPJoinNode &CapturedJoinOrderPlan::GetRootNode() const { + return *plans.at(root); +} + +const JoinOrderPlanMap &CapturedJoinOrderPlan::GetPlans() const { + return plans; +} + +vector CapturedJoinOrderPlan::GetLeafOrder() const { + vector order; + vector> pending {root}; + while (!pending.empty()) { + auto &node = *plans.at(pending.back()); + pending.pop_back(); + if (node.is_leaf) { + D_ASSERT(node.set.count == 1); + order.push_back(node.set.relations[0]); + } else { + pending.push_back(node.right_set); + pending.push_back(node.left_set); + } + } + return order; +} + +JoinOrderPlanMap CapturedJoinOrderPlan::TakePlans() { + return std::move(plans); +} + +} // namespace duckdb diff --git a/src/duckdb/src/optimizer/join_order/join_order_precedence.cpp b/src/duckdb/src/optimizer/join_order/join_order_precedence.cpp new file mode 100644 index 000000000..1ce6fa578 --- /dev/null +++ b/src/duckdb/src/optimizer/join_order/join_order_precedence.cpp @@ -0,0 +1,572 @@ +#include "duckdb/optimizer/join_order/join_order_precedence.hpp" + +#include "duckdb/optimizer/join_order/query_graph_manager.hpp" +#include "duckdb/optimizer/join_order/join_order_plan.hpp" +#include "duckdb/main/client_context.hpp" + +#include +#include + +namespace duckdb { + +JoinOrderPrecedence::Atom::Atom(vector relations, double multiplier, double preparation, idx_t group) + : relations(std::move(relations)), rank(multiplier), log_preparation(preparation), group(group) { +} + +JoinOrderPrecedence::Block::Block(Atom atom, vector prerequisites) + : rank(atom.rank), prerequisites(std::move(prerequisites)) { + atoms.push_back(std::move(atom)); +} + +JoinOrderPrecedence::Node::Node(Block block) : block(std::move(block)) { +} + +JoinOrderPrecedence::JoinOrderPrecedence(QueryGraphManager &graph, CardinalityEstimator &estimator, + JoinOrderCandidateEvaluator &evaluator, const CapturedJoinOrderPlan &witness) + : graph(graph), estimator(estimator), evaluator(evaluator), witness(witness) { +} + +bool JoinOrderPrecedence::Build() { + const auto &plans = witness.GetPlans(); + auto &root = witness.GetRoot(); + for (idx_t i = 0; i < graph.relation_manager.NumRelations(); i++) { + graph.context.InterruptCheck(); + cardinalities.push_back(plans.at(graph.set_manager.GetJoinRelation(RelationIndex(i)))->cardinality.GetLog()); + } + vector, reference>> connections; + graph.GetQueryGraphEdges().EnumerateEdges([&](JoinRelationSet &left, NeighborInfo &edge) { + graph.context.InterruptCheck(); + connections.emplace_back(left, edge); + return false; + }); + vector> pending {*plans.at(root)}, nodes; + while (!pending.empty()) { + graph.context.InterruptCheck(); + auto &node = pending.back().get(); + pending.pop_back(); + if (!node.is_leaf) { + nodes.push_back(node); + pending.push_back(*plans.at(node.left_set)); + pending.push_back(*plans.at(node.right_set)); + } + } + for (idx_t node_idx = nodes.size(); node_idx > 0; node_idx--) { + auto &node = nodes[node_idx - 1].get(); + idx_t best = DConstants::INVALID_INDEX; + for (idx_t i = 0; i < connections.size(); i++) { + graph.context.InterruptCheck(); + auto &left = connections[i].first.get(); + auto &edge = connections[i].second.get(); + if (edge.join_operator != node.join_operator || + edge.generated_cross_product != node.generated_cross_product || + !JoinRelationSet::IsSubset(node.left_set, left) || + !JoinRelationSet::IsSubset(node.right_set, *edge.neighbor) || + !graph.IsConnectionApplicable(edge, node.left_set, node.right_set) || + !graph.IsJoinOrderCandidate(edge.join_operator, edge.generated_cross_product, node.left_set, + node.right_set)) { + continue; + } + // Each connection here uses the same witnessed join estimate. Break proxy ties by full endpoints. + if (best == DConstants::INVALID_INDEX || + EndpointLess(left, *edge.neighbor, connections[best].first, *connections[best].second.get().neighbor)) { + best = i; + } + } + if (best == DConstants::INVALID_INDEX) { + return false; + } + auto left_log = plans.at(node.left_set)->cardinality.GetLog(); + auto right_log = plans.at(node.right_set)->cardinality.GetLog(); + double selectivity = 0; + if (std::isfinite(left_log) && std::isfinite(right_log)) { + selectivity = node.cardinality.GetLog() - left_log - right_log; + } + auto &edge = connections[best]; + edges.push_back({edge.first, *edge.second.get().neighbor, selectivity}); + } + return CheckComponent(Mask(cardinalities.size(), true)); +} + +RankedJoinOrder JoinOrderPrecedence::GetOrder(RelationIndex root) { + Mask component(cardinalities.size(), true); + auto chain = Solve(root, component); + if (chain.empty()) { + return {}; + } + RankedJoinOrder result; + result.log_cost = TotalWork(chain); + vector atoms; + for (auto &block : chain) { + if (!block.prerequisites.empty()) { + return {}; + } + for (auto &atom : block.atoms) { + result.relations.insert(result.relations.end(), atom.relations.begin(), atom.relations.end()); + atoms.push_back(std::move(atom)); + } + } + // Check this prescribed construction, not alternative parenthesizations of the order. + auto plans = CopyJoinOrderLeafPlans(witness.GetPlans()); + auto constructed = Materialize(atoms, plans); + if (!constructed || constructed.get() != &witness.GetRoot()) { + return {}; + } + return result; +} + +bool JoinOrderPrecedence::EndpointLess(const JoinRelationSet &left, const JoinRelationSet &right, + const JoinRelationSet &other_left, const JoinRelationSet &other_right) { + for (auto pair : + {make_pair(reference(left), reference(other_left)), + make_pair(reference(right), reference(other_right))}) { + auto &a = pair.first; + auto &b = pair.second; + for (idx_t i = 0; i < MinValue(a.count, b.count); i++) { + if (a.relations[i] != b.relations[i]) { + return a.relations[i] < b.relations[i]; + } + } + if (a.count != b.count) { + return a.count < b.count; + } + } + return false; +} + +bool JoinOrderPrecedence::Contains(const Mask &mask, const JoinRelationSet &set) { + for (idx_t i = 0; i < set.count; i++) { + if (!mask[set.relations[i].index]) { + return false; + } + } + return true; +} + +idx_t JoinOrderPrecedence::Count(const Mask &mask) { + return std::count(mask.begin(), mask.end(), true); +} + +idx_t JoinOrderPrecedence::FindRoot(vector &parents, idx_t node) { + while (parents[node] != node) { + parents[node] = parents[parents[node]]; + node = parents[node]; + } + return node; +} + +void JoinOrderPrecedence::Components(const Mask &component, idx_t omitted, vector &labels) { + graph.context.InterruptCheck(); + labels.resize(component.size()); + for (idx_t i = 0; i < labels.size(); i++) { + labels[i] = i; + } + for (idx_t edge_idx = 0; edge_idx < edges.size(); edge_idx++) { + auto &edge = edges[edge_idx]; + graph.context.InterruptCheck(); + if (edge_idx == omitted || !Contains(component, edge.left) || !Contains(component, edge.right)) { + continue; + } + auto root = FindRoot(labels, edge.left.get().relations[0].index); + for (auto endpoint : {edge.left, edge.right}) { + for (idx_t i = 0; i < endpoint.get().count; i++) { + labels[FindRoot(labels, endpoint.get().relations[i].index)] = root; + } + } + } + for (idx_t i = 0; i < labels.size(); i++) { + labels[i] = component[i] ? FindRoot(labels, i) : DConstants::INVALID_INDEX; + } +} + +bool JoinOrderPrecedence::CheckComponent(const Mask &component) { + for (auto &checked : checked_components) { + graph.context.InterruptCheck(); + if (checked == component) { + return true; + } + } + vector labels; + Components(component, DConstants::INVALID_INDEX, labels); + unordered_set roots; + for (idx_t i = 0; i < labels.size(); i++) { + if (component[i]) { + roots.insert(labels[i]); + } + } + if (roots.size() != 1) { + return false; + } + vector ordinary_parents(component.size()); + for (idx_t i = 0; i < ordinary_parents.size(); i++) { + ordinary_parents[i] = i; + } + for (idx_t edge_idx = 0; edge_idx < edges.size(); edge_idx++) { + auto &edge = edges[edge_idx]; + graph.context.InterruptCheck(); + if (!Contains(component, edge.left) || !Contains(component, edge.right)) { + continue; + } + if (edge.left.get().count == 1 && edge.right.get().count == 1) { + auto left = FindRoot(ordinary_parents, edge.left.get().relations[0].index); + auto right = FindRoot(ordinary_parents, edge.right.get().relations[0].index); + if (left == right) { + return false; + } + ordinary_parents[right] = left; + continue; + } + Components(component, edge_idx, labels); + roots.clear(); + for (idx_t i = 0; i < labels.size(); i++) { + if (component[i]) { + roots.insert(labels[i]); + } + } + auto left = labels[edge.left.get().relations[0].index]; + auto right = labels[edge.right.get().relations[0].index]; + bool separated = roots.size() == 2 && left != right; + for (auto endpoint : {edge.left, edge.right}) { + auto expected = labels[endpoint.get().relations[0].index]; + for (idx_t i = 0; i < endpoint.get().count; i++) { + separated &= labels[endpoint.get().relations[i].index] == expected; + } + } + if (!separated) { + return false; + } + } + graph.context.InterruptCheck(); + checked_components.push_back(component); + return true; +} + +void JoinOrderPrecedence::Mark(const Block &block, Mask &mask) { + for (auto &atom : block.atoms) { + for (auto relation : atom.relations) { + mask[relation.index] = true; + } + } +} + +double JoinOrderPrecedence::TotalWork(const vector &chain) { + D_ASSERT(!chain.empty()); + auto rank = chain.front().rank; + rank.log_work = -std::numeric_limits::infinity(); + for (idx_t i = 0; i < chain.size(); i++) { + if (i) { + rank.Append(chain[i].rank); + } + for (auto &atom : chain[i].atoms) { + rank.AddIndependentWork(atom.log_preparation); + } + } + return rank.log_work; +} + +idx_t JoinOrderPrecedence::SolveGroup(const JoinRelationSet &group, const Mask &component) { + Mask group_mask(component.size(), false); + for (idx_t i = 0; i < group.count; i++) { + group_mask[group.relations[i].index] = true; + } + for (idx_t i = 0; i < groups.size(); i++) { + auto &cached = groups[i]; + graph.context.InterruptCheck(); + if (cached.component == component && cached.group == group_mask) { + return i; + } + } + if (!CheckComponent(component)) { + return DConstants::INVALID_INDEX; + } + vector best; + double best_work = std::numeric_limits::infinity(); + for (idx_t i = 0; i < group.count; i++) { + graph.context.InterruptCheck(); + auto chain = Solve(group.relations[i], component); + if (chain.empty()) { + continue; + } + auto work = TotalWork(chain); + if (best.empty() || work < best_work) { + best_work = work; + best = std::move(chain); + } + } + if (best.empty()) { + return DConstants::INVALID_INDEX; + } + auto result = BuildGroup(best, group_mask); + // The component already excludes visited outer inputs; their traversal history cannot affect this group. + groups.push_back({component, group_mask, std::move(result)}); + return groups.size() - 1; +} + +JoinOrderPrecedence::Group JoinOrderPrecedence::BuildGroup(vector &chain, const Mask &group_mask) { + // Undo rank-normalization compounds; nested forward groups remain atomic. + vector atoms; + idx_t prefix = 0; + for (auto &block : chain) { + for (auto &atom : block.atoms) { + for (auto relation : atom.relations) { + if (group_mask[relation.index]) { + prefix = atoms.size() + 1; + } + } + atoms.push_back(std::move(atom)); + } + } + D_ASSERT(prefix > 0); + Group result; + auto rank = atoms.front().rank; + rank.log_work = -std::numeric_limits::infinity(); + for (idx_t i = 0; i < prefix; i++) { + graph.context.InterruptCheck(); + if (i) { + rank.Append(atoms[i].rank); + } + rank.AddIndependentWork(atoms[i].log_preparation); + result.relations.insert(result.relations.end(), atoms[i].relations.begin(), atoms[i].relations.end()); + result.atoms.push_back(std::move(atoms[i])); + } + graph.context.InterruptCheck(); + unordered_set bindings(result.relations.begin(), result.relations.end()); + auto &set = graph.set_manager.GetJoinRelation(bindings); + result.log_cardinality = estimator.EstimateCardinality(set).GetLog(); + result.log_preparation = rank.log_work; + return result; +} + +idx_t JoinOrderPrecedence::SolveForwardGroup(idx_t edge_idx, const JoinRelationSet &head, const Mask &component, + const Mask &marked) { + vector labels; + Components(component, edge_idx, labels); + Mask child(component.size(), false); + auto label = labels[head.relations[0].index]; + for (idx_t i = 0; i < child.size(); i++) { + child[i] = component[i] && labels[i] == label && !marked[i]; + } + if (Count(child) >= Count(component) || !Contains(child, head)) { + return DConstants::INVALID_INDEX; + } + return SolveGroup(head, child); +} + +bool JoinOrderPrecedence::Visit(idx_t node_idx, const Mask &component, Mask &marked, Mask path, vector &nodes) { + Mask own(component.size(), false); + Mark(nodes[node_idx].block, own); + Mark(nodes[node_idx].block, path); + Mark(nodes[node_idx].block, marked); + for (idx_t edge_idx = 0; edge_idx < edges.size(); edge_idx++) { + auto &edge = edges[edge_idx]; + for (bool reverse : {false, true}) { + auto &tail = reverse ? edge.right.get() : edge.left.get(); + auto &head = reverse ? edge.left.get() : edge.right.get(); + graph.context.InterruptCheck(); + if (!Contains(component, tail) || !Contains(component, head) || !Contains(marked, tail)) { + continue; + } + bool intersects = false, unvisited = true; + for (idx_t i = 0; i < tail.count; i++) { + intersects |= own[tail.relations[i].index]; + } + for (idx_t i = 0; i < head.count; i++) { + unvisited &= !marked[head.relations[i].index]; + } + if (!intersects || !unvisited) { + continue; + } + vector prerequisites; + for (idx_t i = 0; i < tail.count; i++) { + if (!path[tail.relations[i].index]) { + prerequisites.push_back(tail.relations[i]); + } + } + vector relations; + double cardinality, preparation = -std::numeric_limits::infinity(); + idx_t group_index = DConstants::INVALID_INDEX; + if (head.count == 1) { + relations.push_back(head.relations[0]); + cardinality = cardinalities[head.relations[0].index]; + } else { + group_index = SolveForwardGroup(edge_idx, head, component, marked); + if (group_index == DConstants::INVALID_INDEX) { + return false; + } + auto &group = groups[group_index].result; + relations = group.relations; + cardinality = group.log_cardinality; + preparation = group.log_preparation; + } + auto child_idx = nodes.size(); + nodes[node_idx].children.push_back(child_idx); + nodes.emplace_back( + Block(Atom(std::move(relations), cardinality + edge.log_selectivity, preparation, group_index), + std::move(prerequisites))); + if (!Visit(child_idx, component, marked, path, nodes)) { + return false; + } + } + } + return true; +} + +void JoinOrderPrecedence::Normalize(vector &chain) { + vector normalized; + for (auto &block : chain) { + graph.context.InterruptCheck(); + normalized.push_back(std::move(block)); + while (normalized.size() > 1 && normalized.back().prerequisites.empty() && + normalized.back().rank < normalized[normalized.size() - 2].rank) { + auto &left = normalized[normalized.size() - 2]; + auto &right = normalized.back(); + graph.context.InterruptCheck(); + left.rank.Append(right.rank); + for (auto &atom : right.atoms) { + left.atoms.push_back(std::move(atom)); + } + normalized.pop_back(); + } + } + chain = std::move(normalized); +} + +vector JoinOrderPrecedence::MergeChildren(Node &node, vector> &chains) { + vector chain; + Mask inside(cardinalities.size(), false), emitted(cardinalities.size(), false); + Mark(node.block, inside); + Mark(node.block, emitted); + chain.push_back(std::move(node.block)); + for (auto child : node.children) { + Normalize(chains[child]); + for (auto &block : chains[child]) { + Mark(block, inside); + } + } + vector positions(node.children.size(), 0); + while (true) { + bool unfinished = false; + idx_t best = DConstants::INVALID_INDEX; + for (idx_t child = 0; child < node.children.size(); child++) { + auto &child_chain = chains[node.children[child]]; + graph.context.InterruptCheck(); + if (positions[child] == child_chain.size()) { + continue; + } + unfinished = true; + auto &candidate = child_chain[positions[child]]; + bool available = true; + for (auto prerequisite : candidate.prerequisites) { + available &= !inside[prerequisite.index] || emitted[prerequisite.index]; + } + if (!available) { + continue; + } + if (best != DConstants::INVALID_INDEX) { + auto &incumbent = chains[node.children[best]][positions[best]]; + if (incumbent.rank < candidate.rank || + (!(candidate.rank < incumbent.rank) && + !(candidate.atoms[0].relations[0] < incumbent.atoms[0].relations[0]))) { + continue; + } + } + best = child; + } + if (best == DConstants::INVALID_INDEX) { + if (unfinished) { + return {}; + } + break; + } + auto block = std::move(chains[node.children[best]][positions[best]++]); + block.prerequisites.erase(std::remove_if(block.prerequisites.begin(), block.prerequisites.end(), + [&](RelationIndex relation) { return emitted[relation.index]; }), + block.prerequisites.end()); + Mark(block, emitted); + chain.push_back(std::move(block)); + } + return chain; +} + +vector JoinOrderPrecedence::Solve(RelationIndex root, const Mask &component) { + D_ASSERT(component[root.index]); + graph.context.InterruptCheck(); + vector nodes; + nodes.emplace_back(Block(Atom({root}, cardinalities[root.index], -std::numeric_limits::infinity()), {})); + Mask marked(component.size(), false), path(component.size(), false); + if (!Visit(0, component, marked, path, nodes) || marked != component) { + return {}; + } + vector> chains(nodes.size()); + for (idx_t i = nodes.size(); i > 0; i--) { + chains[i - 1] = MergeChildren(nodes[i - 1], chains); + if (chains[i - 1].empty()) { + return {}; + } + } + Mask covered(component.size(), false); + for (auto &block : chains[0]) { + if (!block.prerequisites.empty()) { + return {}; + } + for (auto &atom : block.atoms) { + for (auto relation : atom.relations) { + if (covered[relation.index]) { + return {}; + } + covered[relation.index] = true; + } + } + } + D_ASSERT(covered == component); + return std::move(chains[0]); +} + +optional_ptr JoinOrderPrecedence::Materialize(const vector &atoms, JoinOrderPlanMap &plans) { + optional_ptr root; + for (auto &atom : atoms) { + graph.context.InterruptCheck(); + optional_ptr next; + if (atom.group == DConstants::INVALID_INDEX) { + D_ASSERT(atom.relations.size() == 1); + next = graph.set_manager.GetJoinRelation(atom.relations[0]); + } else { + next = Materialize(groups[atom.group].result.atoms, plans); + } + if (!next) { + return nullptr; + } + if (!root) { + root = next; + continue; + } + auto &combined = graph.set_manager.Union(*root, *next); + auto &edges = graph.GetQueryGraphEdges(); + evaluator.EmitPair(plans, combined, *root, *next, edges.GetConnections(*root, *next)); + evaluator.EmitPair(plans, combined, *next, *root, edges.GetConnections(*next, *root)); + if (plans.find(combined) == plans.end()) { + return nullptr; + } + root = combined; + } + return root; +} + +vector JoinOrderPrecedence::GetBestOrder() { + cardinalities.clear(); + edges.clear(); + checked_components.clear(); + groups.clear(); + if (!Build()) { + return {}; + } + RankedJoinOrder best; + for (idx_t root = 0; root < graph.relation_manager.NumRelations(); root++) { + auto candidate = GetOrder(RelationIndex(root)); + if (!candidate.relations.empty() && (best.relations.empty() || candidate.log_cost < best.log_cost)) { + best = std::move(candidate); + } + } + return std::move(best.relations); +} + +} // namespace duckdb diff --git a/src/duckdb/src/optimizer/join_order/join_order_rank.cpp b/src/duckdb/src/optimizer/join_order/join_order_rank.cpp new file mode 100644 index 000000000..458ea3bff --- /dev/null +++ b/src/duckdb/src/optimizer/join_order/join_order_rank.cpp @@ -0,0 +1,56 @@ +#include "duckdb/optimizer/join_order/join_order_rank.hpp" + +#include +#include + +namespace duckdb { + +JoinOrderRank::JoinOrderRank(double log_multiplier) : log_multiplier(log_multiplier), log_work(log_multiplier) { + D_ASSERT(!std::isnan(log_multiplier)); +} + +double JoinOrderRank::AddLogValues(double left, double right) { + if (left < right) { + std::swap(left, right); + } + if (left == -std::numeric_limits::infinity()) { + return left; + } + return left + std::log1p(std::exp(right - left)); +} + +void JoinOrderRank::Append(const JoinOrderRank &other) { + log_work = AddLogValues(log_work, log_multiplier + other.log_work); + log_multiplier += other.log_multiplier; +} + +void JoinOrderRank::AddIndependentWork(double work) { + log_work = AddLogValues(log_work, work); +} + +int32_t JoinOrderRank::Sign() const { + return log_multiplier < 0 ? -1 : log_multiplier > 0 ? 1 : 0; +} + +double JoinOrderRank::LogMagnitude() const { + if (log_multiplier < 0) { + return std::log(-std::expm1(log_multiplier)) - log_work; + } + return log_multiplier + std::log(-std::expm1(-log_multiplier)) - log_work; +} + +bool JoinOrderRank::operator<(const JoinOrderRank &other) const { + auto sign = Sign(); + auto other_sign = other.Sign(); + if (sign != other_sign) { + return sign < other_sign; + } + if (sign == 0) { + return false; + } + auto magnitude = LogMagnitude(); + auto other_magnitude = other.LogMagnitude(); + return sign < 0 ? magnitude > other_magnitude : magnitude < other_magnitude; +} + +} // namespace duckdb diff --git a/src/duckdb/src/optimizer/join_order/join_relation_set.cpp b/src/duckdb/src/optimizer/join_order/join_relation_set.cpp index d733c0ae8..63ccb9b7c 100644 --- a/src/duckdb/src/optimizer/join_order/join_relation_set.cpp +++ b/src/duckdb/src/optimizer/join_order/join_relation_set.cpp @@ -2,18 +2,18 @@ #include "duckdb/common/printer.hpp" #include "duckdb/common/string_util.hpp" #include "duckdb/common/to_string.hpp" +#include "duckdb/common/types/hash.hpp" #include namespace duckdb { -using JoinRelationTreeNode = JoinRelationSetManager::JoinRelationTreeNode; - static constexpr idx_t BITMASK_WORD_SIZE = sizeof(idx_t) * 8; JoinRelationSet::JoinRelationSet(unsafe_unique_array relations, idx_t count) : relations(std::move(relations)), count(count) { if (count != 0) { + first_word = this->relations[0].index / BITMASK_WORD_SIZE; // the relations are sorted, so the last one determines the number of words bitmask.resize(this->relations[count - 1].index / BITMASK_WORD_SIZE + 1, 0); for (idx_t i = 0; i < count; i++) { @@ -43,7 +43,7 @@ bool JoinRelationSet::IsSubset(const JoinRelationSet &super, const JoinRelationS if (sub.count > super.count || sub.bitmask.size() > super.bitmask.size()) { return false; } - for (idx_t i = 0; i < sub.bitmask.size(); i++) { + for (idx_t i = sub.first_word; i < sub.bitmask.size(); i++) { if (sub.bitmask[i] & ~super.bitmask[i]) { return false; } @@ -62,24 +62,22 @@ bool JoinRelationSet::Intersects(const JoinRelationSet &left, const JoinRelation } JoinRelationSet &JoinRelationSetManager::GetJoinRelation(unsafe_unique_array relations, idx_t count) { - // now look it up in the tree - reference info(root); + hash_t hash = 0; for (idx_t i = 0; i < count; i++) { - auto entry = info.get().children.find(relations[i]); - if (entry == info.get().children.end()) { - // node not found, create it - auto insert_it = info.get().children.insert(make_pair(relations[i], make_uniq())); - entry = insert_it.first; - } - // move to the next node - info = *entry->second; + hash = CombineHash(hash, Hash(relations[i].index)); } - // now check if the JoinRelationSet has already been created - if (!info.get().relation) { - // if it hasn't we need to create it - info.get().relation = make_uniq(std::move(relations), count); + auto entries = relation_sets.equal_range(hash); + for (auto entry = entries.first; entry != entries.second; ++entry) { + auto &set = *entry->second; + if (set.count != count) { + continue; + } + if (count == 0 || std::equal(relations.get(), relations.get() + count, set.relations.get())) { + return set; + } } - return *info.get().relation; + auto entry = relation_sets.emplace(hash, make_uniq(std::move(relations), count)); + return *entry->second; } //! Create or get a JoinRelationSet from a single node with the given index @@ -179,21 +177,14 @@ JoinRelationSet &JoinRelationSetManager::Difference(const JoinRelationSet &left, return GetJoinRelation(std::move(relations), count); } -static string JoinRelationTreeNodeToString(const JoinRelationTreeNode *node) { - string result = ""; - if (node->relation) { - result += node->relation.get()->ToString() + "\n"; - } - for (auto &child : node->children) { - result += JoinRelationTreeNodeToString(child.second.get()); +string JoinRelationSetManager::ToString() const { + string result; + for (auto &entry : relation_sets) { + result += entry.second->ToString() + "\n"; } return result; } -string JoinRelationSetManager::ToString() const { - return JoinRelationTreeNodeToString(&root); -} - void JoinRelationSetManager::Print() { Printer::Print(ToString()); } diff --git a/src/duckdb/src/optimizer/join_order/linearized_plan_enumerator.cpp b/src/duckdb/src/optimizer/join_order/linearized_plan_enumerator.cpp new file mode 100644 index 000000000..1a73dbb95 --- /dev/null +++ b/src/duckdb/src/optimizer/join_order/linearized_plan_enumerator.cpp @@ -0,0 +1,175 @@ +#include "duckdb/optimizer/join_order/linearized_plan_enumerator.hpp" + +#include "duckdb/main/client_context.hpp" +#include "duckdb/optimizer/join_order/greedy_join_enumerator.hpp" +#include "duckdb/optimizer/join_order/join_order_linearizer.hpp" +#include "duckdb/optimizer/join_order/join_order_precedence.hpp" +#include "duckdb/optimizer/join_order/query_graph_manager.hpp" + +namespace duckdb { + +IntervalJoinEnumerator::IntervalJoinEnumerator(QueryGraphManager &graph, JoinOrderCandidateEvaluator &evaluator, + const JoinOrderPlanMap &inputs) + : query_graph_manager(graph), evaluator(evaluator), plans(CopyJoinOrderLeafPlans(inputs)) { +} + +const JoinOrderPlanMap &IntervalJoinEnumerator::GetPlans() const { + return plans; +} + +LinearizedPlanEnumerator::LinearizedPlanEnumerator(QueryGraphManager &graph, CostModel &cost_model, + JoinOrderCandidateEvaluator &evaluator) + : query_graph_manager(graph), cost_model(cost_model), evaluator(evaluator) { +} + +bool LinearizedPlanEnumerator::SolveGreedy(JoinOrderPlanMap &plans) { + evaluator.InitInputPlan(plans); + GreedyJoinEnumerator greedy(query_graph_manager, evaluator); + return greedy.Solve(plans); +} + +unique_ptr LinearizedPlanEnumerator::CaptureInputPlan(JoinOrderPlanMap &plans, + JoinRelationSet &root) { + evaluator.InitInputPlan(plans); + if (plans.find(root) == plans.end()) { + return nullptr; + } + return CapturedJoinOrderPlan::Capture(plans, root, cost_model); +} + +unique_ptr LinearizedPlanEnumerator::CaptureGreedyPlan(JoinOrderPlanMap &plans, + JoinRelationSet &root) { + GreedyJoinEnumerator greedy(query_graph_manager, evaluator); + if (!greedy.Solve(plans)) { + return nullptr; + } + return CapturedJoinOrderPlan::Capture(plans, root, cost_model); +} + +void LinearizedPlanEnumerator::OfferPlan(JoinRelationSet &root, unique_ptr candidate, + unique_ptr &incumbent) { + if (&candidate->GetRoot() != &root || (incumbent && &incumbent->GetRoot() != &root)) { + throw InternalException("Join-order incumbent root does not match the search region"); + } + if (!incumbent || evaluator.PreferPlan(candidate->GetRootNode(), candidate->GetPlans(), incumbent->GetRootNode(), + incumbent->GetPlans())) { + incumbent = std::move(candidate); + } +} + +bool IntervalJoinEnumerator::Solve(const vector &order) { + auto count = order.size(); + D_ASSERT(count > 0); + // Each trial starts with the same immutable leaves. In particular, a winner from another order may not + // replace an interval's child after its parent has been costed. + vector>> intervals(count); + for (idx_t start = 0; start < count; start++) { + intervals[start].resize(count - start); + intervals[start][0] = query_graph_manager.set_manager.GetJoinRelation(order[start]); + } + for (idx_t length = 2; length <= count; length++) { + for (idx_t start = 0; start + length <= count; start++) { + query_graph_manager.context.InterruptCheck(); + auto &set = + query_graph_manager.set_manager.Union(*intervals[start][length - 2], *intervals[start + length - 1][0]); + intervals[start][length - 1] = set; + } + } + for (idx_t length = 2; length <= count; length++) { + for (idx_t start = 0; start + length <= count; start++) { + auto &set = *intervals[start][length - 1]; + for (idx_t split = 1; split < length; split++) { + query_graph_manager.context.InterruptCheck(); + auto &left = *intervals[start][split - 1]; + auto &right = *intervals[start + split][length - split - 1]; + auto left_plan = plans.find(left); + auto right_plan = plans.find(right); + if (left_plan == plans.end() || right_plan == plans.end()) { + continue; + } + auto incumbent = plans.find(set); + if (incumbent != plans.end() && + !evaluator.CanImprovePair(plans, *left_plan->second, *right_plan->second, *incumbent->second)) { + continue; + } + // A trial visits each ordered pair once; do not retain a cubic connection cache. + auto &edges = query_graph_manager.GetQueryGraphEdges(); + evaluator.EmitPair(plans, set, left, right, edges.GetConnections(left, right)); + evaluator.EmitPair(plans, set, right, left, edges.GetConnections(right, left)); + } + } + } + return plans.find(*intervals[0][count - 1]) != plans.end(); +} + +bool LinearizedPlanEnumerator::SolveApproximately(JoinOrderPlanMap &plans) { + // Larger regions need subtree refinement rather than a full cubic pass. + if (query_graph_manager.relation_manager.NumRelations() > 32) { + return SolveGreedy(plans); + } + JoinOrderLinearizer linearizer(query_graph_manager, cost_model.GetCardinalityEstimator()); + auto ordinary = linearizer.BuildTree(); + unordered_set bindings; + for (idx_t i = 0; i < query_graph_manager.relation_manager.NumRelations(); i++) { + bindings.emplace(i); + } + auto &root = query_graph_manager.set_manager.GetJoinRelation(bindings); + unique_ptr incumbent; + if (plans.find(root) != plans.end()) { + OfferPlan(root, CapturedJoinOrderPlan::Capture(plans, root, cost_model), incumbent); + } + // Partial exact nodes may have stale ancestor costs. Each new search starts from immutable leaves. + plans = CopyJoinOrderLeafPlans(plans); + evaluator.ResetConnectionCache(); + unique_ptr input_plan, greedy_plan; + bool greedy_ran = false; + vector order; + if (ordinary) { + order = linearizer.GetBestOrder(); + } else { + input_plan = CaptureInputPlan(plans, root); + optional_ptr witness = input_plan ? input_plan.get() : incumbent.get(); + if (!witness) { + // Some input trees need cross-product activation before a complete witness is available. + greedy_ran = true; + greedy_plan = CaptureGreedyPlan(plans, root); + plans = CopyJoinOrderLeafPlans(plans); + input_plan = CaptureInputPlan(plans, root); + witness = input_plan ? input_plan.get() : greedy_plan.get(); + } + if (!witness) { + return false; + } + JoinOrderPrecedence precedence(query_graph_manager, cost_model.GetCardinalityEstimator(), evaluator, *witness); + order = precedence.GetBestOrder(); + if (order.empty()) { + order = witness->GetLeafOrder(); + } + } + { + IntervalJoinEnumerator trial(query_graph_manager, evaluator, plans); + if (trial.Solve(order)) { + OfferPlan(root, CapturedJoinOrderPlan::Capture(trial.GetPlans(), root, cost_model), incumbent); + } + } + if (ordinary) { + input_plan = CaptureInputPlan(plans, root); + } + if (input_plan) { + OfferPlan(root, std::move(input_plan), incumbent); + } + // Greedy explores different bushy plans. Compare complete candidates without mixing their memos. + if (!greedy_ran) { + greedy_plan = CaptureGreedyPlan(plans, root); + } + if (greedy_plan) { + OfferPlan(root, std::move(greedy_plan), incumbent); + } + if (!incumbent) { + return false; + } + plans = incumbent->TakePlans(); + return true; +} + +} // namespace duckdb diff --git a/src/duckdb/src/optimizer/join_order/plan_enumerator.cpp b/src/duckdb/src/optimizer/join_order/plan_enumerator.cpp index b1eb41535..207e571c6 100644 --- a/src/duckdb/src/optimizer/join_order/plan_enumerator.cpp +++ b/src/duckdb/src/optimizer/join_order/plan_enumerator.cpp @@ -2,13 +2,14 @@ #include "duckdb/main/settings.hpp" #include "duckdb/optimizer/join_order/dphyp_enumerator.hpp" -#include "duckdb/optimizer/join_order/greedy_join_enumerator.hpp" +#include "duckdb/optimizer/join_order/linearized_plan_enumerator.hpp" #include "duckdb/optimizer/join_order/query_graph_manager.hpp" namespace duckdb { PlanEnumerator::PlanEnumerator(QueryGraphManager &graph, CostModel &cost_model, const QueryGraphEdges &edges) - : query_graph_manager(graph), query_graph(edges), candidate_evaluator(graph, cost_model, edges) { + : query_graph_manager(graph), cost_model(cost_model), query_graph(edges), + candidate_evaluator(graph, cost_model, edges) { } const JoinOrderPlanMap &PlanEnumerator::GetPlans() const { @@ -16,13 +17,12 @@ const JoinOrderPlanMap &PlanEnumerator::GetPlans() const { } void PlanEnumerator::InitLeafPlans() { - candidate_evaluator.InitLeafPlans(plans); + candidate_evaluator.InitLeafPlans(plans, query_graph_manager.relation_manager.GetRelationStats()); } bool PlanEnumerator::SolveJoinOrderApproximately() { - candidate_evaluator.InitInputPlan(plans); - GreedyJoinEnumerator greedy(query_graph_manager, candidate_evaluator); - return greedy.Solve(plans); + LinearizedPlanEnumerator linearized(query_graph_manager, cost_model, candidate_evaluator); + return linearized.SolveApproximately(plans); } bool PlanEnumerator::HasCompletePlan(const JoinOrderPlanMap &memo) const { diff --git a/src/duckdb/src/optimizer/join_order/query_graph.cpp b/src/duckdb/src/optimizer/join_order/query_graph.cpp index cd207c0b0..93b71fffe 100644 --- a/src/duckdb/src/optimizer/join_order/query_graph.cpp +++ b/src/duckdb/src/optimizer/join_order/query_graph.cpp @@ -63,6 +63,7 @@ void QueryGraphEdges::CreateEdge(JoinRelationSet &left, JoinRelationSet &right, D_ASSERT(left.count > 0 && right.count > 0); // find the EdgeInfo corresponding to the left set auto info = GetQueryEdge(left); + info->relations = left; // now insert the edge to the right relation, if it does not exist for (idx_t i = 0; i < info->neighbors.size(); i++) { if (info->neighbors[i]->neighbor == right && info->neighbors[i]->join_operator == join_operator && @@ -82,6 +83,23 @@ void QueryGraphEdges::CreateEdge(JoinRelationSet &left, JoinRelationSet &right, info->neighbors.push_back(std::move(n)); } +void QueryGraphEdges::EnumerateEdges(const std::function &callback) const { + vector> pending {root}; + while (!pending.empty()) { + auto &edge = pending.back().get(); + pending.pop_back(); + for (auto &neighbor : edge.neighbors) { + D_ASSERT(edge.relations); + if (callback(*edge.relations.get_mutable(), *neighbor)) { + return; + } + } + for (auto &child : edge.children) { + pending.push_back(*child.second); + } + } +} + void QueryGraphEdges::EnumerateNeighborsDFS(JoinRelationSet &node, reference info, idx_t index, const std::function &callback) const { for (auto &neighbor : info.get().neighbors) { diff --git a/src/duckdb/src/optimizer/join_order/query_graph_manager.cpp b/src/duckdb/src/optimizer/join_order/query_graph_manager.cpp index ae4b8cad4..d7fad5332 100644 --- a/src/duckdb/src/optimizer/join_order/query_graph_manager.cpp +++ b/src/duckdb/src/optimizer/join_order/query_graph_manager.cpp @@ -308,7 +308,12 @@ void QueryGraphManager::PreparePredicateModel(LogicalOperator &op) { filters_and_bindings = std::move(extraction.filters); join_operators = std::move(extraction.join_operators); JoinOrderConflictDetector::Build(join_operators, set_manager, relation_manager.relation_mapping); + candidate_constraints.clear(); for (auto &join_operator : join_operators) { + if (join_operator->type == JoinOrderOperatorType::CROSS_PRODUCT || + JoinOrderConflictDetector::MustApplyAsOperator(*join_operator)) { + candidate_constraints.push_back(*join_operator); + } for (auto predicate_index : join_operator->costing_predicate_indices) { filters_and_bindings[predicate_index]->semantic_left_set = optional_ptr(join_operator->left_total_set.get()); @@ -662,6 +667,35 @@ void QueryGraphManager::ClearExtractedExpressions() { } } +vector> QueryGraphManager::GetPendingFilters(JoinRelationSet &root) const { + vector assigned(filters_and_bindings.size(), false); + vector> pending {root}; + while (!pending.empty()) { + auto &set = pending.back().get(); + pending.pop_back(); + auto entry = plans->find(set); + if (entry == plans->end()) { + throw InternalException("Join Order Optimizer Error: No full plan was created"); + } + auto &node = *entry->second; + for (auto &predicate : node.predicates) { + assigned[predicate.get().GetIndex()] = true; + } + if (!node.is_leaf) { + pending.push_back(node.left_set); + pending.push_back(node.right_set); + } + } + vector> result; + for (auto &filter : filters_and_bindings) { + // Selected join conditions are consumed by their assigned node, not by filter pushdown. + if (!assigned[filter->filter_index] && !operator_costing_predicates.count(filter->filter_index)) { + result.push_back(*filter); + } + } + return result; +} + GenerateJoinRelation QueryGraphManager::Reconstruct(unique_ptr plan, const vector &relation_stats) { // now we have to rewrite the plan @@ -699,7 +733,8 @@ GenerateJoinRelation QueryGraphManager::Reconstruct(unique_ptr } // now we generate the actual joins - auto join_tree = GenerateJoins(extracted_relations, total_relation, relation_stats); + auto pending_filters = GetPendingFilters(total_relation); + auto join_tree = GenerateJoins(extracted_relations, total_relation, relation_stats, pending_filters); for (auto &join_operator : join_operators) { if (JoinOrderConflictDetector::MustApplyAsOperator(*join_operator) && !reconstructed_operators.count(join_operator->index)) { @@ -792,6 +827,8 @@ static JoinType GetJoinType(JoinOrderOperatorType type) { return JoinType::SEMI; case JoinOrderOperatorType::ANTI: return JoinType::ANTI; + case JoinOrderOperatorType::MARK: + return JoinType::MARK; default: throw InternalException("Operator occurrence type %d has no comparison join type", static_cast(type)); } @@ -820,8 +857,8 @@ static void OrientInnerConditions(RelationManager &relation_manager, JoinRelatio } GenerateJoinRelation QueryGraphManager::GenerateJoins(vector> &extracted_relations, - JoinRelationSet &set, - const vector &relation_stats) { + JoinRelationSet &set, const vector &relation_stats, + const vector> &pending_filters) { optional_ptr left_node; optional_ptr right_node; optional_ptr result_relation; @@ -836,8 +873,8 @@ GenerateJoinRelation QueryGraphManager::GenerateJoins(vectorcardinality.GetIndex(); if (!dp_entry->second->is_leaf) { // generate the left and right children - auto left = GenerateJoins(extracted_relations, node->left_set, relation_stats); - auto right = GenerateJoins(extracted_relations, node->right_set, relation_stats); + auto left = GenerateJoins(extracted_relations, node->left_set, relation_stats, pending_filters); + auto right = GenerateJoins(extracted_relations, node->right_set, relation_stats, pending_filters); auto descriptor = node->join_operator; if (descriptor) { D_ASSERT(descriptor->type == JoinOrderOperatorType::CROSS_PRODUCT || @@ -876,6 +913,8 @@ GenerateJoinRelation QueryGraphManager::GenerateJoins(vector(GetJoinType(descriptor->type)); + join->mark_index = descriptor->mark_index; + join->mark_types = std::move(descriptor->mark_types); join->children.push_back(std::move(left.op)); join->children.push_back(std::move(right.op)); join->conditions = std::move(descriptor->conditions); @@ -943,10 +982,16 @@ GenerateJoinRelation QueryGraphManager::GenerateJoins(vector> child_stats {left.stats, right.stats}; if (result_operator->type == LogicalOperatorType::LOGICAL_COMPARISON_JOIN && (result_operator->Cast().join_type == JoinType::SEMI || + result_operator->Cast().join_type == JoinType::MARK || result_operator->Cast().join_type == JoinType::ANTI)) { result_stats = RelationStatisticsHelper::ExtractOperatorStats(*result_operator, context, child_stats); if (result_stats) { - result_cardinality = result_stats->cardinality; + if (result_operator->Cast().join_type == JoinType::MARK) { + result_stats->cardinality = result_cardinality; + result_stats->CapCurrentDomainsToCardinality(); + } else { + result_cardinality = result_stats->cardinality; + } } } else { result_stats = CombineRelationStats(result_operator->GetColumnBindings(), child_stats, result_cardinality); @@ -971,11 +1016,11 @@ GenerateJoinRelation QueryGraphManager::GenerateJoins(vector> unused_residual_predicates; - for (auto &filter_info : filters_and_bindings) { - if (filter_info->from_residual_predicate && filters_and_bindings[filter_info->filter_index]->filter && - !operator_costing_predicates.count(filter_info->filter_index) && filter_info->set.get().count > 0 && - JoinRelationSet::IsSubset(*result_relation, filter_info->set)) { - unused_residual_predicates.push_back(std::move(filters_and_bindings[filter_info->filter_index]->filter)); + for (auto &filter_ref : pending_filters) { + auto &filter = filter_ref.get(); + if (filter.from_residual_predicate && filter.filter && filter.set.get().count > 0 && + JoinRelationSet::IsSubset(*result_relation, filter.set)) { + unused_residual_predicates.push_back(std::move(filter.filter)); } } if (!unused_residual_predicates.empty()) { @@ -995,12 +1040,9 @@ GenerateJoinRelation QueryGraphManager::GenerateJoins(vectorfilter) { if (info.from_residual_predicate) { continue; @@ -1211,6 +1253,9 @@ bool QueryGraphManager::IsJoinOrderCandidate(optional_ptr sel if (generated_cross_product && !CanCreateCrossProduct(left, right)) { return false; } + if (!selected_operator && candidate_constraints.empty()) { + return true; + } auto &combined = set_manager.Union(left, right); if (selected_operator && (!JoinOrderConflictDetector::IsApplicable(*selected_operator, left, right) || JoinOrderConflictDetector::IsCompletedBy(*selected_operator, left) || @@ -1218,8 +1263,8 @@ bool QueryGraphManager::IsJoinOrderCandidate(optional_ptr sel !JoinOrderConflictDetector::IsCompletedBy(*selected_operator, combined))) { return false; } - for (auto &operator_ptr : join_operators) { - auto &op = *operator_ptr; + for (auto &constraint : candidate_constraints) { + auto &op = constraint.get(); if (JoinOrderConflictDetector::IsCompletedBy(op, left) || JoinOrderConflictDetector::IsCompletedBy(op, right) || !JoinOrderConflictDetector::IsCompletedBy(op, combined)) { continue; @@ -1228,7 +1273,7 @@ bool QueryGraphManager::IsJoinOrderCandidate(optional_ptr sel if (!JoinOrderConflictDetector::IsApplicable(op, left, right)) { return false; } - } else if (JoinOrderConflictDetector::MustApplyAsOperator(op) && selected_operator != &op) { + } else if (selected_operator.get() != &op) { return false; } } diff --git a/src/duckdb/src/optimizer/join_order/relation_manager.cpp b/src/duckdb/src/optimizer/join_order/relation_manager.cpp index 15b318b20..cdec24fa5 100644 --- a/src/duckdb/src/optimizer/join_order/relation_manager.cpp +++ b/src/duckdb/src/optimizer/join_order/relation_manager.cpp @@ -15,6 +15,7 @@ #include "duckdb/planner/joinside.hpp" #include "duckdb/planner/operator/list.hpp" #include "duckdb/planner/expression/bound_comparison_expression.hpp" +#include "duckdb/planner/subquery/has_volatile_expressions.hpp" namespace duckdb { @@ -395,7 +396,7 @@ static bool ContainsRecurringCTERef(const LogicalOperator &op) { return false; } -static bool JoinIsReorderable(LogicalOperator &op) { +static bool JoinIsReorderable(LogicalOperator &op, bool has_throwing_predicate) { if (op.type == LogicalOperatorType::LOGICAL_CROSS_PRODUCT) { return true; } @@ -405,6 +406,20 @@ static bool JoinIsReorderable(LogicalOperator &op) { if (join.HasProjectionMap()) { return false; } + if (join.join_type == JoinType::MARK) { + // Opening this boundary must not expose an ancestor's throwing predicate to additional rows. + if (has_throwing_predicate || !join.duplicate_eliminated_columns.empty() || join.filter_pushdown || + HasVolatileExpressionsIgnoringError(join)) { + return false; + } + for (auto &condition : join.conditions) { + if (!condition.IsComparison() || condition.GetLHS().CanThrow() || condition.GetRHS().CanThrow() || + !ExpressionContainsColumnRef(condition.GetLHS()) || + !ExpressionContainsColumnRef(condition.GetRHS())) { + return false; + } + } + } // Keep constant membership filters local instead of expanding the join search. if (join.join_type == JoinType::SEMI || join.join_type == JoinType::ANTI) { optional_ptr rhs = join.children[1].get(); @@ -433,6 +448,7 @@ static bool JoinIsReorderable(LogicalOperator &op) { case JoinType::SEMI: case JoinType::LEFT: case JoinType::ANTI: + case JoinType::MARK: for (auto &cond : join.conditions) { if (cond.IsComparison() && ExpressionContainsColumnRef(cond.GetLHS()) && ExpressionContainsColumnRef(cond.GetRHS())) { @@ -555,7 +571,7 @@ bool RelationManager::ExtractJoinRelations(JoinOrderOptimizer &optimizer, Logica active_recursive_ctes = optimizer.recursive_cte_indexes; // Keep the join-region walk off the call stack: leaf extraction has a substantial frame, and generated // plans (e.g. many DISTINCT aggregates) can contain hundreds of nested binary joins. - vector pending_relations {{input_op, parent, false}}; + vector pending_relations {{input_op, parent, false, false}}; bool can_reorder = true; while (!pending_relations.empty()) { auto relation = pending_relations.back(); @@ -586,11 +602,15 @@ bool RelationManager::ExtractJoinRelation(JoinOrderOptimizer &optimizer, Pending auto parent = relation.parent; optional_ptr op = &input_op; vector> unary_filters; + auto has_throwing_predicate = relation.has_throwing_predicate; // pass through single child operators (but never past a non-reorderable op such as a DML node, which // must be preserved as its own relation rather than skipped over and dropped during reconstruction) while (op->children.size() == 1 && !OperatorNeedsRelation(op->type) && !OperatorIsNonReorderable(*op)) { if (op->type == LogicalOperatorType::LOGICAL_FILTER) { unary_filters.push_back(*op); + for (auto &expression : op->expressions) { + has_throwing_predicate |= expression->CanThrow(); + } } op = op->children[0].get(); } @@ -603,7 +623,7 @@ bool RelationManager::ExtractJoinRelation(JoinOrderOptimizer &optimizer, Pending } // Filters inside a leaf are already priced by its statistics and stay with that relation. - if (JoinIsReorderable(*op)) { + if (JoinIsReorderable(*op, has_throwing_predicate)) { filter_operators.insert(filter_operators.end(), unary_filters.begin(), unary_filters.end()); if (op->type == LogicalOperatorType::LOGICAL_COMPARISON_JOIN) { filter_operators.push_back(*op); @@ -705,17 +725,22 @@ bool RelationManager::ExtractJoinRelation(JoinOrderOptimizer &optimizer, Pending } case LogicalOperatorType::LOGICAL_COMPARISON_JOIN: { auto &join = op->Cast(); - // SEMI/ANTI and LEFT RHS subtrees stay independent relations. Process the left subtree first, + for (auto &condition : join.conditions) { + has_throwing_predicate |= condition.IsComparison() + ? condition.GetLHS().CanThrow() || condition.GetRHS().CanThrow() + : condition.GetJoinExpression().CanThrow(); + } + // Non-inner RHS subtrees stay independent relations. Process the left subtree first, // then optimize/register the RHS, just as for the recursive traversal. - auto separate_rhs = - join.join_type == JoinType::SEMI || join.join_type == JoinType::ANTI || join.join_type == JoinType::LEFT; - pending_relations.push_back({*op->children[1], op, separate_rhs}); - pending_relations.push_back({*op->children[0], op, false}); + auto separate_rhs = join.join_type == JoinType::SEMI || join.join_type == JoinType::ANTI || + join.join_type == JoinType::LEFT || join.join_type == JoinType::MARK; + pending_relations.push_back({*op->children[1], op, separate_rhs, has_throwing_predicate}); + pending_relations.push_back({*op->children[0], op, false, has_throwing_predicate}); return true; } case LogicalOperatorType::LOGICAL_CROSS_PRODUCT: { - pending_relations.push_back({*op->children[1], op, false}); - pending_relations.push_back({*op->children[0], op, false}); + pending_relations.push_back({*op->children[1], op, false, has_throwing_predicate}); + pending_relations.push_back({*op->children[0], op, false, has_throwing_predicate}); return true; } case LogicalOperatorType::LOGICAL_DUMMY_SCAN: { @@ -1001,6 +1026,11 @@ bool RelationManager::ExtractBindings(const Expression &expression, unordered_se auto &colref = expression.Cast(); D_ASSERT(colref.Depth() == 0); D_ASSERT(colref.Binding().table_index.IsValid()); + auto marker = marker_dependencies.find(colref.Binding().table_index); + if (marker != marker_dependencies.end()) { + bindings.insert(marker->second.begin(), marker->second.end()); + return true; + } // map the base table index to the relation index used by the JoinOrderOptimizer if (expression.GetAlias() == "SUBQUERY" && relation_mapping.find(colref.Binding().table_index) == relation_mapping.end()) { @@ -1049,6 +1079,27 @@ JoinOrderExtraction RelationManager::ExtractEdges(LogicalOperator &op, auto &join_operators = result.join_operators; reference_map_t> operator_predicates; reference_map_t> operator_conditions; + for (auto entry = filter_operators.rbegin(); entry != filter_operators.rend(); ++entry) { + auto ¤t = entry->get(); + if (current.type != LogicalOperatorType::LOGICAL_COMPARISON_JOIN) { + continue; + } + auto &join = current.Cast(); + if (join.join_type != JoinType::MARK) { + continue; + } + auto rhs = operator_relations.at(*join.children[1]); + unordered_set dependencies {rhs}; + for (auto &condition : join.conditions) { + ExtractBindings(condition.GetLHS(), dependencies); + } + marker_dependencies.emplace(join.mark_index, std::move(dependencies)); + relation_mapping.emplace(join.mark_index, rhs); + // The marker is produced by the join, after the RHS's own columns. + normalized_bindings.emplace( + ColumnBinding(join.mark_index, ProjectionIndex(0)), + ColumnBinding(TableIndex(rhs.index), ProjectionIndex(relations[rhs.index]->stats.columns.size()))); + } expression_set_t filter_set; // two equal volatile filters are two evaluations, so neither is a duplicate of the other auto is_new_filter = [&](const Expression &expr) { @@ -1115,6 +1166,7 @@ JoinOrderExtraction RelationManager::ExtractEdges(LogicalOperator &op, D_ASSERT(join.expressions.empty()); switch (join.join_type) { case JoinType::SEMI: + case JoinType::MARK: case JoinType::ANTI: { column_binding_set_t semantic_left_bindings; column_binding_set_t semantic_right_bindings; @@ -1299,6 +1351,9 @@ JoinOrderExtraction RelationManager::ExtractEdges(LogicalOperator &op, case JoinType::ANTI: operator_type = JoinOrderOperatorType::ANTI; break; + case JoinType::MARK: + operator_type = JoinOrderOperatorType::MARK; + break; default: throw InternalException("Unexpected reorderable join type %s", EnumUtil::ToChars(join.join_type)); } @@ -1326,6 +1381,11 @@ JoinOrderExtraction RelationManager::ExtractEdges(LogicalOperator &op, } auto descriptor = make_uniq(join_operators.size(), operator_type, left.relations, right.relations, syntactic_set, std::move(conditions)); + if (operator_type == JoinOrderOperatorType::MARK) { + auto &join = current.Cast(); + descriptor->mark_index = join.mark_index; + descriptor->mark_types = join.mark_types; + } descriptor->left_operators = left.operators; descriptor->right_operators = right.operators; descriptor->costing_predicate_indices = std::move(predicate_indices); diff --git a/src/duckdb/src/optimizer/join_simplification.cpp b/src/duckdb/src/optimizer/join_simplification.cpp index 5375a126f..e9aa75d25 100644 --- a/src/duckdb/src/optimizer/join_simplification.cpp +++ b/src/duckdb/src/optimizer/join_simplification.cpp @@ -124,7 +124,12 @@ void JoinSimplification::AddRequiredColumns(const vector &conditi bool JoinSimplification::GetColumnBinding(const Expression &expr, ColumnBinding &binding) { if (expr.GetExpressionClass() != ExpressionClass::BOUND_COLUMN_REF) { if (!BoundCastExpression::IsCast(expr)) { - return false; + // a unary function that propagates NULLs (e.g. encode) is only non-NULL if its input is + if (expr.GetExpressionClass() != ExpressionClass::BOUND_FUNCTION || !expr.PropagatesNullValues()) { + return false; + } + auto &func = expr.Cast(); + return func.GetChildren().size() == 1 && GetColumnBinding(*func.GetChildren()[0], binding); } auto &cast = expr.Cast(); return GetColumnBinding(BoundCastExpression::Child(cast), binding); @@ -375,14 +380,15 @@ void JoinSimplification::VisitJoinChildren(LogicalOperator &op, bool left_ignore return; } // the column sets do not pass through this join: each child starts with all of its columns required - for (idx_t child_idx = 0; child_idx < 2; child_idx++) { + auto visit_child = [&](idx_t child_idx, ParentInfo info) { column_binding_set_t child_required_columns; for (const auto &binding : op.children[child_idx]->GetColumnBindings()) { child_required_columns.insert(binding); } - VisitChildInNewContext(op, child_idx, std::move(child_required_columns), - child_idx == 0 ? std::move(left_info) : std::move(right_info)); - } + VisitChildInNewContext(op, child_idx, std::move(child_required_columns), std::move(info)); + }; + visit_child(0, std::move(left_info)); + visit_child(1, std::move(right_info)); } void JoinSimplification::VisitComparisonJoin(LogicalComparisonJoin &join, unique_ptr &op_ptr) { diff --git a/src/duckdb/src/optimizer/late_materialization.cpp b/src/duckdb/src/optimizer/late_materialization.cpp index 345159652..450d2f8f9 100644 --- a/src/duckdb/src/optimizer/late_materialization.cpp +++ b/src/duckdb/src/optimizer/late_materialization.cpp @@ -65,8 +65,10 @@ vector LateMaterialization::ConstructRHS(unique_ptr(); // column bindings pass-through this operator as-is UNLESS the filter has a projection map if (filter.HasProjectionMap()) { - // if the filter has a projection map, we need to project the new column - filter.projection_map.emplace_back(column_count - 1); + // if the filter has a projection map, we need to project all of the new row-id columns + for (idx_t r_idx = 0; r_idx < row_id_columns.size(); r_idx++) { + filter.projection_map.emplace_back(column_count - row_id_columns.size() + r_idx); + } column_count = filter.projection_map.size(); } break; diff --git a/src/duckdb/src/optimizer/mark_join_simplifier.cpp b/src/duckdb/src/optimizer/mark_join_simplifier.cpp index 5efb67118..7f1c16dc1 100644 --- a/src/duckdb/src/optimizer/mark_join_simplifier.cpp +++ b/src/duckdb/src/optimizer/mark_join_simplifier.cpp @@ -1,5 +1,6 @@ #include "duckdb/optimizer/mark_join_simplifier.hpp" +#include "duckdb/common/assert.hpp" #include "duckdb/execution/expression_executor.hpp" #include "duckdb/optimizer/column_binding_replacer.hpp" #include "duckdb/optimizer/optimizer.hpp" @@ -13,6 +14,7 @@ #include "duckdb/planner/expression_iterator.hpp" #include "duckdb/planner/expression_nullability.hpp" #include "duckdb/planner/logical_operator_visitor.hpp" +#include "duckdb/planner/joinside.hpp" #include "duckdb/planner/operator/logical_comparison_join.hpp" #include "duckdb/planner/operator/logical_filter.hpp" #include "duckdb/planner/operator/logical_projection.hpp" @@ -24,6 +26,136 @@ namespace duckdb { MarkJoinSimplifier::MarkJoinSimplifier(Optimizer &optimizer) : optimizer(optimizer) { } +static bool IsConstantInputComparisonOptimizable(const JoinCondition &condition) { + if (!condition.IsComparison() || condition.GetRHS().IsVolatile()) { + return false; + } + // A NULL-only hash build can skip evaluating the probe expression. + if (condition.GetLHS().IsVolatile() || condition.GetLHS().CanThrow()) { + return false; + } + + const auto comparison_type = condition.GetComparisonType(); + if ((condition.GetLHS().GetReturnType().id() == LogicalTypeId::TUPLE || + condition.GetRHS().GetReturnType().id() == LogicalTypeId::TUPLE) && + comparison_type == ExpressionType::COMPARE_NOTEQUAL) { + return false; + } + + switch (comparison_type) { + case ExpressionType::COMPARE_EQUAL: + case ExpressionType::COMPARE_NOTEQUAL: + case ExpressionType::COMPARE_LESSTHAN: + case ExpressionType::COMPARE_GREATERTHAN: + case ExpressionType::COMPARE_LESSTHANOREQUALTO: + case ExpressionType::COMPARE_GREATERTHANOREQUALTO: + case ExpressionType::COMPARE_DISTINCT_FROM: + case ExpressionType::COMPARE_NOT_DISTINCT_FROM: + return true; + default: + return false; + } +} + +bool MarkJoinSimplifier::TrySimplifyConstantInput(unique_ptr &op, + BindingReplacementGraph &replacements) { + if (op->type != LogicalOperatorType::LOGICAL_COMPARISON_JOIN) { + return false; + } + + auto &join = op->Cast(); + if (join.join_type != JoinType::MARK || join.HasArbitraryConditions() || join.conditions.size() != 1 || + !IsConstantInputComparisonOptimizable(join.conditions[0])) { + return false; + } + + D_ASSERT(join.children.size() == 2); + auto &right_plan = *join.children[1]; + if (right_plan.type != LogicalOperatorType::LOGICAL_PROJECTION || right_plan.children.size() != 1 || + right_plan.children[0]->type != LogicalOperatorType::LOGICAL_DUMMY_SCAN || right_plan.expressions.size() != 1) { + return false; + } + + const auto &constant_expression = *right_plan.expressions[0]; + if (!constant_expression.IsFoldable() || constant_expression.HasParameter() || constant_expression.IsVolatile() || + constant_expression.CanThrow()) { + return false; + } + + const auto &right_bindings = right_plan.GetColumnBindings(); + if (right_bindings.size() != 1) { + return false; + } + + Value constant; + if (!ExpressionExecutor::TryEvaluateScalar(optimizer.context, constant_expression, constant)) { + return false; + } + + const auto &condition = join.conditions[0]; + const auto &left_bindings = join.children[0]->GetColumnBindings(); + bool valid_left_expression = true; + ExpressionIterator::VisitExpression(condition.GetLHS(), [&](const auto &ref) { + if (ref.Depth() != 0 || + std::find(left_bindings.begin(), left_bindings.end(), ref.Binding()) == left_bindings.end()) { + valid_left_expression = false; + } + }); + + const auto right_binding = right_bindings[0]; + bool valid_right_expression = true; + bool found_right_binding = false; + ExpressionIterator::VisitExpression(condition.GetRHS(), [&](const auto &ref) { + if (ref.Depth() != 0 || ref.Binding() != right_binding) { + valid_right_expression = false; + } + found_right_binding |= ref.Binding() == right_binding; + }); + + if (!valid_left_expression || !valid_right_expression || !found_right_binding) { + return false; + } + + const auto old_bindings = join.GetColumnBindings(); + const auto old_types = join.types; + if (old_bindings.size() != old_types.size() || old_bindings.empty() || + old_bindings.back() != ColumnBinding(join.mark_index, ProjectionIndex(0)) || + old_types.back() != LogicalType::BOOLEAN) { + return false; + } + + for (idx_t i = 0; i + 1 < old_bindings.size(); ++i) { + if (std::find(left_bindings.begin(), left_bindings.end(), old_bindings[i]) == left_bindings.end()) { + return false; + } + } + + auto comparison_right = condition.GetRHS().Copy(); + ExpressionIterator::VisitExpressionMutable( + comparison_right, [&right_binding, &constant](auto &ref, auto &slot) { + if (ref.Binding() == right_binding) { + slot = make_uniq(constant); + } + }); + + vector> expressions; + expressions.reserve(old_bindings.size()); + for (idx_t i = 0; i + 1 < old_bindings.size(); ++i) { + expressions.push_back(make_uniq(old_types[i], old_bindings[i])); + } + expressions.push_back(BoundComparisonExpression::Create(condition.GetComparisonType(), condition.GetLHS().Copy(), + std::move(comparison_right))); + auto projection = make_uniq(optimizer.binder.GenerateTableIndex(), std::move(expressions)); + projection->children.push_back(std::move(join.children[0])); + projection->ResolveOperatorTypes(); + const auto new_bindings = projection->GetColumnBindings(); + for (idx_t i = 0; i < old_bindings.size(); ++i) { + replacements.Add(old_bindings[i], new_bindings[i]); + } + op = std::move(projection); + return true; +} + static bool ComparisonInputIsNotNull(NotNullExpressionAnalyzer &analyzer, LogicalOperator &op, const Expression &expr) { // These comparisons can produce NULL from nested members. if (expr.GetReturnType().id() == LogicalTypeId::TUPLE || expr.GetReturnType().id() == LogicalTypeId::UNION) { @@ -439,17 +571,26 @@ bool MarkJoinSimplifier::TrySimplifyDisjunction(unique_ptr &op, } void MarkJoinSimplifier::Rewrite(unique_ptr &op, NotNullExpressionAnalyzer &nullability, - BindingReplacementGraph &replacements, vector> &ancestors) { + BindingReplacementGraph &replacements, vector> &ancestors, + bool constant_input_only) { ancestors.push_back(*op); - for (auto &child : op->children) { - Rewrite(child, nullability, replacements, ancestors); + for (idx_t child_idx = 0; child_idx < op->children.size(); ++child_idx) { + ColumnBindingRewrite::RewriteChild( + op, child_idx, + [this, &nullability, &replacements, &ancestors, + constant_input_only](unique_ptr &child, BindingReplacementGraph &child_replacements) { + Rewrite(child, nullability, child_replacements, ancestors, constant_input_only); + replacements.Merge(child_replacements); + }); } ancestors.pop_back(); // Visit original consumers before adding their enclosing conversion's replacement edges. ColumnBindingRewrite::ApplyToOperatorBindings(*op, replacements); - if (op->type == LogicalOperatorType::LOGICAL_FILTER && - (TrySimplify(op, nullability, replacements) || - TrySimplifyDisjunction(op, nullability, ancestors, replacements))) { + if (constant_input_only) { + TrySimplifyConstantInput(op, replacements); + } else if (op->type == LogicalOperatorType::LOGICAL_FILTER && + (TrySimplify(op, nullability, replacements) || + TrySimplifyDisjunction(op, nullability, ancestors, replacements))) { auto &filter = op->Cast(); if (filter.expressions.empty() && !filter.HasProjectionMap()) { op = std::move(filter.children[0]); @@ -457,11 +598,19 @@ void MarkJoinSimplifier::Rewrite(unique_ptr &op, NotNullExpress } } +void MarkJoinSimplifier::OptimizeConstantInput(unique_ptr &plan) { + plan->ResolveOperatorTypes(); + NotNullExpressionAnalyzer nullability(optimizer.context, *plan); + BindingReplacementGraph replacements; + vector> ancestors; + Rewrite(plan, nullability, replacements, ancestors, true); +} + void MarkJoinSimplifier::Optimize(unique_ptr &plan) { NotNullExpressionAnalyzer nullability(optimizer.context, *plan); BindingReplacementGraph replacements; vector> ancestors; - Rewrite(plan, nullability, replacements, ancestors); + Rewrite(plan, nullability, replacements, ancestors, false); } } // namespace duckdb diff --git a/src/duckdb/src/optimizer/optimizer.cpp b/src/duckdb/src/optimizer/optimizer.cpp index 10fe09bc6..7f9c79028 100644 --- a/src/duckdb/src/optimizer/optimizer.cpp +++ b/src/duckdb/src/optimizer/optimizer.cpp @@ -20,6 +20,7 @@ #include "duckdb/optimizer/filter_statistics.hpp" #include "duckdb/optimizer/filter_pullup.hpp" #include "duckdb/optimizer/filter_pushdown.hpp" +#include "duckdb/optimizer/group_by_top_key.hpp" #include "duckdb/optimizer/grouping_sets_optimizer.hpp" #include "duckdb/optimizer/in_clause_rewriter.hpp" #include "duckdb/optimizer/join_elimination.hpp" @@ -229,6 +230,12 @@ void Optimizer::RunBuiltInOptimizers() { plan = filter_pullup.Rewrite(std::move(plan)); }); + // Simplify constant-input MARK joins before filter pushdown. + RunOptimizer(OptimizerType::MARK_JOIN_SIMPLIFIER, [&]() { + MarkJoinSimplifier mark_simplifier(*this); + mark_simplifier.OptimizeConstantInput(plan); + }); + // perform filter pushdown RunOptimizer(OptimizerType::FILTER_PUSHDOWN, [&]() { FilterPushdown filter_pushdown(*this); @@ -259,7 +266,7 @@ void Optimizer::RunBuiltInOptimizers() { CTEFilterPusher::ClearDependencies(*plan); RunOptimizer(OptimizerType::REGEX_RANGE, [&]() { - RegexRangeFilter regex_opt; + RegexRangeFilter regex_opt(context); plan = regex_opt.Rewrite(std::move(plan)); }); @@ -330,10 +337,7 @@ void Optimizer::RunBuiltInOptimizers() { }); // Pull up projection from joins - RunOptimizer(OptimizerType::PROJECTION_PULLUP, [&]() { - ProjectionPullup projection_pullup(*this, plan); - projection_pullup.Optimize(plan); - }); + RunOptimizer(OptimizerType::PROJECTION_PULLUP, [&]() { ProjectionPullup::Optimize(*this, plan); }); // Push down joins against windows RunOptimizer(OptimizerType::WINDOW_JOIN_PUSHDOWN, [&]() { @@ -587,6 +591,13 @@ void Optimizer::RunBuiltInOptimizers() { ScalarFnPushdown fn_pushdown(context); plan = fn_pushdown.Optimize(std::move(plan)); }); + + // Bounds the input of grouped aggregates whose Top-N orders by the group keys, and turns a LIMIT over a grouped + // aggregate into such a Top-N. Runs last: the filter is placed below the finished aggregate. + RunOptimizer(OptimizerType::GROUP_BY_TOP_KEY, [&]() { + GroupByTopKey group_by_top_key(*this); + plan = group_by_top_key.Optimize(std::move(plan)); + }); } unique_ptr Optimizer::LowerMandatoryAggregateRewrites(unique_ptr plan_p) { diff --git a/src/duckdb/src/optimizer/projection_placement.cpp b/src/duckdb/src/optimizer/projection_placement.cpp index 51fc9b934..a7a02fa99 100644 --- a/src/duckdb/src/optimizer/projection_placement.cpp +++ b/src/duckdb/src/optimizer/projection_placement.cpp @@ -1,5 +1,6 @@ #include "duckdb/optimizer/projection_placement.hpp" +#include "duckdb/common/reference_map.hpp" #include "duckdb/function/scalar/compressed_materialization_utils.hpp" #include "duckdb/optimizer/column_binding_replacer.hpp" #include "duckdb/optimizer/expression_heuristics.hpp" @@ -34,6 +35,11 @@ struct ExpressionPlacement { idx_t expression_index = 0; vector path; unique_ptr expression; +}; + +struct PlacementCandidate { + idx_t path_size; + unique_ptr expression; double evaluation_cardinality = 0; double output_transport_cardinality = 0; double input_transport_savings_cardinality = 0; @@ -63,18 +69,16 @@ struct LiftOption { double input_transport_cardinality; column_binding_set_t result_bindings; vector target_bindings; - vector target_types; }; struct LiftPlacement { - optional_ptr source; + TableIndex source_table_index; idx_t expression_index; ColumnBinding source_binding; vector dependencies; vector path; column_binding_set_t result_bindings; vector target_bindings; - vector target_types; }; struct LiftDependency { @@ -83,12 +87,69 @@ struct LiftDependency { LogicalType type; }; +struct LiftedExpression { + idx_t expression_index; + ColumnBinding source_binding; +}; + +struct LiftPlacementGroup { + TableIndex source_table_index; + vector expressions; + vector path; + vector target_bindings; + vector dependencies; + column_binding_map_t dependency_indexes; + column_binding_map_t result_indexes; + + bool TryAdd(LiftPlacement placement) { + if (source_table_index.IsValid()) { + if (source_table_index != placement.source_table_index || + !RefersToSameObject(path.back().op.get(), placement.path.back().op.get())) { + return false; + } + D_ASSERT(path.size() == placement.path.size()); + for (idx_t path_idx = 0; path_idx < path.size(); path_idx++) { + D_ASSERT(RefersToSameObject(path[path_idx].op.get(), placement.path[path_idx].op.get())); + auto &bindings = placement.path[path_idx].result_bindings; + path[path_idx].result_bindings.insert(bindings.begin(), bindings.end()); + } + } else { + source_table_index = placement.source_table_index; + path = std::move(placement.path); + target_bindings = std::move(placement.target_bindings); + } + for (auto &dependency : placement.dependencies) { + auto entry = dependency_indexes.emplace(dependency.binding, dependencies.size()); + if (entry.second) { + dependencies.push_back({dependency.binding, dependency.binding, dependency.type}); + } else { + D_ASSERT(dependencies[entry.first->second].type == dependency.type); + } + } + for (auto &binding : placement.result_bindings) { + auto inserted = result_indexes.emplace(binding, expressions.size()); + D_ASSERT(inserted.second); + (void)inserted; + } + expressions.push_back({placement.expression_index, placement.source_binding}); + return true; + } +}; + static unique_ptr &GetPathTarget(const vector &path) { D_ASSERT(!path.empty()); auto &last_step = path.back(); return last_step.op.get().children[last_step.child_index]; } +static unique_ptr &GetPathOperator(unique_ptr &root, const vector &path, + idx_t index) { + D_ASSERT(index < path.size()); + auto &op = index == 0 ? root : path[index - 1].op.get().children[path[index - 1].child_index]; + D_ASSERT(RefersToSameObject(*op, path[index].op.get())); + return op; +} + static void CopyStatistics(column_binding_map_t> &statistics_map, const ColumnBinding &source, const ColumnBinding &target) { auto entry = statistics_map.find(source); @@ -286,14 +347,17 @@ static bool TraceProjectionResult(LogicalProjection &projection, const column_bi return !output_bindings.empty(); } +static bool CanMoveExpression(const Expression &expression) { + // Preserve evaluation effects and the placement chosen by compressed materialization. + return expression.GetExpressionClass() != ExpressionClass::BOUND_COLUMN_REF && !expression.IsVolatile() && + !expression.CanThrow() && !CMUtils::GetWrappedInput(expression); +} + static bool FindLiftPlacement(LogicalProjection &projection, idx_t expression_index, const vector &ancestors, const column_binding_map_t> &statistics_map, const column_binding_map_t &reading_expressions, LiftPlacement &result) { auto &expression = *projection.expressions[expression_index]; - // Preserve the placement chosen by compressed materialization. - if (expression.GetExpressionClass() == ExpressionClass::BOUND_COLUMN_REF || expression.IsVolatile() || - expression.CanThrow() || CMUtils::GetWrappedInput(expression) || - !projection.children[0]->has_estimated_cardinality) { + if (!CanMoveExpression(expression) || !projection.children[0]->has_estimated_cardinality) { return false; } @@ -340,7 +404,6 @@ static bool FindLiftPlacement(LogicalProjection &projection, idx_t expression_in break; } - op.ResolveOperatorTypes(); LiftPathStep step {op, ancestor.child_index, op.GetColumnBindings(), current_bindings}; path.push_back(std::move(step)); if (!IsEligibleJoin(op)) { @@ -348,7 +411,7 @@ static bool FindLiftPlacement(LogicalProjection &projection, idx_t expression_in } transport_cardinality += static_cast(op.estimated_cardinality); options.push_back({path.size(), static_cast(op.estimated_cardinality), transport_cardinality, - current_bindings, op.GetColumnBindings(), op.types}); + current_bindings, op.GetColumnBindings()}); } if (options.empty()) { @@ -392,7 +455,7 @@ static bool FindLiftPlacement(LogicalProjection &projection, idx_t expression_in } auto &option = options[best_option.GetIndex()]; - result.source = projection; + result.source_table_index = projection.table_index; result.expression_index = expression_index; result.source_binding = source_binding; result.dependencies = std::move(dependencies); @@ -402,56 +465,33 @@ static bool FindLiftPlacement(LogicalProjection &projection, idx_t expression_in } result.result_bindings = option.result_bindings; result.target_bindings = option.target_bindings; - result.target_types = option.target_types; return true; } -struct ProjectionRewrite { - vector old_bindings; - vector new_bindings; -}; - -static optional_ptr> FindOperator(unique_ptr &op, - const LogicalOperator &target) { - if (op.get() == &target) { - return op; - } - for (auto &child : op->children) { - auto result = FindOperator(child, target); - if (result) { - return result; +static LiftPlacementGroup +FindLiftPlacementGroup(LogicalProjection &projection, const vector &ancestors, + const column_binding_map_t> &statistics_map) { + auto reading_expressions = CountReadingExpressions(projection); + LiftPlacementGroup group; + for (idx_t expression_idx = 0; expression_idx < projection.expressions.size(); expression_idx++) { + LiftPlacement placement; + if (FindLiftPlacement(projection, expression_idx, ancestors, statistics_map, reading_expressions, placement)) { + // Other destinations must be reconsidered after bindings and input-reading counts change. + group.TryAdd(std::move(placement)); } } - return nullptr; + return group; } -static ColumnBinding ResolveBinding(const ColumnBinding &binding, - const vector> &replacements) { - auto result = binding; - for (idx_t iteration = 0; iteration <= replacements.size(); iteration++) { - bool replaced = false; - for (auto &replacement : replacements) { - if (replacement.first != result) { - continue; - } - result = replacement.second; - replaced = true; - break; - } - if (!replaced) { - return result; - } - } - throw InternalException("Projection placement encountered a cyclic binding replacement"); -} +struct ProjectionRewrite { + vector old_bindings; + vector new_bindings; +}; -static void RemapParentProjectionMap(optional_ptr parent, idx_t child_index, +static void RemapParentProjectionMap(LogicalOperator &parent, idx_t child_index, const vector &old_bindings, const vector &new_bindings) { - if (!parent) { - return; - } - auto projection_map = LogicalOperatorVisitor::GetProjectionMap(*parent, child_index); + auto projection_map = LogicalOperatorVisitor::GetProjectionMap(parent, child_index); if (!projection_map || projection_map->empty() || old_bindings == new_bindings) { return; } @@ -486,18 +526,49 @@ static void ExposeBinding(LogicalOperator &op, idx_t child_index, const ColumnBi } } -static ProjectionRewrite RebuildProjection(Optimizer &optimizer, - column_binding_map_t> &statistics_map, - unique_ptr &root, LogicalProjection &projection, - const column_binding_set_t &removed_bindings, - vector &dependencies, - vector> &binding_replacements, - optional_ptr &lowest_rebuilt) { - auto projection_ptr = FindOperator(root, projection); - if (!projection_ptr) { - throw InternalException("Projection placement lost a projection while lifting an expression"); +static void SetProjectionTypes(LogicalProjection &projection) { + projection.types.clear(); + for (auto &expression : projection.expressions) { + projection.types.push_back(expression->GetReturnType()); } +} + +//! Wrap an owning slot and finish local metadata before exposing the new projection to its caller. +static LogicalProjection &WrapLiftProjection(Optimizer &optimizer, unique_ptr &op, + vector> expressions) { + auto projection = make_uniq(optimizer.binder.GenerateTableIndex(), std::move(expressions)); + SetProjectionTypes(*projection); + if (op->has_estimated_cardinality) { + projection->SetEstimatedCardinality(op->estimated_cardinality); + } + projection->children.push_back(std::move(op)); + op = std::move(projection); + return op->Cast(); +} +//! Select types from the current child layouts, including any columns exposed by a changed projection map. +//! Children on the rewritten path are already updated; other child subtrees do not need type resolution. +static void UpdateLiftTypes(LogicalOperator &op) { + D_ASSERT(op.type == LogicalOperatorType::LOGICAL_FILTER || IsEligibleJoin(op)); + column_binding_map_t types; + for (auto &child : op.children) { + auto bindings = child->GetColumnBindings(); + D_ASSERT(bindings.size() == child->types.size()); + for (idx_t i = 0; i < bindings.size(); i++) { + types.emplace(bindings[i], child->types[i]); + } + } + op.types.clear(); + for (auto &binding : op.GetColumnBindings()) { + op.types.push_back(types.at(binding)); + } +} + +static ProjectionRewrite +RebuildProjection(Optimizer &optimizer, column_binding_map_t> &statistics_map, + unique_ptr &op, const column_binding_set_t &removed_bindings, + vector &dependencies, BindingReplacementGraph &binding_replacements) { + auto &projection = op->Cast(); auto old_bindings = projection.GetColumnBindings(); vector> expressions; vector dependency_indexes(dependencies.size()); @@ -512,9 +583,8 @@ static ProjectionRewrite RebuildProjection(Optimizer &optimizer, if (expression->GetExpressionClass() == ExpressionClass::BOUND_COLUMN_REF) { auto &colref = expression->Cast(); if (colref.Depth() == 0) { - // the expressions still refer to the bindings of projections rebuilt below us: the binding replacer - // only runs once the whole placement is in place (see ApplyLiftPlacement) - auto current_binding = ResolveBinding(colref.Binding(), binding_replacements); + // Retained expressions can still refer to projections rebuilt below us. + auto current_binding = binding_replacements.Resolve(colref.Binding()); for (idx_t dependency_idx = 0; dependency_idx < dependencies.size(); dependency_idx++) { if (!dependency_indexes[dependency_idx].IsValid() && current_binding == dependencies[dependency_idx].current_binding && @@ -543,12 +613,11 @@ static ProjectionRewrite RebuildProjection(Optimizer &optimizer, replacement->SetEstimatedCardinality(projection.estimated_cardinality); } replacement->children.push_back(std::move(projection.children[0])); - optional_ptr replacement_ptr = *replacement; - *projection_ptr = std::move(replacement); + op = std::move(replacement); for (auto &retained_binding : retained_bindings) { auto new_binding = ColumnBinding(table_index, ProjectionIndex(retained_binding.second)); - binding_replacements.emplace_back(retained_binding.first, new_binding); + binding_replacements.Add(retained_binding.first, new_binding); CopyStatistics(statistics_map, retained_binding.first, new_binding); } for (idx_t dependency_idx = 0; dependency_idx < dependencies.size(); dependency_idx++) { @@ -557,14 +626,12 @@ static ProjectionRewrite RebuildProjection(Optimizer &optimizer, CopyStatistics(statistics_map, old_binding, new_binding); dependencies[dependency_idx].current_binding = new_binding; } - if (!lowest_rebuilt) { - lowest_rebuilt = replacement_ptr; - } - // The references to the old bindings are replaced later, in one go, once the lifted expression has been placed: - // the projection maps of the operators above us are only made consistent with the new column layout step by - // step (RemapParentProjectionMap, ExposeBinding, and finally the restore projection), and walking the plan with - // a ColumnBindingReplacer before that resolves the column bindings of every operator through these stale maps. - return {std::move(old_bindings), replacement_ptr->GetColumnBindings()}; + // Only visit this projection's expressions. The enclosing path still has partially rebuilt layouts, + // but resolving its child bindings does not require inspecting those layouts or walking other subtrees. + ColumnBindingReplacer replacer(binding_replacements); + replacer.VisitOperatorBindings(*op); + SetProjectionTypes(op->Cast()); + return {std::move(old_bindings), op->GetColumnBindings()}; } static void RewriteLiftedExpression(unique_ptr &expression, const vector &dependencies) { @@ -582,65 +649,83 @@ static void RewriteLiftedExpression(unique_ptr &expression, const ve }); } -static void ApplyLiftPlacement(Optimizer &optimizer, column_binding_map_t> &statistics_map, - unique_ptr &root, LiftPlacement &placement) { - D_ASSERT(placement.source); - D_ASSERT(!placement.path.empty()); - auto &source = *placement.source; - auto expression = std::move(source.expressions[placement.expression_index]); - vector dependencies; - for (auto &dependency : placement.dependencies) { - dependencies.push_back({dependency.binding, dependency.binding, dependency.type}); - } - vector> binding_replacements; - - column_binding_set_t source_binding; - source_binding.insert(placement.source_binding); - optional_ptr lowest_rebuilt; - auto source_rewrite = RebuildProjection(optimizer, statistics_map, root, source, source_binding, dependencies, - binding_replacements, lowest_rebuilt); - RemapParentProjectionMap(placement.path[0].op.get(), placement.path[0].child_index, source_rewrite.old_bindings, +static BindingReplacementGraph RebuildLiftPath(Optimizer &optimizer, + column_binding_map_t> &statistics_map, + LiftPlacementGroup &group) { + auto &path = group.path; + auto &source_op = path.front().op.get().children[path.front().child_index]; + auto &dependencies = group.dependencies; + column_binding_set_t source_bindings; + for (auto &placement : group.expressions) { + source_bindings.insert(placement.source_binding); + } + BindingReplacementGraph binding_replacements; + + auto source_rewrite = + RebuildProjection(optimizer, statistics_map, source_op, source_bindings, dependencies, binding_replacements); + RemapParentProjectionMap(path[0].op.get(), path[0].child_index, source_rewrite.old_bindings, source_rewrite.new_bindings); - for (idx_t path_idx = 0; path_idx < placement.path.size(); path_idx++) { - auto &step = placement.path[path_idx]; + for (idx_t path_idx = 0; path_idx < path.size(); path_idx++) { + auto &step = path[path_idx]; ProjectionRewrite rewrite {step.output_bindings, step.output_bindings}; if (step.op.get().type == LogicalOperatorType::LOGICAL_PROJECTION) { - rewrite = RebuildProjection(optimizer, statistics_map, root, step.op.get().Cast(), - step.result_bindings, dependencies, binding_replacements, lowest_rebuilt); + // The destination is a join, so every rebuilt projection has an unchanged parent above it. + // Replace its owning child slot and immediately refresh the borrowed path reference. + D_ASSERT(path_idx + 1 < path.size()); + auto &parent = path[path_idx + 1]; + auto &projection = parent.op.get().children[parent.child_index]; + rewrite = RebuildProjection(optimizer, statistics_map, projection, step.result_bindings, dependencies, + binding_replacements); + step.op = *projection; } else { for (auto &dependency : dependencies) { ExposeBinding(step.op.get(), step.child_index, dependency.current_binding); } rewrite.new_bindings = step.op.get().GetColumnBindings(); + ColumnBindingReplacer replacer(binding_replacements); + replacer.VisitOperatorBindings(step.op.get()); + UpdateLiftTypes(step.op.get()); } - if (path_idx + 1 < placement.path.size()) { - RemapParentProjectionMap(placement.path[path_idx + 1].op.get(), placement.path[path_idx + 1].child_index, - rewrite.old_bindings, rewrite.new_bindings); + if (path_idx + 1 < path.size()) { + RemapParentProjectionMap(path[path_idx + 1].op.get(), path[path_idx + 1].child_index, rewrite.old_bindings, + rewrite.new_bindings); } } + return binding_replacements; +} + +struct LiftRewriteResult { + BindingReplacementGraph output_replacements; + //! Updated root-to-source-parent path, including every projection added by the rewrite. + vector path_to_source; +}; - RewriteLiftedExpression(expression, dependencies); - auto &target_step = placement.path.back(); - auto target_ptr = FindOperator(root, target_step.op.get()); - if (!target_ptr) { - throw InternalException("Projection placement lost its target join"); +static LiftRewriteResult RestoreLiftedOutputs(Optimizer &optimizer, + column_binding_map_t> &statistics_map, + unique_ptr &target, const LiftPlacementGroup &group, + const BindingReplacementGraph &binding_replacements, + vector> expressions, + const vector &target_types) { + LiftRewriteResult result; + for (idx_t path_idx = group.path.size(); path_idx > 0; path_idx--) { + auto &step = group.path[path_idx - 1]; + result.path_to_source.push_back({step.op, step.child_index}); } - auto &target = **target_ptr; - target.ResolveOperatorTypes(); - auto current_target_bindings = target.GetColumnBindings(); + auto &result_indexes = group.result_indexes; + auto current_target_bindings = target->GetColumnBindings(); vector> compute_expressions; vector compute_inputs; vector restore_indexes; - restore_indexes.reserve(placement.target_bindings.size()); - for (idx_t target_idx = 0; target_idx < placement.target_bindings.size(); target_idx++) { - auto &old_binding = placement.target_bindings[target_idx]; - if (placement.result_bindings.find(old_binding) != placement.result_bindings.end()) { + restore_indexes.reserve(group.target_bindings.size()); + for (idx_t target_idx = 0; target_idx < group.target_bindings.size(); target_idx++) { + auto &old_binding = group.target_bindings[target_idx]; + if (result_indexes.find(old_binding) != result_indexes.end()) { restore_indexes.push_back(DConstants::INVALID_INDEX); continue; } - auto current_binding = ResolveBinding(old_binding, binding_replacements); + auto current_binding = binding_replacements.Resolve(old_binding); auto current_entry = std::find(current_target_bindings.begin(), current_target_bindings.end(), current_binding); if (current_entry == current_target_bindings.end()) { throw InternalException("Projection placement lost target binding %s", current_binding.ToString()); @@ -650,111 +735,241 @@ static void ApplyLiftPlacement(Optimizer &optimizer, column_binding_map_t(current_entry - current_target_bindings.begin()); - compute_expressions.push_back(make_uniq(target.types[type_idx], current_binding)); + compute_expressions.push_back( + make_uniq(target_types[target_idx], current_binding)); } else { compute_idx = NumericCast(compute_entry - compute_inputs.begin()); } restore_indexes.push_back(compute_idx); } - auto candidate_idx = compute_expressions.size(); - compute_expressions.push_back(std::move(expression)); - auto compute_table_index = optimizer.binder.GenerateTableIndex(); - auto compute_projection = make_uniq(compute_table_index, std::move(compute_expressions)); - if (target.has_estimated_cardinality) { - compute_projection->SetEstimatedCardinality(target.estimated_cardinality); + auto first_candidate_idx = compute_expressions.size(); + for (auto &expression : expressions) { + compute_expressions.push_back(std::move(expression)); } - compute_projection->children.push_back(std::move(*target_ptr)); + auto &compute_projection = WrapLiftProjection(optimizer, target, std::move(compute_expressions)); + auto compute_table_index = compute_projection.table_index; + result.path_to_source.insert(result.path_to_source.begin(), {compute_projection, 0}); vector> restore_expressions; - restore_expressions.reserve(placement.target_bindings.size()); - for (idx_t target_idx = 0; target_idx < placement.target_bindings.size(); target_idx++) { - auto compute_idx = restore_indexes[target_idx]; + restore_expressions.reserve(group.target_bindings.size()); + for (idx_t target_idx = 0; target_idx < group.target_bindings.size(); target_idx++) { + auto &compute_idx = restore_indexes[target_idx]; if (compute_idx == DConstants::INVALID_INDEX) { - compute_idx = candidate_idx; + compute_idx = first_candidate_idx + result_indexes.at(group.target_bindings[target_idx]); } restore_expressions.push_back(make_uniq( - placement.target_types[target_idx], ColumnBinding(compute_table_index, ProjectionIndex(compute_idx)))); + target_types[target_idx], ColumnBinding(compute_table_index, ProjectionIndex(compute_idx)))); } - auto restore_table_index = optimizer.binder.GenerateTableIndex(); - auto restore_projection = make_uniq(restore_table_index, std::move(restore_expressions)); - if (target.has_estimated_cardinality) { - restore_projection->SetEstimatedCardinality(target.estimated_cardinality); - } - restore_projection->children.push_back(std::move(compute_projection)); - optional_ptr restore_ptr = *restore_projection; - *target_ptr = std::move(restore_projection); + auto &restore_projection = WrapLiftProjection(optimizer, target, std::move(restore_expressions)); + auto restore_table_index = restore_projection.table_index; + result.path_to_source.insert(result.path_to_source.begin(), {restore_projection, 0}); for (idx_t compute_idx = 0; compute_idx < compute_inputs.size(); compute_idx++) { CopyStatistics(statistics_map, compute_inputs[compute_idx], ColumnBinding(compute_table_index, ProjectionIndex(compute_idx))); } - CopyStatistics(statistics_map, placement.source_binding, - ColumnBinding(compute_table_index, ProjectionIndex(candidate_idx))); - - // now that the restore projection reproduces the target's original column layout, every projection map in the - // plan is consistent again: replace the references to the bindings of the rebuilt projections (resolved through - // the chain of rebuilds) everywhere above the lowest rebuilt projection - ColumnBindingReplacer rebuild_replacer; - for (auto &replacement : binding_replacements) { - auto final_binding = ResolveBinding(replacement.first, binding_replacements); - if (final_binding != replacement.first) { - rebuild_replacer.replacement_bindings.emplace_back(replacement.first, final_binding); - } + for (idx_t placement_idx = 0; placement_idx < group.expressions.size(); placement_idx++) { + CopyStatistics(statistics_map, group.expressions[placement_idx].source_binding, + ColumnBinding(compute_table_index, ProjectionIndex(first_candidate_idx + placement_idx))); } - rebuild_replacer.stop_operator = lowest_rebuilt; - rebuild_replacer.VisitOperator(*root); - ColumnBindingReplacer replacer; - for (idx_t target_idx = 0; target_idx < placement.target_bindings.size(); target_idx++) { + // The complete subtree now restores the original ordered values. Its callers only need these output changes; + // references inside the subtree have already been repaired at each rebuilt operator. + for (idx_t target_idx = 0; target_idx < group.target_bindings.size(); target_idx++) { auto restore_binding = ColumnBinding(restore_table_index, ProjectionIndex(target_idx)); - auto &old_binding = placement.target_bindings[target_idx]; - replacer.replacement_bindings.emplace_back(old_binding, restore_binding); - if (placement.result_bindings.find(old_binding) == placement.result_bindings.end()) { - auto current_binding = ResolveBinding(old_binding, binding_replacements); - if (current_binding != old_binding) { - replacer.replacement_bindings.emplace_back(current_binding, restore_binding); - } + auto &old_binding = group.target_bindings[target_idx]; + if (!result.output_replacements.Find(old_binding)) { + // Repeated output bindings are aliases of the same value: retain the first restore slot. + result.output_replacements.Add(old_binding, restore_binding); } auto compute_idx = restore_indexes[target_idx]; - if (compute_idx == DConstants::INVALID_INDEX) { - compute_idx = candidate_idx; - } CopyStatistics(statistics_map, ColumnBinding(compute_table_index, ProjectionIndex(compute_idx)), restore_binding); } - replacer.stop_operator = restore_ptr; - replacer.VisitOperator(*root); + return result; } -static bool LiftFirstProfitableExpression(Optimizer &optimizer, - column_binding_map_t> &statistics_map, - unique_ptr &root, unique_ptr &op, - vector &ancestors) { - for (idx_t child_idx = 0; child_idx < op->children.size(); child_idx++) { - ancestors.push_back({*op, child_idx}); - auto changed = - LiftFirstProfitableExpression(optimizer, statistics_map, root, op->children[child_idx], ancestors); - ancestors.pop_back(); - if (changed) { - return true; - } +static LiftRewriteResult RewriteLiftPlacementGroup(Optimizer &optimizer, + column_binding_map_t> &statistics_map, + unique_ptr &target, LiftPlacementGroup &group) { + D_ASSERT(!group.expressions.empty()); + D_ASSERT(RefersToSameObject(*target, group.path.back().op.get())); + auto &source = group.path.front().op.get().children[group.path.front().child_index]->Cast(); + D_ASSERT(source.table_index == group.source_table_index); + // Types are initialized once before lifting and maintained along each rewritten path. + auto target_types = target->types; + vector> expressions; + for (auto &placement : group.expressions) { + expressions.push_back(std::move(source.expressions[placement.expression_index])); } - if (op->type != LogicalOperatorType::LOGICAL_PROJECTION) { + auto replacements = RebuildLiftPath(optimizer, statistics_map, group); + for (auto &expression : expressions) { + RewriteLiftedExpression(expression, group.dependencies); + } + return RestoreLiftedOutputs(optimizer, statistics_map, target, group, replacements, std::move(expressions), + target_types); +} + +//! Own traversal progress and its invalidation together. Rewrites must refresh the active path and forget +//! replaced operators before destruction; only newly exposed dependency producers need reconsideration. +class LiftTraversal { +public: + LiftTraversal(Optimizer &optimizer, column_binding_map_t> &statistics_map, + unique_ptr &root) + : optimizer(optimizer), statistics_map(statistics_map), root(root) { + } + + void Optimize(); + +private: + unique_ptr &GetOperator(idx_t depth); + void Apply(LiftPlacementGroup &group); + bool InvalidateInputs(LogicalOperator &op, const column_binding_set_t &bindings); + + Optimizer &optimizer; + column_binding_map_t> &statistics_map; + unique_ptr &root; + vector ancestors; + reference_set_t completed; +}; + +unique_ptr &LiftTraversal::GetOperator(idx_t depth) { + if (depth == 0) { + return root; + } + auto &parent = ancestors[depth - 1]; + return parent.op.get().children[parent.child_index]; +} + +bool LiftTraversal::InvalidateInputs(LogicalOperator &op, const column_binding_set_t &bindings) { + if (bindings.empty()) { return false; } - auto &projection = op->Cast(); - auto reading_expressions = CountReadingExpressions(projection); - for (idx_t expression_idx = 0; expression_idx < projection.expressions.size(); expression_idx++) { - LiftPlacement placement; - if (!FindLiftPlacement(projection, expression_idx, ancestors, statistics_map, reading_expressions, placement)) { - continue; + if (op.type == LogicalOperatorType::LOGICAL_PROJECTION) { + auto &projection = op.Cast(); + column_binding_set_t inputs; + bool affected = false; + for (auto &binding : bindings) { + if (binding.table_index != projection.table_index) { + continue; + } + affected = true; + auto &expression = projection.GetExpression(binding); + if (expression.GetExpressionClass() == ExpressionClass::BOUND_COLUMN_REF) { + auto &colref = expression.Cast(); + if (colref.Depth() == 0) { + inputs.insert(colref.Binding()); + } + } + } + if (!affected) { + return false; } - ApplyLiftPlacement(optimizer, statistics_map, root, placement); + completed.erase(op); + // Follow aliases to their producers. A computed producer is reconsidered here; its own inputs + // only gain an opportunity if that expression subsequently moves. + InvalidateInputs(*op.children[0], inputs); return true; } - return false; + if (op.type != LogicalOperatorType::LOGICAL_FILTER && !IsEligibleJoin(op)) { + return false; + } + bool affected = false; + for (auto &child : op.children) { + column_binding_set_t inputs; + for (auto &binding : child->GetColumnBindings()) { + if (bindings.find(binding) != bindings.end()) { + inputs.insert(binding); + } + } + affected |= InvalidateInputs(*child, inputs); + } + if (affected) { + completed.erase(op); + } + return affected; +} + +void LiftTraversal::Apply(LiftPlacementGroup &group) { + const auto target_depth = ancestors.size() - group.path.size(); + struct AncestorRewrite { + idx_t depth; + vector child_bindings; + }; + vector rewrites; + column_binding_set_t affected_bindings(group.target_bindings.begin(), group.target_bindings.end()); + for (idx_t depth = target_depth; depth > 0; depth--) { + auto &ancestor = ancestors[depth - 1]; + auto child_bindings = ancestor.op.get().children[ancestor.child_index]->GetColumnBindings(); + bool affected = false; + for (auto &binding : child_bindings) { + if (affected_bindings.find(binding) != affected_bindings.end()) { + affected = true; + break; + } + } + if (!affected) { + break; + } + rewrites.push_back({depth - 1, std::move(child_bindings)}); + } + // No completion entry may outlive the operator it names, including when an allocator reuses its address. + completed.erase(*GetOperator(ancestors.size())); + for (auto &step : group.path) { + completed.erase(step.op); + } + auto &target = GetOperator(target_depth); + auto result = RewriteLiftPlacementGroup(optimizer, statistics_map, target, group); + for (auto &rewrite : rewrites) { + auto &parent = GetOperator(rewrite.depth); + ColumnBindingRewrite::ApplyToChild(parent, ancestors[rewrite.depth].child_index, + std::move(rewrite.child_bindings), result.output_replacements); + } + // The rewrite supplies the complete replacement path. Traversal does not depend on the shape or + // number of inserted operators, and child indexes preserve progress through unaffected siblings. + ancestors.erase(ancestors.begin() + NumericCast::difference_type>(target_depth), ancestors.end()); + ancestors.insert(ancestors.end(), result.path_to_source.begin(), result.path_to_source.end()); + column_binding_set_t inputs; + for (auto &dependency : group.dependencies) { + inputs.insert(dependency.original_binding); + } + InvalidateInputs(*GetOperator(ancestors.size())->children[0], inputs); +} + +void LiftTraversal::Optimize() { + root->ResolveOperatorTypes(); + bool visit_children = true; + while (true) { + auto &op = GetOperator(ancestors.size()); + if (completed.find(*op) == completed.end()) { + if (visit_children && !op->children.empty()) { + ancestors.push_back({*op, 0}); + continue; + } + if (op->type == LogicalOperatorType::LOGICAL_PROJECTION) { + auto group = FindLiftPlacementGroup(op->Cast(), ancestors, statistics_map); + if (!group.expressions.empty()) { + Apply(group); + // Revisit exposed input producers and the rebuilt source, then continue through the + // updated path. Completion entries skip unrelated descendants and sibling subtrees. + visit_children = true; + continue; + } + } + completed.insert(*op); + } + if (ancestors.empty()) { + return; + } + auto &parent = ancestors.back(); + if (++parent.child_index < parent.op.get().children.size()) { + visit_children = true; + } else { + ancestors.pop_back(); + visit_children = false; + } + } } static optional_idx GetExpressionChild(const Expression &expression, LogicalOperator &op) { @@ -770,10 +985,7 @@ static bool FindPlacement(LogicalProjection &projection, idx_t expression_index, const column_binding_map_t> &statistics_map, const column_binding_map_t &reading_expressions, ExpressionPlacement &result) { auto &expression = *projection.expressions[expression_index]; - // Preserve the placement chosen by compressed materialization. - if (expression.GetExpressionClass() == ExpressionClass::BOUND_COLUMN_REF || expression.IsVolatile() || - expression.CanThrow() || CMUtils::GetWrappedInput(expression) || - !projection.children[0]->has_estimated_cardinality) { + if (!CanMoveExpression(expression) || !projection.children[0]->has_estimated_cardinality) { return false; } @@ -809,7 +1021,7 @@ static bool FindPlacement(LogicalProjection &projection, idx_t expression_index, double input_transport_savings_cardinality = 0; // Beyond the first direct join, the source can be live for another path expression or join condition. bool can_credit_input_transport = true; - vector candidates; + vector candidates; // Compare every position on the dependency path instead of making a greedy per-join decision. while (current.get()) { @@ -859,9 +1071,8 @@ static bool FindPlacement(LogicalProjection &projection, idx_t expression_index, input_transport_savings_cardinality += static_cast(op.estimated_cardinality); } can_credit_input_transport = false; - ExpressionPlacement candidate; - candidate.expression_index = expression_index; - candidate.path = path; + PlacementCandidate candidate; + candidate.path_size = path.size(); candidate.expression = current_expression->Copy(); candidate.evaluation_cardinality = static_cast(child->estimated_cardinality); candidate.output_transport_cardinality = transport_cardinality; @@ -873,7 +1084,7 @@ static bool FindPlacement(LogicalProjection &projection, idx_t expression_index, const double current_cost = current_evaluation_cost + input_transport_savings_cardinality * static_cast(exclusive_input_width); double best_cost = current_cost * MINIMUM_COST_RATIO; - bool found = false; + optional_ptr best_candidate; for (auto &candidate : candidates) { const double remaining_input_transport = input_transport_savings_cardinality - candidate.input_transport_savings_cardinality; @@ -882,11 +1093,18 @@ static bool FindPlacement(LogicalProjection &projection, idx_t expression_index, remaining_input_transport * static_cast(exclusive_input_width); if (candidate_cost < best_cost) { best_cost = candidate_cost; - result = std::move(candidate); - found = true; + best_candidate = candidate; } } - return found; + if (!best_candidate) { + return false; + } + // Materialize only the selected prefix, without retaining capacity for the rest of the explored path. + result.expression_index = expression_index; + auto path_end = path.begin() + NumericCast::difference_type>(best_candidate->path_size); + result.path.assign(path.begin(), path_end); + result.expression = std::move(best_candidate->expression); + return true; } static void ExposeBinding(PathStep &step, const ColumnBinding &binding) { @@ -934,12 +1152,9 @@ static void ApplyPlacementGroup(Optimizer &optimizer, column_binding_map_t 0; path_idx--) { auto &step = group.path[path_idx - 1]; - auto step_ptr = FindOperator(upper_projection.children[0], step.op.get()); - if (!step_ptr) { - throw InternalException("Projection placement lost a path operator"); - } - ColumnBindingRewrite::ApplyToChild(*step_ptr, step.child_index, - std::move(old_path_child_bindings[path_idx - 1]), replacements); + auto &step_op = GetPathOperator(upper_projection.children[0], group.path, path_idx - 1); + ColumnBindingRewrite::ApplyToChild(step_op, step.child_index, std::move(old_path_child_bindings[path_idx - 1]), + replacements); if (step.op.get().type == LogicalOperatorType::LOGICAL_PROJECTION) { auto &projection = step.op.get().Cast(); for (idx_t i = 0; i < computed_bindings.size(); i++) { @@ -969,10 +1184,11 @@ static void ApplyPlacementGroup(Optimizer &optimizer, column_binding_map_t> &statistics_map, - unique_ptr &op) { +static void LowerProfitableExpressions(Optimizer &optimizer, + column_binding_map_t> &statistics_map, + unique_ptr &op) { for (auto &child : op->children) { - OptimizeOperator(optimizer, statistics_map, child); + LowerProfitableExpressions(optimizer, statistics_map, child); } if (op->type != LogicalOperatorType::LOGICAL_PROJECTION) { return; @@ -1008,11 +1224,8 @@ ProjectionPlacementOptimizer::ProjectionPlacementOptimizer( } void ProjectionPlacementOptimizer::Optimize(unique_ptr &plan) { - vector ancestors; - while (LiftFirstProfitableExpression(optimizer, statistics_map, plan, plan, ancestors)) { - plan->ResolveOperatorTypes(); - } - OptimizeOperator(optimizer, statistics_map, plan); + LiftTraversal(optimizer, statistics_map, plan).Optimize(); + LowerProfitableExpressions(optimizer, statistics_map, plan); plan->ResolveOperatorTypes(); } diff --git a/src/duckdb/src/optimizer/projection_pullup.cpp b/src/duckdb/src/optimizer/projection_pullup.cpp index 15afb8e30..13c9a5591 100644 --- a/src/duckdb/src/optimizer/projection_pullup.cpp +++ b/src/duckdb/src/optimizer/projection_pullup.cpp @@ -40,6 +40,8 @@ optional_ptr ProjectionPullup::FindParent(LogicalOperator &targ void ProjectionPullup::InsertProjectionBelowOp(unique_ptr &op, unique_ptr &child, bool stop_at_op) { + // Insertion rewrites bindings eagerly, and the child starts an independent replacement scope. + FlushReplacements(); if (child->type != LogicalOperatorType::LOGICAL_PROJECTION) { auto proj_index = optimizer.binder.GenerateTableIndex(); auto child_bindings = child->GetColumnBindings(); @@ -68,36 +70,32 @@ void ProjectionPullup::InsertProjectionBelowOp(unique_ptr &op, // can reference bindings produced underneath, so the subtree runs its own pass // with the projection as replacement root instead of walking the whole plan for // every pull inside it - ProjectionPullup next(optimizer, child); - next.Optimize(child->children[0]); + OptimizeSubtree(optimizer, child, child->children[0]); } void ProjectionPullup::RemoveProjection(unique_ptr &op, LogicalProjection &proj, vector &proj_bindings) { - ColumnBindingReplacer replacer; for (idx_t i = 0; i < proj.expressions.size(); i++) { if (proj.expressions[i]->GetExpressionType() != ExpressionType::BOUND_COLUMN_REF) { D_ASSERT(proj.expressions[i]->GetExpressionType() == ExpressionType::VALUE_CONSTANT); continue; } auto &colref = proj.expressions[i]->Cast(); - replacer.replacement_bindings.emplace_back(proj_bindings[i], colref.Binding()); + replacements.Add(proj_bindings[i], colref.Binding()); } - replacer.stop_operator = proj.children[0]; - replacer.VisitOperator(*root); - - // Re-run optimization after removing this projection. - // Binding rewrites can make parent projections redundant, and without - // another pass they would not be eliminated. + // Continue through the exposed child. Resolve pending bindings when inspecting operators, + // instead of rewriting the entire root for every projection removed. auto child = std::move(op->children[0]); op = std::move(child); - Optimize(op); + VisitOperator(op); return; } void ProjectionPullup::PullUpNonColrefProjection(unique_ptr &op, LogicalProjection &proj, vector &proj_bindings, idx_t pull_up_to_here) { + // Moving a projection inspects output layouts and performs its own eager binding rewrites. + FlushReplacements(); // Not all expressions are colrefs. We can pull up instead of removing for (idx_t i = 0; i < parents.size(); i++) { LogicalOperator &parent_op = parents[i].get(); @@ -112,8 +110,8 @@ void ProjectionPullup::PullUpNonColrefProjection(unique_ptr &op if (join.join_type == JoinType::LEFT || join.join_type == JoinType::RIGHT || join.join_type == JoinType::OUTER) { // Recurse into child without pulling up - ProjectionPullup next(optimizer, root); - next.Optimize(proj.children[0]); + ProjectionPullup next(optimizer, root, replacements); + next.VisitOperator(proj.children[0]); return; } } @@ -175,8 +173,8 @@ void ProjectionPullup::PullUpNonColrefProjection(unique_ptr &op } // The caller's traversal no longer reaches the subtree left behind by the moved projection. - ProjectionPullup next(optimizer, root); - next.Optimize(op); + ProjectionPullup next(optimizer, root, replacements); + next.VisitOperator(op); } static bool HasJoinBelow(const LogicalOperator &op) { @@ -211,6 +209,9 @@ void ProjectionPullup::CanPullThrough(column_binding_map_t 0; i--) { idx_t parent_idx = i - 1; LogicalOperator &parent_op = parents[parent_idx].get(); + // Ancestors may still reference removed projections. Normalize their own bindings before + // inspecting expressions so eligibility checks can use ordinary binding lookups. + ColumnBindingRewrite::ApplyToOperatorBindings(parent_op, replacements); can_pull_through = true; if (parent_op.type == LogicalOperatorType::LOGICAL_CROSS_PRODUCT) { @@ -261,11 +262,29 @@ void ProjectionPullup::CanPullThrough(column_binding_map_t &op) { - VisitOperator(op); +void ProjectionPullup::Optimize(Optimizer &optimizer, unique_ptr &op) { + OptimizeSubtree(optimizer, op, op); +} + +void ProjectionPullup::OptimizeSubtree(Optimizer &optimizer, unique_ptr &root, + unique_ptr &op) { + BindingReplacementGraph pending; + ProjectionPullup next(optimizer, root, pending); + next.VisitOperator(op); + next.FlushReplacements(); +} + +void ProjectionPullup::FlushReplacements() { + if (replacements.Empty()) { + return; + } + CorrelatedColumnBindingReplacer replacer(replacements); + replacer.VisitOperator(*root); + replacements = BindingReplacementGraph(); } void ProjectionPullup::VisitOperator(unique_ptr &op) { + ColumnBindingRewrite::ApplyToOperatorBindings(*op, replacements); switch (op->type) { // These operators depend on column order. // If their immediate child is a projection, keep it and recurse into the projection’s child. @@ -342,8 +361,8 @@ void ProjectionPullup::VisitOperator(unique_ptr &op) { all_column_refs = false; } if (proj.expressions[i]->IsVolatile() || proj.expressions[i]->CanThrow()) { - ProjectionPullup next(optimizer, root); - next.Optimize(proj.children[0]); + ProjectionPullup next(optimizer, root, replacements); + next.VisitOperator(proj.children[0]); return; // bail } } @@ -360,8 +379,8 @@ void ProjectionPullup::VisitOperator(unique_ptr &op) { // reduce the opportunities for join reordering without providing any benefit. if (!can_pull_through) { // Recurse into child; - ProjectionPullup next(optimizer, root); - next.Optimize(proj.children[0]); + ProjectionPullup next(optimizer, root, replacements); + next.VisitOperator(proj.children[0]); return; } @@ -373,7 +392,7 @@ void ProjectionPullup::VisitOperator(unique_ptr &op) { // memory blowup. if (op->children[0]->type == LogicalOperatorType::LOGICAL_UNNEST) { parents.push_back(*op); - Optimize(op->children[0]); + VisitOperator(op->children[0]); PopParents(*op); return; } @@ -386,7 +405,7 @@ void ProjectionPullup::VisitOperator(unique_ptr &op) { } // Recurse on child - Optimize(op->children[0]); + VisitOperator(op->children[0]); PopParents(*op); return; } @@ -395,9 +414,10 @@ void ProjectionPullup::VisitOperator(unique_ptr &op) { } } - // Create new optimizer for child (start fresh without any state) - ProjectionPullup next(optimizer, root); + // Start a fresh pullup scope for the children, sharing pending binding replacements. + ProjectionPullup next(optimizer, root, replacements); next.VisitOperatorChildren(*op); + ColumnBindingRewrite::ApplyToOperatorBindings(*op, replacements); if (op->type == LogicalOperatorType::LOGICAL_AGGREGATE_AND_GROUP_BY && op->children[0]->type == LogicalOperatorType::LOGICAL_PROJECTION) { auto &projection = op->children[0]->Cast(); diff --git a/src/duckdb/src/optimizer/regex_range_filter.cpp b/src/duckdb/src/optimizer/regex_range_filter.cpp index 3e0ca04da..b62daf3e2 100644 --- a/src/duckdb/src/optimizer/regex_range_filter.cpp +++ b/src/duckdb/src/optimizer/regex_range_filter.cpp @@ -2,7 +2,9 @@ #include "duckdb/catalog/catalog_entry/scalar_function_catalog_entry.hpp" +#include "duckdb/function/builtin_function_lookup.hpp" #include "duckdb/function/scalar/string_functions.hpp" +#include "duckdb/main/extension_manager.hpp" #include "duckdb/planner/expression.hpp" #include "duckdb/planner/expression/bound_comparison_expression.hpp" @@ -33,15 +35,19 @@ unique_ptr RegexRangeFilter::Rewrite(unique_ptrCast(); - if (!info.range_success) { + // encode (from core_functions) compares the bytes as a BLOB, as the bounds need not be valid UTF-8 + if (!info.range_success || !ExtensionManager::Get(context).ExtensionIsLoaded("core_functions")) { continue; } - auto filter_left = BoundComparisonExpression::Create( - ExpressionType::COMPARE_GREATERTHANOREQUALTO, func.GetChildren()[0]->Copy(), - make_uniq(Value::BLOB_RAW(info.range_min))); - auto filter_right = BoundComparisonExpression::Create( - ExpressionType::COMPARE_LESSTHANOREQUALTO, func.GetChildren()[0]->Copy(), - make_uniq(Value::BLOB_RAW(info.range_max))); + vector> arguments; + arguments.push_back(func.GetChildren()[0]->Copy()); + auto blob_input = BindBuiltinScalarExpression(context, "encode", std::move(arguments)); + auto filter_left = + BoundComparisonExpression::Create(ExpressionType::COMPARE_GREATERTHANOREQUALTO, blob_input->Copy(), + make_uniq(Value::BLOB_RAW(info.range_min))); + auto filter_right = + BoundComparisonExpression::Create(ExpressionType::COMPARE_LESSTHANOREQUALTO, std::move(blob_input), + make_uniq(Value::BLOB_RAW(info.range_max))); auto filter_expr = make_uniq(ExpressionType::CONJUNCTION_AND, std::move(filter_left), std::move(filter_right)); diff --git a/src/duckdb/src/optimizer/row_number_rewriter.cpp b/src/duckdb/src/optimizer/row_number_rewriter.cpp index 6ae3bca9d..e2faa884f 100644 --- a/src/duckdb/src/optimizer/row_number_rewriter.cpp +++ b/src/duckdb/src/optimizer/row_number_rewriter.cpp @@ -65,19 +65,19 @@ bool RowNumberRewriter::CanOptimize(LogicalOperator &op) { } unique_ptr RowNumberRewriter::Optimize(unique_ptr op) { - ColumnBindingReplacer replacer; - LogicalOperator *root = op.get(); - op = RewritePlan(std::move(op), replacer); + BindingReplacementGraph replacements; + op = RewritePlan(std::move(op), replacements); - if (!replacer.replacement_bindings.empty()) { - replacer.VisitOperator(*root); + if (!replacements.Empty()) { + ColumnBindingReplacer replacer(replacements); + replacer.VisitOperator(*op); } return op; } unique_ptr RowNumberRewriter::RewriteGet(unique_ptr op, - ColumnBindingReplacer &replacer) { + BindingReplacementGraph &replacements) { auto &window = op->Cast(); auto &child = window.children[0]; auto &get = child->Cast(); @@ -89,37 +89,21 @@ unique_ptr RowNumberRewriter::RewriteGet(unique_ptr RowNumberRewriter::RewritePlan(unique_ptr op, - ColumnBindingReplacer &replacer) { + BindingReplacementGraph &replacements) { if (CanOptimize(*op)) { - return RewriteGet(std::move(op), replacer); + return RewriteGet(std::move(op), replacements); } // Recurse into children for (auto &child : op->children) { - child = RewritePlan(std::move(child), replacer); + child = RewritePlan(std::move(child), replacements); } return op; } diff --git a/src/duckdb/src/optimizer/rule/monotone_preimage.cpp b/src/duckdb/src/optimizer/rule/monotone_preimage.cpp index a29d86d6d..e4c1f8039 100644 --- a/src/duckdb/src/optimizer/rule/monotone_preimage.cpp +++ b/src/duckdb/src/optimizer/rule/monotone_preimage.cpp @@ -1,6 +1,8 @@ #include "duckdb/optimizer/rule/monotone_preimage.hpp" +#include "duckdb/common/types/cast_helpers.hpp" #include "duckdb/common/types/date.hpp" +#include "duckdb/common/types/decimal.hpp" #include "duckdb/common/types/timestamp.hpp" #include "duckdb/common/value_operations/value_operations.hpp" #include "duckdb/execution/expression_executor.hpp" @@ -13,6 +15,8 @@ #include "duckdb/planner/expression/bound_constant_expression.hpp" #include "duckdb/planner/expression/bound_function_expression.hpp" +#include + namespace duckdb { MonotonePreimageRule::MonotonePreimageRule(ExpressionRewriter &rewriter) : Rule(rewriter) { @@ -58,14 +62,78 @@ static bool GetFiniteDomain(const LogicalType &type, int64_t &lo, int64_t &hi, b hi = timestamp_t::infinity().value - 1; has_infinity = true; return true; + case LogicalTypeId::DECIMAL: { + // the unscaled integer of a decimal is exact like the integer types + const auto width = DecimalType::GetWidth(type); + if (width > Decimal::MAX_WIDTH_INT64) { + return false; + } + hi = NumericHelper::POWERS_OF_TEN[width] - 1; + lo = -hi; + return true; + } default: // BIGINT's full int64 domain would overflow the never-true bisection sentinels, other timestamp - // resolutions and HUGEINT need a wider midpoint, and floating types are only monotone up to - // rounding: all left to a later extension. + // resolutions, HUGEINT and wide decimals need a wider midpoint, and floating types are only monotone up + // to rounding (see FloatRoundingPreimage for the exceptions): all left to a later extension. return false; } } +//! The functions rounding a FLOAT or DOUBLE to an integer. They are exact, unlike the libm functions that are +//! declared monotone, so their preimage is computed in closed form instead of by bisection. +static bool GetFloatRounding(const BoundFunctionExpression &func, const LogicalType &col_type, + IntegerRounding &rounding) { + if (col_type.id() != LogicalTypeId::FLOAT && col_type.id() != LogicalTypeId::DOUBLE) { + return false; + } + rounding = func.Function().GetArgProperties(0).integer_rounding; + return rounding != IntegerRounding::UNKNOWN; +} + +//! `rounding(col) >= k`, or its complement `rounding(col) < k`, as a comparison on col. NaN sorts above every number +//! and the infinities and NaN round to themselves, so this agrees with comparing the rounding for every value. +static unique_ptr RoundingAtLeast(IntegerRounding rounding, double k, bool complement, + const BoundColumnRefExpression &col, const LogicalType &col_type) { + // floor and positive trunc reach k at k, ceil and non-positive trunc right above k - 1 + const bool from_k = rounding == IntegerRounding::FLOOR || (rounding == IntegerRounding::TRUNCATE && k > 0); + auto type = from_k ? ExpressionType::COMPARE_GREATERTHANOREQUALTO : ExpressionType::COMPARE_GREATERTHAN; + const double bound = from_k ? k : k - 1; + if (complement) { + type = NegateComparisonExpression(type); + } + auto value = col_type.id() == LogicalTypeId::FLOAT ? Value::FLOAT(static_cast(bound)) : Value::DOUBLE(bound); + return BoundComparisonExpression::Create(type, col.Copy(), make_uniq(std::move(value))); +} + +//! Preimage of `rounding(col) cmp c` on a FLOAT or DOUBLE column +static unique_ptr FloatRoundingPreimage(ClientContext &context, IntegerRounding rounding, + ExpressionType cmp, const Value &c, + const BoundColumnRefExpression &col, const LogicalType &col_type) { + const auto value = c.GetValue(); + // the integers next to the constant must be exact, which they are not beyond 2^24 (FLOAT) or 2^53 (DOUBLE) + const double exact_limit = col_type.id() == LogicalTypeId::FLOAT ? 16777216.0 : 9007199254740992.0; + if (!Value::IsFinite(value) || std::fabs(value) > exact_limit - 2) { + return nullptr; + } + // the rounding is an integer (or NaN or an infinity), so it is compared with the integer next to the constant + if (cmp == ExpressionType::COMPARE_EQUAL) { + if (std::floor(value) != value) { + return ExpressionRewriter::ConstantOrNull(context, col.Copy(), Value::BOOLEAN(false)); + } + auto lower = RoundingAtLeast(rounding, value, false, col, col_type); + auto upper = RoundingAtLeast(rounding, value + 1, true, col, col_type); + return make_uniq(ExpressionType::CONJUNCTION_AND, std::move(lower), + std::move(upper)); + } + const bool at_least = + cmp == ExpressionType::COMPARE_GREATERTHANOREQUALTO || cmp == ExpressionType::COMPARE_GREATERTHAN; + const bool use_ceil = + cmp == ExpressionType::COMPARE_GREATERTHANOREQUALTO || cmp == ExpressionType::COMPARE_LESSTHAN; + const double k = use_ceil ? std::ceil(value) : std::floor(value) + 1; + return RoundingAtLeast(rounding, k, !at_least, col, col_type); +} + //! Evaluate f at the probe value with internal representation `i`, returning false if the result is //! NULL or the evaluation fails (e.g. a domain error) - in which case the rewrite must bail. static bool EvalFunc(ClientContext &context, const BoundFunctionExpression &func, const LogicalType &col_type, @@ -183,9 +251,11 @@ unique_ptr MonotonePreimageRule::Apply(LogicalOperator &op, vectorCast(); auto &col_type = col.GetReturnType(); - int64_t dom_lo, dom_hi; - bool has_infinity; - if (!GetFiniteDomain(col_type, dom_lo, dom_hi, has_infinity)) { + int64_t dom_lo = 0, dom_hi = 0; + bool has_infinity = false; + IntegerRounding rounding = IntegerRounding::FLOOR; + const bool is_float_rounding = GetFloatRounding(func, col_type, rounding); + if (!is_float_rounding && !GetFiniteDomain(col_type, dom_lo, dom_hi, has_infinity)) { return nullptr; } // Infinity sentinels can make date/time functions return NULL for non-NULL inputs. @@ -224,6 +294,9 @@ unique_ptr MonotonePreimageRule::Apply(LogicalOperator &op, vector] ungrouped aggregate -> filters -> plain scan(s) -//===--------------------------------------------------------------------===// -//! One leaf of a cross-product tree that can be merged with its siblings -struct ScalarAggregateMerger::Branch { - //! The leaf's slot in the cross-product tree - reference> leaf; - //! The projection over the aggregate, if any - optional_ptr projection; - reference aggregate; - //! The slot under the filters: the scan, or the cross product of scans of different tables (a FROM list) - reference> relation; - vector> scans; - //! The filters' predicates, with ANDs split into their conjuncts - vector> conjuncts; -}; - -//! One of the first branch's scans, which the merged leaf keeps, and the columns it gains for the other branches -struct ScalarAggregateMerger::MergeTarget { - reference scan; - //! A column the scan gains, and the binding that column lands on - vector> added_columns; -}; - //! The aggregates that are merged: FILTER (WHERE p) feeds exactly the rows where p holds, so the result over the rows //! where p holds equals the result with FILTER (WHERE p) over any superset of them, for empty input too //! (0 for the counts, NULL otherwise). min(x, n) and max(x, n) take two arguments and are not matched. @@ -136,6 +116,7 @@ static bool SameNamedParameters(const named_argument_map_t &a, const named_argum //! Two plain scans that read the same rows: the same catalog table, or the same table function (read_parquet, //! read_csv, ...) called with the same arguments. What a call without arguments reads is known to its bind data alone. +//! HashRelation must stay consistent with changes to this comparison. static bool IsSameRelation(const LogicalGet &a, const LogicalGet &b) { if (a.function != b.function || !SameValues(a.parameters, b.parameters) || !SameNamedParameters(a.named_parameters, b.named_parameters)) { @@ -177,6 +158,7 @@ static bool RecordsRejects(const LogicalGet &get) { //! Two scans that one scan reading both of their columns can replace: the same relation, and the rows a scan returns do //! not depend on the columns it reads. A scan that drops the rows it fails to parse (ignore_errors) returns a row when //! every column it reads parses, so such scans are only shared when they read the same columns. +//! HashScan must hash compatible scans alike; keep it consistent with changes to this comparison. static bool CanShareScan(const LogicalGet &a, const LogicalGet &b) { if (!IsSameRelation(a, b) || RecordsRejects(a)) { return false; @@ -184,48 +166,203 @@ static bool CanShareScan(const LogicalGet &a, const LogicalGet &b) { return !HasOption(a, "ignore_errors") || ReadColumns(a) == ReadColumns(b); } -//! The plain scans under `op`: one scan, or a cross product of scans of different relations (a self-join's copies of -//! a table would not pair one to one with another branch's) -static bool CollectScans(LogicalOperator &op, vector> &scans) { - if (op.type == LogicalOperatorType::LOGICAL_CROSS_PRODUCT) { - for (auto &child : op.children) { - if (!CollectScans(*child, scans)) { +static hash_t HashScanParameter(const Value &value) { + auto result = value.type().Hash(); + // VARIANT equality can equate different representations that Value::Hash distinguishes. + if (TypeVisitor::Contains(value.type(), LogicalTypeId::VARIANT)) { + return result; + } + return CombineHash(result, value.Hash()); +} + +//! Equal relations must hash alike. Bind data without arguments has no generic hash and is omitted. +//! Column selection is excluded: a target may gain columns without changing which relation it reads. +static hash_t HashRelation(const LogicalGet &scan) { + auto result = CombineHash(scan.function.GetName().Hash(), Hash(CastPointerToValue(scan.GetTable().get()))); + for (auto ¶meter : scan.parameters) { + result = CombineHash(Hash(result), HashScanParameter(parameter)); + } + hash_t named_parameters = 0; + for (auto &entry : scan.named_parameters) { + named_parameters += Hash(CombineHash(entry.first.Hash(), HashScanParameter(entry.second))); + } + return CombineHash(result, named_parameters); +} + +//! Compatible scans must hash alike. CanShareWith checks collisions before grouping branches. +static hash_t HashScan(const LogicalGet &scan) { + auto result = HashRelation(scan); + if (HasOption(scan, "ignore_errors")) { + for (auto column : ReadColumns(scan)) { + result = CombineHash(Hash(result), Hash(column)); + } + } + return result; +} + +//! Borrows the ordered scans of one branch while matching and merging, indexed by relation identity. +//! Adding columns during merging does not change relation identity or invalidate the index. +class ScalarAggregateMerger::ScanCollection { +public: + //! One plain scan, or a cross product of scans of different relations (self-joins do not pair one to one). + bool Collect(LogicalOperator &op) { + if (op.type == LogicalOperatorType::LOGICAL_CROSS_PRODUCT) { + for (auto &child : op.children) { + if (!Collect(*child)) { + return false; + } + } + return true; + } + if (op.type != LogicalOperatorType::LOGICAL_GET) { + return false; + } + auto &scan = op.Cast(); + // Reject-recording scans cannot share even with an identical scan; exclude them before candidate grouping. + return IsPlainScan(scan) && !RecordsRejects(scan) && TryAdd(scan); + } + + //! Each stored scan must have a compatible scan in other, preserving the comparison's left/right order. + bool CanShareWith(const ScanCollection &other) const { + if (scans.size() != other.scans.size()) { + return false; + } + for (auto &scan : scans) { + auto candidates = other.FindCandidates(scan.get()); + if (!candidates) { + return false; + } + bool found = false; + for (auto index : *candidates) { + if (CanShareScan(scan.get(), other.scans[index].get())) { + found = true; + break; + } + } + if (!found) { return false; } } return true; } - if (op.type != LogicalOperatorType::LOGICAL_GET) { - return false; + + //! The last compatible stored scan, in iteration order, matching the original target-selection order. + optional_idx FindCompatible(const LogicalGet &scan) const { + auto candidates = FindCandidates(scan); + if (!candidates) { + return optional_idx(); + } + optional_idx result; + for (auto index : *candidates) { + if (CanShareScan(scans[index].get(), scan)) { + result = index; + } + } + return result; } - auto &scan = op.Cast(); - if (!IsPlainScan(scan)) { - return false; + + idx_t size() const { + return scans.size(); } - for (auto &other : scans) { - if (IsSameRelation(other.get(), scan)) { - return false; + + using const_iterator = vector>::const_iterator; + const_iterator begin() const { + return scans.begin(); + } + const_iterator end() const { + return scans.end(); + } + +private: + bool TryAdd(LogicalGet &scan) { + auto &candidates = relation_index[HashRelation(scan)]; + for (auto index : candidates) { + if (IsSameRelation(scans[index].get(), scan)) { + return false; + } } + candidates.push_back(scans.size()); + scans.push_back(scan); + return true; } - scans.push_back(scan); - return true; -} -//! Two branches read the same tables when their scans pair up one to one as scans that can be shared -static bool ReadSameTables(const ScalarAggregateMerger::Branch &a, const ScalarAggregateMerger::Branch &b) { - if (a.scans.size() != b.scans.size()) { - return false; + optional_ptr> FindCandidates(const LogicalGet &scan) const { + auto entry = relation_index.find(HashRelation(scan)); + if (entry == relation_index.end()) { + return nullptr; + } + return &entry->second; + } + + vector> scans; + unordered_map> relation_index; +}; + +//===--------------------------------------------------------------------===// +// Branch: [projection ->] ungrouped aggregate -> filters -> plain scan(s) +//===--------------------------------------------------------------------===// +//! One leaf of a cross-product tree that can be merged with its siblings +struct ScalarAggregateMerger::Branch { + //! The leaf's position in the collected cross-product leaves + idx_t leaf_index; + //! The projection over the aggregate, if any + optional_ptr projection; + reference aggregate; + //! The slot under the filters: the scan, or the cross product of scans of different tables (a FROM list) + reference> relation; + ScanCollection scans; + //! The filters' predicates, with ANDs split into their conjuncts + vector> conjuncts; +}; + +//! One of the first branch's scans, which the merged leaf keeps, and the columns it gains for the other branches +struct ScalarAggregateMerger::MergeTarget { + explicit MergeTarget(LogicalGet &scan_p) : scan(scan_p) { + auto &column_ids = scan_p.GetColumnIds(); + column_bindings.reserve(column_ids.size()); + for (idx_t i = 0; i < column_ids.size(); i++) { + // Keep the first position if a column occurs more than once. + column_bindings.emplace(column_ids[i].GetPrimaryIndex(), + ColumnBinding(scan_p.table_index, ProjectionIndex(i))); + } } - for (auto &scan : a.scans) { - bool found = false; - for (auto &other : b.scans) { - found = found || CanShareScan(scan.get(), other.get()); + + //! Where this target reads column, allocating a position without changing the scan until the merge is accepted. + ColumnBinding BindingFor(column_t column) { + auto entry = column_bindings.find(column); + if (entry != column_bindings.end()) { + return entry->second; } - if (!found) { - return false; + ColumnBinding binding(scan.get().table_index, + ProjectionIndex(scan.get().GetColumnIds().size() + added_columns.size())); + column_bindings.emplace(column, binding); + added_columns.emplace_back(column, binding); + return binding; + } + + void ApplyAddedColumns() { + for (auto &entry : added_columns) { + auto position = scan.get().AddColumnId(entry.first); + D_ASSERT(position == entry.second.column_index); + (void)position; } + added_columns.clear(); } - return true; + +private: + reference scan; + //! A column the scan gains, and the binding that column lands on + vector> added_columns; + unordered_map column_bindings; +}; + +static hash_t HashBranch(const ScalarAggregateMerger::Branch &branch) { + auto result = Hash(branch.scans.size()); + // CanShareWith matches scans irrespective of their order. + for (auto &scan : branch.scans) { + result += Hash(HashScan(scan.get())); + } + return result; } //! Equal conjuncts, or the same comparison with its sides swapped (a = b and b = a) @@ -243,14 +380,46 @@ static bool IsSameConjunct(const Expression &a, const Expression &b) { BoundComparisonExpression::Right(left).Equals(BoundComparisonExpression::Left(right)); } -static bool ContainsConjunct(const vector> &conjuncts, const Expression &expr) { - for (auto &conjunct : conjuncts) { - if (IsSameConjunct(*conjunct, expr)) { - return true; +//! Borrows immutable expressions. Keep the index within the lifetime of the expressions it searches. +class ScalarAggregateMerger::ConjunctIndex { +public: + void Add(const Expression &expr) { + conjuncts[HashConjunct(expr)].push_back(expr); + } + + bool Contains(const Expression &expr) const { + auto entry = conjuncts.find(HashConjunct(expr)); + return entry != conjuncts.end() && Contains(entry->second, expr); + } + +private: + static hash_t HashConjunct(const Expression &expr) { + if (!BoundComparisonExpression::IsComparison(expr)) { + return expr.Hash(); + } + // IsSameConjunct also matches flipped comparisons, without comparing their function bind data. + auto type = expr.GetExpressionType(); + auto flipped_type = FlipComparisonExpression(type); + if (flipped_type < type) { + type = flipped_type; } + auto &comparison = expr.Cast(); + auto operands = Hash(BoundComparisonExpression::Left(comparison).Hash()) + + Hash(BoundComparisonExpression::Right(comparison).Hash()); + return CombineHash(Hash(static_cast(type)), operands); } - return false; -} + + static bool Contains(const vector> &bucket, const Expression &expr) { + for (auto &conjunct : bucket) { + if (IsSameConjunct(conjunct.get(), expr)) { + return true; + } + } + return false; + } + + unordered_map>> conjuncts; +}; static void CollectBindings(const Expression &expr, column_binding_set_t &bindings) { ExpressionIterator::VisitExpression( @@ -292,25 +461,6 @@ static bool TreeHasProjectionMap(const LogicalOperator &op) { return false; } -//! Where `target` reads `column`: the binding it has, or the one it gains once its group merges -static ColumnBinding TargetBinding(ScalarAggregateMerger::MergeTarget &target, column_t column) { - auto &scan = target.scan.get(); - auto &column_ids = scan.GetColumnIds(); - for (idx_t i = 0; i < column_ids.size(); i++) { - if (column_ids[i].GetPrimaryIndex() == column) { - return ColumnBinding(scan.table_index, ProjectionIndex(i)); - } - } - for (auto &entry : target.added_columns) { - if (entry.first == column) { - return entry.second; - } - } - ColumnBinding binding(scan.table_index, ProjectionIndex(column_ids.size() + target.added_columns.size())); - target.added_columns.emplace_back(column, binding); - return binding; -} - //===--------------------------------------------------------------------===// // ScalarAggregateMerger //===--------------------------------------------------------------------===// @@ -318,16 +468,17 @@ ScalarAggregateMerger::ScalarAggregateMerger(Optimizer &optimizer) : optimizer(o } void ScalarAggregateMerger::Optimize(unique_ptr &plan) { - // rebuilding a cross-product tree would move the positions a projection map names: only plans without them + // Merging or removing leaves moves the positions a projection map names: only plans without them. if (TreeHasProjectionMap(*plan)) { return; } VisitOperator(plan); - if (replacements.empty()) { + if (replacements.Empty()) { return; } - ColumnBindingReplacer replacer; - replacer.replacement_bindings = std::move(replacements); + auto binding_replacements = std::move(replacements); + replacements = BindingReplacementGraph(); + ColumnBindingReplacer replacer(binding_replacements); replacer.VisitOperator(*plan); plan->ResolveOperatorTypes(); } @@ -352,14 +503,19 @@ static void CollectLeaves(unique_ptr &op, vector>> &leaves, - const unique_ptr &leaf) { - for (idx_t i = 0; i < leaves.size(); i++) { - if (&leaves[i].get() == &leaf) { - return i; - } +//! Remove empty cross products and collapse those with only one surviving child. +static void PruneCrossProduct(unique_ptr &op) { + if (!op || op->type != LogicalOperatorType::LOGICAL_CROSS_PRODUCT) { + return; + } + D_ASSERT(op->children.size() == 2); + for (auto &child : op->children) { + PruneCrossProduct(child); + } + if (!op->children[0] || !op->children[1]) { + auto child = std::move(op->children[op->children[0] ? 0 : 1]); + op = std::move(child); } - throw InternalException("ScalarAggregateMerger: a branch's leaf is not among its tree's leaves"); } bool ScalarAggregateMerger::IsWorthMerging(const Branch &branch) { @@ -382,21 +538,25 @@ void ScalarAggregateMerger::MergeCrossProduct(unique_ptr &op) { VisitOperator(leaf.get()); } vector branches; - for (auto &leaf : leaves) { - TryMatchBranch(leaf, branches); + for (idx_t i = 0; i < leaves.size(); i++) { + TryMatchBranch(leaves, i, branches); } // groups of branches that read the same tables, in the order their first branch appears vector> groups; + unordered_map> group_index; for (idx_t i = 0; i < branches.size(); i++) { bool placed = false; - for (auto &group : groups) { - if (ReadSameTables(branches[group[0]], branches[i])) { + auto &candidates = group_index[HashBranch(branches[i])]; + for (auto group_idx : candidates) { + auto &group = groups[group_idx]; + if (branches[group[0]].scans.CanShareWith(branches[i].scans)) { group.push_back(i); placed = true; break; } } if (!placed) { + candidates.push_back(groups.size()); groups.push_back({i}); } } @@ -412,33 +572,31 @@ void ScalarAggregateMerger::MergeCrossProduct(unique_ptr &op) { if (!merged_leaf) { continue; } - merged_leaves[LeafPosition(leaves, branches[group[0]].leaf.get())] = std::move(merged_leaf); + merged_leaves[branches[group[0]].leaf_index] = std::move(merged_leaf); for (idx_t k = 1; k < group.size(); k++) { - removed[LeafPosition(leaves, branches[group[k]].leaf.get())] = true; + removed[branches[group[k]].leaf_index] = true; } changed = true; } if (!changed) { return; } - // rebuild the tree over the leaves that remain: a cross product's bindings are its children's, so their order - // changes nothing above it - vector> kept; + // Keep the surviving tree's shape instead of rebuilding it as a left-deep chain. + // Finish all leaf-slot updates before pruning, which invalidates the references in leaves and branches. for (idx_t i = 0; i < leaves.size(); i++) { if (removed[i]) { - continue; + leaves[i].get().reset(); + } else if (merged_leaves[i]) { + leaves[i].get() = std::move(merged_leaves[i]); } - kept.push_back(merged_leaves[i] ? std::move(merged_leaves[i]) : std::move(leaves[i].get())); - } - auto tree = std::move(kept[0]); - for (idx_t i = 1; i < kept.size(); i++) { - tree = LogicalCrossProduct::Create(std::move(tree), std::move(kept[i])); } - op = std::move(tree); + PruneCrossProduct(op); + D_ASSERT(op); } -void ScalarAggregateMerger::TryMatchBranch(unique_ptr &leaf, vector &branches) { - reference op = *leaf; +void ScalarAggregateMerger::TryMatchBranch(const vector>> &leaves, + idx_t leaf_index, vector &branches) { + reference op = *leaves[leaf_index].get(); optional_ptr projection; if (op.get().type == LogicalOperatorType::LOGICAL_PROJECTION) { projection = &op.get().Cast(); @@ -471,11 +629,11 @@ void ScalarAggregateMerger::TryMatchBranch(unique_ptr &leaf, ve return; } } - vector> scans; - if (!CollectScans(*relation.get(), scans)) { + ScanCollection scans; + if (!scans.Collect(*relation.get())) { return; } - branches.push_back(Branch {leaf, projection, aggregate, relation, std::move(scans), std::move(conjuncts)}); + branches.push_back(Branch {leaf_index, projection, aggregate, relation, std::move(scans), std::move(conjuncts)}); } unique_ptr ScalarAggregateMerger::MergeBranches(vector &branches, const vector &group) { @@ -483,21 +641,19 @@ unique_ptr ScalarAggregateMerger::MergeBranches(vector auto &first = branches[group[0]]; // every branch's scan bindings land on the first branch's scan of the same table, which gains the columns it // lacks once the group is known to merge + // Targets have the first branch's scan order, which FindCompatible returns. vector targets; + targets.reserve(first.scans.size()); for (auto &scan : first.scans) { - targets.push_back(MergeTarget {scan, {}}); + targets.emplace_back(scan.get()); } vector> remaps(group.size()); for (idx_t k = 1; k < group.size(); k++) { for (auto &branch_scan : branches[group[k]].scans) { auto &scan = branch_scan.get(); - optional_ptr target; - for (auto &candidate : targets) { - if (CanShareScan(candidate.scan.get(), scan)) { - target = &candidate; - } - } - D_ASSERT(target); + auto target_index = first.scans.FindCompatible(scan); + D_ASSERT(target_index.IsValid()); + auto &target = targets[target_index.GetIndex()]; auto &column_ids = scan.GetColumnIds(); for (idx_t i = 0; i < column_ids.size(); i++) { // nothing refers to the empty placeholder @@ -505,7 +661,7 @@ unique_ptr ScalarAggregateMerger::MergeBranches(vector continue; } remaps[k][ColumnBinding(scan.table_index, ProjectionIndex(i))] = - TargetBinding(*target, column_ids[i].GetPrimaryIndex()); + target.BindingFor(column_ids[i].GetPrimaryIndex()); } } } @@ -519,20 +675,35 @@ unique_ptr ScalarAggregateMerger::MergeBranches(vector } } vector> shared; - for (auto &conjunct : conjuncts[0]) { - bool everywhere = !ContainsConjunct(shared, *conjunct); - for (idx_t k = 1; everywhere && k < group.size(); k++) { - everywhere = ContainsConjunct(conjuncts[k], *conjunct); + vector>> own(group.size()); + { + vector conjunct_indexes(group.size()); + for (idx_t k = 1; k < group.size(); k++) { + for (auto &conjunct : conjuncts[k]) { + conjunct_indexes[k].Add(*conjunct); + } } - if (everywhere) { - shared.push_back(conjunct->Copy()); + ConjunctIndex shared_index; + expression_set_t tested; + for (auto &conjunct : conjuncts[0]) { + // Do not repeat failed searches for identical conjuncts either. + if (!tested.insert(*conjunct).second || shared_index.Contains(*conjunct)) { + continue; + } + bool everywhere = true; + for (idx_t k = 1; everywhere && k < group.size(); k++) { + everywhere = conjunct_indexes[k].Contains(*conjunct); + } + if (everywhere) { + shared.push_back(conjunct->Copy()); + shared_index.Add(*shared.back()); + } } - } - vector>> own(group.size()); - for (idx_t k = 0; k < group.size(); k++) { - for (auto &conjunct : conjuncts[k]) { - if (!ContainsConjunct(shared, *conjunct)) { - own[k].push_back(std::move(conjunct)); + for (idx_t k = 0; k < group.size(); k++) { + for (auto &conjunct : conjuncts[k]) { + if (!shared_index.Contains(*conjunct)) { + own[k].push_back(std::move(conjunct)); + } } } } @@ -558,11 +729,7 @@ unique_ptr ScalarAggregateMerger::MergeBranches(vector // the group merges: the target scans read the added columns for (auto &target : targets) { - for (auto &entry : target.added_columns) { - auto position = target.scan.get().AddColumnId(entry.first); - D_ASSERT(position == entry.second.column_index); - (void)position; - } + target.ApplyAddedColumns(); } // each branch's own predicate (none: every row the shared conjuncts keep) vector> predicates(group.size()); @@ -613,14 +780,14 @@ unique_ptr ScalarAggregateMerger::MergeBranches(vector for (idx_t i = 0; i < expressions.size(); i++) { auto copy = expressions[i]->Copy(); RemapBindings(copy, to_merged); - replacements.emplace_back(ColumnBinding(branch.projection->table_index, ProjectionIndex(i)), - ColumnBinding(projection_index, ProjectionIndex(columns.size()))); + replacements.Add(ColumnBinding(branch.projection->table_index, ProjectionIndex(i)), + ColumnBinding(projection_index, ProjectionIndex(columns.size()))); columns.push_back(std::move(copy)); } } else { for (idx_t j = 0; j < aggregate.expressions.size(); j++) { - replacements.emplace_back(ColumnBinding(aggregate.aggregate_index, ProjectionIndex(j)), - ColumnBinding(projection_index, ProjectionIndex(columns.size()))); + replacements.Add(ColumnBinding(aggregate.aggregate_index, ProjectionIndex(j)), + ColumnBinding(projection_index, ProjectionIndex(columns.size()))); columns.push_back(make_uniq( aggregate.expressions[j]->GetReturnType(), ColumnBinding(aggregate_index, ProjectionIndex(offsets[k] + j)))); @@ -634,9 +801,13 @@ unique_ptr ScalarAggregateMerger::MergeBranches(vector if (every_branch_restricted) { // branches with the same predicate (q9 has three per range) contribute one alternative vector> alternatives; - for (auto &predicate : predicates) { - if (!ContainsConjunct(alternatives, *predicate)) { - alternatives.push_back(predicate->Copy()); + { + ConjunctIndex alternative_index; + for (auto &predicate : predicates) { + if (!alternative_index.Contains(*predicate)) { + alternatives.push_back(predicate->Copy()); + alternative_index.Add(*alternatives.back()); + } } } // the OR is a new expression: the rewrite rules that ran before the merge (predicate factoring) derive from it diff --git a/src/duckdb/src/optimizer/topn_optimizer.cpp b/src/duckdb/src/optimizer/topn_optimizer.cpp index bf8608355..4a710a68d 100644 --- a/src/duckdb/src/optimizer/topn_optimizer.cpp +++ b/src/duckdb/src/optimizer/topn_optimizer.cpp @@ -60,32 +60,18 @@ bool TopN::CanOptimize(LogicalOperator &op, optional_ptr context) return false; } -void TopN::PushdownDynamicFilters(LogicalTopN &op) { - // pushdown dynamic filters through the Top-N operator - bool nulls_first = op.orders[0].null_order == OrderByNullType::NULLS_FIRST; - auto &type = op.orders[0].expression->GetReturnType(); - if (!TypeIsNumeric(type.InternalType()) && type.id() != LogicalTypeId::VARCHAR) { - // only supported for numeric and varchar types - return; - } - if (op.orders[0].expression->GetExpressionType() != ExpressionType::BOUND_COLUMN_REF) { - // we can only pushdown on ORDER BY [col] currently - return; - } - if (op.dynamic_filter) { - // dynamic filter is already set - return; - } - auto &colref = op.orders[0].expression->Cast(); +shared_ptr TopN::PushDynamicFilterIntoScans(ClientContext &context, LogicalOperator &child, + ColumnBinding binding, const LogicalType &type, + bool nulls_first, ExpressionType comparison_type) { vector columns; JoinFilterPushdownColumn column; - column.probe_column_index = colref.Binding(); + column.probe_column_index = binding; columns.emplace_back(column); vector pushdown_targets; - JoinFilterPushdownOptimizer::GetPushdownFilterTargets(*op.children[0], std::move(columns), pushdown_targets); + JoinFilterPushdownOptimizer::GetPushdownFilterTargets(child, std::move(columns), pushdown_targets); if (pushdown_targets.empty()) { // no pushdown targets - return; + return nullptr; } for (auto &target : pushdown_targets) { auto &pushed_column = target.columns[0]; @@ -95,28 +81,19 @@ void TopN::PushdownDynamicFilters(LogicalTopN &op) { // the pushed expression cannot be reconstructed on top of the raw scan value in the sort // key's type (e.g. a non-integral cast or a VARIANT in between), or the cast chain is not // order-preserving (an explicit TRY_CAST, or a cast that can throw) - bail out - return; + return nullptr; + } + bool preserves_cast_errors = false; + RuntimeFilterCastUtil::CreateRuntimeFilterInputExpression(context, pushed_column, preserves_cast_errors); + if (preserves_cast_errors) { + // the reconstructed expression can raise an error for a row that the filter would otherwise skip + return nullptr; } } // found pushdown targets! generate dynamic filters - ExpressionType comparison_type; - if (op.orders[0].type == OrderType::ASCENDING) { - // for ascending order, we want the lowest N elements, so we filter on C <= [boundary] - // if we only have a single order clause, we can filter on C < boundary - comparison_type = - op.orders.size() == 1 ? ExpressionType::COMPARE_LESSTHAN : ExpressionType::COMPARE_LESSTHANOREQUALTO; - } else { - // for descending order, we want the highest N elements, so we filter on C >= [boundary] - // if we only have a single order clause, we can filter on C > boundary - comparison_type = - op.orders.size() == 1 ? ExpressionType::COMPARE_GREATERTHAN : ExpressionType::COMPARE_GREATERTHANOREQUALTO; - } Value minimum_value = type.InternalType() == PhysicalType::VARCHAR ? Value("") : Value::MinimumValue(type); auto filter_data = make_shared_ptr(comparison_type, std::move(minimum_value)); - // put the filter into the Top-N clause - op.dynamic_filter = filter_data; - for (auto &target : pushdown_targets) { auto &get = target.get; D_ASSERT(target.columns.size() == 1); @@ -151,6 +128,41 @@ void TopN::PushdownDynamicFilters(LogicalTopN &op) { make_uniq(CreateOptionalFilterExpression( std::move(pushed_expr), pushed_column.storage_type))); } + return filter_data; +} + +void TopN::PushdownDynamicFilters(LogicalTopN &op) { + // pushdown dynamic filters through the Top-N operator + bool nulls_first = op.orders[0].null_order == OrderByNullType::NULLS_FIRST; + auto &type = op.orders[0].expression->GetReturnType(); + if (!TypeIsNumeric(type.InternalType()) && type.id() != LogicalTypeId::VARCHAR) { + // only supported for numeric and varchar types + return; + } + if (op.orders[0].expression->GetExpressionType() != ExpressionType::BOUND_COLUMN_REF) { + // we can only pushdown on ORDER BY [col] currently + return; + } + if (op.dynamic_filter) { + // dynamic filter is already set + return; + } + auto &colref = op.orders[0].expression->Cast(); + ExpressionType comparison_type; + if (op.orders[0].type == OrderType::ASCENDING) { + // for ascending order, we want the lowest N elements, so we filter on C <= [boundary] + // if we only have a single order clause, we can filter on C < boundary + comparison_type = + op.orders.size() == 1 ? ExpressionType::COMPARE_LESSTHAN : ExpressionType::COMPARE_LESSTHANOREQUALTO; + } else { + // for descending order, we want the highest N elements, so we filter on C >= [boundary] + // if we only have a single order clause, we can filter on C > boundary + comparison_type = + op.orders.size() == 1 ? ExpressionType::COMPARE_GREATERTHAN : ExpressionType::COMPARE_GREATERTHANOREQUALTO; + } + // put the filter into the Top-N clause + op.dynamic_filter = + PushDynamicFilterIntoScans(context, *op.children[0], colref.Binding(), type, nulls_first, comparison_type); } unique_ptr TopN::Optimize(unique_ptr op) { diff --git a/src/duckdb/src/optimizer/topn_window_elimination.cpp b/src/duckdb/src/optimizer/topn_window_elimination.cpp index 6fc1730f7..db0ced397 100644 --- a/src/duckdb/src/optimizer/topn_window_elimination.cpp +++ b/src/duckdb/src/optimizer/topn_window_elimination.cpp @@ -309,6 +309,9 @@ unique_ptr TopNWindowElimination::OptimizeInternal(unique_ptr> return function_binder.BindAggregateFunction(fun, std::move(aggregate_params)); } +//! Whether the aggregate keeps the sign of a zero it returns: a FLOAT or DOUBLE stored as a sort key does not. +//! Struct-packed payloads are not checked. +bool TopNWindowElimination::AggregateKeepsZeroSign(const LogicalWindow &window, + const vector> &payload, + const TopNWindowEliminationParameters ¶ms) const { + if (payload.size() > 1) { + return true; + } + auto &order_key = window.expressions[0]->Cast().OrderBy()[0].expression; + const auto returned_type = payload.empty() ? order_key->GetReturnType() : payload[0]->GetReturnType(); + if (returned_type.id() != LogicalTypeId::FLOAT && returned_type.id() != LogicalTypeId::DOUBLE) { + return true; + } + + vector> aggregate_params; + if (!payload.empty()) { + aggregate_params.push_back(payload[0]->Copy()); + } + aggregate_params.push_back(order_key->Copy()); + if (params.limit > 1) { + aggregate_params.push_back(make_uniq(Value::BIGINT(params.limit))); + } + auto aggregate = CreateAggregateExpression(std::move(aggregate_params), !payload.empty(), params); + auto &function = aggregate->Cast().Function(); + return !function.GetProperties().GetBooleanProperty(BoundAggregateExpression::ARG_STORED_AS_SORT_KEY_PROPERTY); +} + unique_ptr TopNWindowElimination::CreateAggregateOperator(LogicalWindow &window, vector> args, const TopNWindowEliminationParameters ¶ms) const { diff --git a/src/duckdb/src/optimizer/window_fusion.cpp b/src/duckdb/src/optimizer/window_fusion.cpp index fcef82811..9a9866483 100644 --- a/src/duckdb/src/optimizer/window_fusion.cpp +++ b/src/duckdb/src/optimizer/window_fusion.cpp @@ -47,10 +47,10 @@ bool CanRank(const BoundWindowExpression &wexpr, LogicalOperator &op) { return false; } - // Natural orders can always rank + // If there is no sorting, then the ranks are degenerate and not unique. auto &order_bys = wexpr.OrderBy(); if (order_bys.empty()) { - return true; + return false; } // For the other rankers to apply, we must have a UCC in play diff --git a/src/duckdb/src/parallel/async_result.cpp b/src/duckdb/src/parallel/async_result.cpp index 3159bcce0..11f9aa2f4 100644 --- a/src/duckdb/src/parallel/async_result.cpp +++ b/src/duckdb/src/parallel/async_result.cpp @@ -5,6 +5,9 @@ #include "duckdb/parallel/task_scheduler.hpp" #include "duckdb/parallel/task_executor.hpp" #include "duckdb/execution/executor.hpp" +#include "duckdb/execution/execution_context.hpp" +#include "duckdb/execution/physical_operator_states.hpp" +#include "duckdb/parallel/pipeline.hpp" #include "duckdb/execution/physical_table_scan_enum.hpp" #include "duckdb/logging/log_type.hpp" #include "duckdb/logging/logger.hpp" @@ -195,6 +198,19 @@ void AsyncResult::ExecuteTasksSynchronously(ClientContext &context) { result_type = AsyncResultType::HAVE_MORE_OUTPUT; } +SourceResultType AsyncResult::ScheduleOrExecute(ExecutionContext &context, OperatorSourceInput &input, + StateWithBlockableTasks &state) { + if (input.interrupt_state.CanCallback()) { + annotated_lock_guard guard(state.lock); + if (state.CanBlock()) { + ScheduleTasks(input.interrupt_state, context.pipeline->executor); + return SourceResultType::BLOCKED; + } + } + ExecuteTasksSynchronously(context.client); + return SourceResultType::HAVE_MORE_OUTPUT; +} + AsyncResult AsyncResult::FromTasks(vector> &&tasks, TaskSchedulerType pool_type) { if (tasks.empty()) { return AsyncResult(SourceResultType::HAVE_MORE_OUTPUT); @@ -265,9 +281,11 @@ bool AsyncResult::TryGenerateTestResult(AsyncResult &result) { tasks.push_back(make_uniq(rand() % 32)); tasks.push_back(make_uniq(rand() % 32)); tasks.push_back(make_uniq(rand() % 32)); + break; #ifndef AVOID_DUCKDB_DEBUG_ASYNC_THROW case 1: tasks.push_back(make_uniq(rand() % 32)); + break; #endif default: break; diff --git a/src/duckdb/src/parallel/pipeline_broadcast_exchange.cpp b/src/duckdb/src/parallel/pipeline_broadcast_exchange.cpp index aa4a1688d..e10f427ee 100644 --- a/src/duckdb/src/parallel/pipeline_broadcast_exchange.cpp +++ b/src/duckdb/src/parallel/pipeline_broadcast_exchange.cpp @@ -574,11 +574,11 @@ PipelineBroadcastExchange::ConsumerState::operator=(ConsumerState &&other) noexc PipelineBroadcastExchange::~PipelineBroadcastExchange() = default; -PipelineBroadcastExchangeLocalState::PipelineBroadcastExchangeLocalState(ClientContext &context, +PipelineBroadcastExchangeLocalState::PipelineBroadcastExchangeLocalState(ClientContext &context_p, const PipelineBroadcastExchange &exchange, idx_t producer_base_batch_index_p) - : producer_base_batch_index(producer_base_batch_index_p), supports_batch_index(exchange.SupportsBatchIndex()) { - vector> direct_pipeline_refs; + : context(context_p), producer_base_batch_index(producer_base_batch_index_p), + supports_batch_index(exchange.SupportsBatchIndex()) { { annotated_lock_guard guard(exchange.lock); auto summary = exchange.GetConsumerSummaryLocked(); @@ -590,16 +590,30 @@ PipelineBroadcastExchangeLocalState::PipelineBroadcastExchangeLocalState(ClientC direct_pipeline_refs = exchange.direct_pipelines; } - for (auto &pipeline_ref : direct_pipeline_refs) { - auto &pipeline = pipeline_ref.get(); + direct_executors.resize(direct_pipeline_refs.size()); + for (idx_t index = 0; index < direct_pipeline_refs.size(); index++) { + auto &pipeline = direct_pipeline_refs[index].get(); pipeline.PrepareExternalInput(); - direct_executors.push_back(make_uniq(context, pipeline)); + // Ordered consumers must register their local state before batch progress advances. + if (pipeline.GetSink()->RequiredPartitionInfo().AnyRequired()) { + GetOrCreateDirectExecutor(index); + } auto input_chunk = make_uniq(); input_chunk->InitializeEmpty(exchange.Types()); direct_input_chunks.push_back(std::move(input_chunk)); } } +PipelineExecutor &PipelineBroadcastExchangeLocalState::GetOrCreateDirectExecutor(idx_t index) { + D_ASSERT(index >= direct_finalize_idx); + auto &executor = direct_executors[index]; + if (!executor) { + auto &pipeline = direct_pipeline_refs[index].get(); + executor = make_uniq(context, pipeline); + } + return *executor; +} + void PipelineBroadcastExchange::SetLogOperator(const PhysicalOperator &op) { annotated_lock_guard guard(lock); log_operator = &op; @@ -914,7 +928,7 @@ SinkResultType PipelineBroadcastExchangeLocalState::Push(DataChunk &chunk, const auto source_partition_data = GetSourcePartitionData(partition_info); auto source_min_batch_index = GetSourceMinBatchIndex(partition_info); for (; direct_idx < direct_executors.size(); direct_idx++) { - auto &executor = *direct_executors[direct_idx]; + auto &executor = GetOrCreateDirectExecutor(direct_idx); executor.SetInterruptState(interrupt_state); if (executor.IsFinishedProcessing()) { resuming = false; @@ -958,6 +972,9 @@ SinkNextBatchType PipelineBroadcastExchangeLocalState::NextBatch(const SourcePar } for (; direct_next_batch_idx < direct_executors.size(); direct_next_batch_idx++) { + if (!direct_executors[direct_next_batch_idx]) { + continue; + } auto &executor = *direct_executors[direct_next_batch_idx]; executor.SetInterruptState(interrupt_state); PipelineExecuteResult result; @@ -978,6 +995,9 @@ SinkNextBatchType PipelineBroadcastExchangeLocalState::UpdateMinBatchIndex(const const InterruptState &interrupt_state) { auto source_min_batch_index = GetSourceMinBatchIndex(partition_info); for (; direct_min_batch_idx < direct_executors.size(); direct_min_batch_idx++) { + if (!direct_executors[direct_min_batch_idx]) { + continue; + } auto &executor = *direct_executors[direct_min_batch_idx]; executor.SetInterruptState(interrupt_state); if (executor.IsFinishedProcessing()) { @@ -996,7 +1016,8 @@ SinkCombineResultType PipelineBroadcastExchangeLocalState::Finish(const SourcePa const InterruptState &interrupt_state) { auto source_min_batch_index = GetSourceMinBatchIndex(partition_info); for (; direct_finalize_idx < direct_executors.size(); direct_finalize_idx++) { - auto &executor = *direct_executors[direct_finalize_idx]; + // Empty consumers still finalize, but need only one executor at a time. + auto &executor = GetOrCreateDirectExecutor(direct_finalize_idx); executor.SetInterruptState(interrupt_state); auto result = PipelineExecuteResult::NOT_FINISHED; while (result == PipelineExecuteResult::NOT_FINISHED) { @@ -1005,6 +1026,8 @@ SinkCombineResultType PipelineBroadcastExchangeLocalState::Finish(const SourcePa if (result == PipelineExecuteResult::INTERRUPTED) { return SinkCombineResultType::BLOCKED; } + direct_input_chunks[direct_finalize_idx].reset(); + direct_executors[direct_finalize_idx].reset(); } return SinkCombineResultType::FINISHED; } diff --git a/src/duckdb/src/parser/expression/value_expression.cpp b/src/duckdb/src/parser/expression/value_expression.cpp index 9ab1a5bca..ddb1c343b 100644 --- a/src/duckdb/src/parser/expression/value_expression.cpp +++ b/src/duckdb/src/parser/expression/value_expression.cpp @@ -182,7 +182,7 @@ static unique_ptr GeometryExpression(const Value &value) { static bool HasUnsupportedVariantKeys(const VariantNode &node) { // Struct literals require nonempty, case-insensitively unique keys; inspect before the lossy STRUCT conversion. - if (node.GetTypeId() == VariantLogicalType::OBJECT) { + if (node.GetTypeId() == LogicalTypeId::STRUCT) { identifier_set_t names; for (auto &child : node.GetObjectChildren()) { if (child.key.GetSize() == 0 || !names.insert(Identifier(child.key.GetString())).second || @@ -190,7 +190,7 @@ static bool HasUnsupportedVariantKeys(const VariantNode &node) { return true; } } - } else if (node.GetTypeId() == VariantLogicalType::ARRAY) { + } else if (node.GetTypeId() == LogicalTypeId::LIST) { for (auto child : node.GetArrayChildren()) { if (HasUnsupportedVariantKeys(child)) { return true; diff --git a/src/duckdb/src/parser/parsed_expression_iterator.cpp b/src/duckdb/src/parser/parsed_expression_iterator.cpp index 0a7195b10..8a26dc0bd 100644 --- a/src/duckdb/src/parser/parsed_expression_iterator.cpp +++ b/src/duckdb/src/parser/parsed_expression_iterator.cpp @@ -94,6 +94,12 @@ void ParsedExpressionIterator::EnumerateTableRefChildren( if (j_ref.condition) { expr_callback(j_ref.condition); } + for (auto &column : j_ref.duplicate_eliminated_columns) { + expr_callback(column); + } + if (j_ref.ranking_expression) { + expr_callback(j_ref.ranking_expression); + } break; } case TableReferenceType::PIVOT: { @@ -102,6 +108,19 @@ void ParsedExpressionIterator::EnumerateTableRefChildren( for (auto &aggr : p_ref.aggregates) { expr_callback(aggr); } + for (auto &pivot : p_ref.pivots) { + for (auto &expr : pivot.pivot_expressions) { + expr_callback(expr); + } + for (auto &entry : pivot.entries) { + if (entry.expr) { + expr_callback(entry.expr); + } + } + if (pivot.subquery) { + EnumerateQueryNodeChildren(*pivot.subquery, expr_callback, ref_callback); + } + } break; } case TableReferenceType::SUBQUERY: { @@ -132,7 +151,7 @@ void ParsedExpressionIterator::EnumerateTableRefChildren( expr_callback(mr_ref.config->pattern); } if (mr_ref.input) { - ref_callback(*mr_ref.input); + EnumerateTableRefChildren(*mr_ref.input, expr_callback, ref_callback); } break; } @@ -143,7 +162,13 @@ void ParsedExpressionIterator::EnumerateTableRefChildren( } break; } - case TableReferenceType::BASE_TABLE: + case TableReferenceType::BASE_TABLE: { + auto &base_ref = ref.Cast(); + if (base_ref.at_clause && base_ref.at_clause->ExpressionMutable()) { + expr_callback(base_ref.at_clause->ExpressionMutable()); + } + break; + } case TableReferenceType::EMPTY_FROM: case TableReferenceType::COLUMN_DATA: case TableReferenceType::DELIM_GET: diff --git a/src/duckdb/src/parser/peg/transformer/peg_transformer_factory.cpp b/src/duckdb/src/parser/peg/transformer/peg_transformer_factory.cpp index 11315df7d..69d7ac3f3 100644 --- a/src/duckdb/src/parser/peg/transformer/peg_transformer_factory.cpp +++ b/src/duckdb/src/parser/peg/transformer/peg_transformer_factory.cpp @@ -173,6 +173,7 @@ PEGTransformerFactory::PEGTransformerFactory(ParsedGrammar &grammar_p) : grammar grammar.SetExpressionDepth("Type", ExpressionDepthKind::NESTING); grammar.SetExpressionDepth("NestedType", ExpressionDepthKind::NESTING); grammar.SetExpressionDepth("SubqueryReference", ExpressionDepthKind::NESTING); + grammar.SetExpressionDepth("WithStatement", ExpressionDepthKind::NESTING); grammar.SetExpressionDepth("CustomPrefixExpression", ExpressionDepthKind::NESTING); grammar.SetExpressionDepth("NotExpression", ExpressionDepthKind::CHAIN); grammar.SetExpressionDepth("IsExpressionContinuation", ExpressionDepthKind::CHAIN); diff --git a/src/duckdb/src/parser/peg/transformer/transform_generated_trampoline.cpp b/src/duckdb/src/parser/peg/transformer/transform_generated_trampoline.cpp index f6d34a8c4..826a8a6e8 100644 --- a/src/duckdb/src/parser/peg/transformer/transform_generated_trampoline.cpp +++ b/src/duckdb/src/parser/peg/transformer/transform_generated_trampoline.cpp @@ -6,243 +6,243 @@ namespace duckdb { -static const TransformChildPlan FRAME_CHILDREN_0[] = {{PEGRuleId::AlterOptions, - TransformChildKind::REQUIRED, - 1, - 0, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_0 = {FRAME_CHILDREN_0, 1, 1, false, 0, {}}; -static const TransformFramePlan FRAME_PLAN_1 = {nullptr, 0, 1, false, 0, {0, 0, false, true, 0, nullptr}}; -static const TransformChildPlan FRAME_CHILDREN_1[] = {{PEGRuleId::AlterTableOptions, - TransformChildKind::LIST, - 3, - 2, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}, - {PEGRuleId::BaseTableName, - TransformChildKind::REQUIRED, - 2, - 1, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}, - {PEGRuleId::IfExists, - TransformChildKind::OPTIONAL, - 1, - 0, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_2 = {FRAME_CHILDREN_1, 3, 3, true, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_2[] = {{PEGRuleId::AlterSchemaOptions, - TransformChildKind::REQUIRED, - 3, - 2, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}, - {PEGRuleId::QualifiedName, - TransformChildKind::REQUIRED, - 2, - 1, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}, - {PEGRuleId::IfExists, - TransformChildKind::OPTIONAL, - 1, - 0, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_3 = {FRAME_CHILDREN_2, 3, 3, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_3[] = {{PEGRuleId::TopLevelConstraint, - TransformChildKind::REQUIRED, - 1, - 0, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_4 = {FRAME_CHILDREN_3, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_4[] = {{PEGRuleId::DropBehavior, - TransformChildKind::OPTIONAL, - 4, - 2, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}, - {PEGRuleId::ConstraintName, - TransformChildKind::REQUIRED, - 3, - 1, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}, - {PEGRuleId::IfExists, - TransformChildKind::OPTIONAL, - 2, - 0, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_5 = {FRAME_CHILDREN_4, 3, 3, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_5[] = {{PEGRuleId::AddColumnEntry, - TransformChildKind::REQUIRED, - 3, - 1, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}, - {PEGRuleId::IfNotExists, - TransformChildKind::OPTIONAL, - 2, - 0, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_6 = {FRAME_CHILDREN_5, 2, 2, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_6[] = {{PEGRuleId::ColumnConstraint, - TransformChildKind::OPTIONAL_REPEAT, - 3, - 3, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}, - {PEGRuleId::GeneratedColumn, - TransformChildKind::OPTIONAL, - 2, - 2, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}, - {PEGRuleId::Type, - TransformChildKind::OPTIONAL, - 1, - 1, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}, - {PEGRuleId::DottedIdentifier, - TransformChildKind::REQUIRED, - 0, - 0, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_7 = {FRAME_CHILDREN_6, 4, 4, true, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_7[] = {{PEGRuleId::DropBehavior, - TransformChildKind::OPTIONAL, - 4, - 2, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}, - {PEGRuleId::NestedColumnName, - TransformChildKind::REQUIRED, - 3, - 1, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}, - {PEGRuleId::IfExists, - TransformChildKind::OPTIONAL, - 2, - 0, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_8 = {FRAME_CHILDREN_7, 3, 3, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_8[] = {{PEGRuleId::AlterColumnEntry, - TransformChildKind::REQUIRED, - 3, - 1, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}, - {PEGRuleId::NestedColumnName, - TransformChildKind::REQUIRED, - 2, - 0, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_9 = {FRAME_CHILDREN_8, 2, 2, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_9[] = {{PEGRuleId::ColIdOrString, - TransformChildKind::REQUIRED, - 4, - 1, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}, - {PEGRuleId::NestedColumnName, - TransformChildKind::REQUIRED, - 2, - 0, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_10 = {FRAME_CHILDREN_9, 2, 2, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_10[] = {{PEGRuleId::IdentifierDot, - TransformChildKind::OPTIONAL_REPEAT, - 0, - 0, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_11 = {FRAME_CHILDREN_10, 1, 1, true, 0, {}}; -static const TransformFramePlan FRAME_PLAN_12 = {nullptr, 0, 0, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_11[] = {{PEGRuleId::ColIdOrString, - TransformChildKind::REQUIRED, - 2, - 0, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_13 = {FRAME_CHILDREN_11, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_12[] = {{PEGRuleId::Expression, - TransformChildKind::LIST, - 3, - 0, - false, - {1, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_14 = {FRAME_CHILDREN_12, 1, 1, true, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_13[] = {{PEGRuleId::OrderByExpressions, - TransformChildKind::REQUIRED, - 3, - 0, - false, - {1, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_15 = {FRAME_CHILDREN_13, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_14[] = {{PEGRuleId::RelOptionList, - TransformChildKind::REQUIRED, - 1, - 0, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_16 = {FRAME_CHILDREN_14, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_15[] = {{PEGRuleId::Expression, - TransformChildKind::REQUIRED, - 2, - 0, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_17 = {FRAME_CHILDREN_15, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_16[] = {{PEGRuleId::DropOrSet, - TransformChildKind::REQUIRED, - 0, - 0, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_18 = {FRAME_CHILDREN_16, 1, 1, false, 0, {}}; -static const TransformFramePlan FRAME_PLAN_19 = { +static const TransformChildPlan FRAME_CHILDREN_AlterStatement[] = {{PEGRuleId::AlterOptions, + TransformChildKind::REQUIRED, + 1, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_AlterStatement = {FRAME_CHILDREN_AlterStatement, 1, 1, false, 0, {}}; +static const TransformFramePlan FRAME_PLAN_ChoiceThrow = {nullptr, 0, 1, false, 0, {0, 0, false, true, 0, nullptr}}; +static const TransformChildPlan FRAME_CHILDREN_AlterTableStmt[] = {{PEGRuleId::AlterTableOptions, + TransformChildKind::LIST, + 3, + 2, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::BaseTableName, + TransformChildKind::REQUIRED, + 2, + 1, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::IfExists, + TransformChildKind::OPTIONAL, + 1, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_AlterTableStmt = {FRAME_CHILDREN_AlterTableStmt, 3, 3, true, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_AlterSchemaStmt[] = {{PEGRuleId::AlterSchemaOptions, + TransformChildKind::REQUIRED, + 3, + 2, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::QualifiedName, + TransformChildKind::REQUIRED, + 2, + 1, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::IfExists, + TransformChildKind::OPTIONAL, + 1, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_AlterSchemaStmt = {FRAME_CHILDREN_AlterSchemaStmt, 3, 3, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_AddConstraint[] = {{PEGRuleId::TopLevelConstraint, + TransformChildKind::REQUIRED, + 1, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_AddConstraint = {FRAME_CHILDREN_AddConstraint, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_DropConstraint[] = {{PEGRuleId::DropBehavior, + TransformChildKind::OPTIONAL, + 4, + 2, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::ConstraintName, + TransformChildKind::REQUIRED, + 3, + 1, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::IfExists, + TransformChildKind::OPTIONAL, + 2, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_DropConstraint = {FRAME_CHILDREN_DropConstraint, 3, 3, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_AddColumn[] = {{PEGRuleId::AddColumnEntry, + TransformChildKind::REQUIRED, + 3, + 1, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::IfNotExists, + TransformChildKind::OPTIONAL, + 2, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_AddColumn = {FRAME_CHILDREN_AddColumn, 2, 2, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_AddColumnEntry[] = {{PEGRuleId::ColumnConstraint, + TransformChildKind::OPTIONAL_REPEAT, + 3, + 3, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::GeneratedColumn, + TransformChildKind::OPTIONAL, + 2, + 2, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::Type, + TransformChildKind::OPTIONAL, + 1, + 1, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::DottedIdentifier, + TransformChildKind::REQUIRED, + 0, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_AddColumnEntry = {FRAME_CHILDREN_AddColumnEntry, 4, 4, true, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_DropColumn[] = {{PEGRuleId::DropBehavior, + TransformChildKind::OPTIONAL, + 4, + 2, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::NestedColumnName, + TransformChildKind::REQUIRED, + 3, + 1, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::IfExists, + TransformChildKind::OPTIONAL, + 2, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_DropColumn = {FRAME_CHILDREN_DropColumn, 3, 3, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_AlterColumn[] = {{PEGRuleId::AlterColumnEntry, + TransformChildKind::REQUIRED, + 3, + 1, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::NestedColumnName, + TransformChildKind::REQUIRED, + 2, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_AlterColumn = {FRAME_CHILDREN_AlterColumn, 2, 2, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_RenameColumn[] = {{PEGRuleId::ColIdOrString, + TransformChildKind::REQUIRED, + 4, + 1, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::NestedColumnName, + TransformChildKind::REQUIRED, + 2, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_RenameColumn = {FRAME_CHILDREN_RenameColumn, 2, 2, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_NestedColumnName[] = {{PEGRuleId::IdentifierDot, + TransformChildKind::OPTIONAL_REPEAT, + 0, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_NestedColumnName = {FRAME_CHILDREN_NestedColumnName, 1, 1, true, 0, {}}; +static const TransformFramePlan FRAME_PLAN_Leaf = {nullptr, 0, 0, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_ColumnCompression[] = {{PEGRuleId::ColIdOrString, + TransformChildKind::REQUIRED, + 2, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_ColumnCompression = {FRAME_CHILDREN_ColumnCompression, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_SetPartitionedBy[] = {{PEGRuleId::Expression, + TransformChildKind::LIST, + 3, + 0, + false, + {1, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_SetPartitionedBy = {FRAME_CHILDREN_SetPartitionedBy, 1, 1, true, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_SetSortedBy[] = {{PEGRuleId::OrderByExpressions, + TransformChildKind::REQUIRED, + 3, + 0, + false, + {1, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_SetSortedBy = {FRAME_CHILDREN_SetSortedBy, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_ResetOptions[] = {{PEGRuleId::RelOptionList, + TransformChildKind::REQUIRED, + 1, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_ResetOptions = {FRAME_CHILDREN_ResetOptions, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_AddDefault[] = {{PEGRuleId::Expression, + TransformChildKind::REQUIRED, + 2, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_AddDefault = {FRAME_CHILDREN_AddDefault, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_ChangeNullability[] = {{PEGRuleId::DropOrSet, + TransformChildKind::REQUIRED, + 0, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_ChangeNullability = {FRAME_CHILDREN_ChangeNullability, 1, 1, false, 0, {}}; +static const TransformFramePlan FRAME_PLAN_ChoiceEarlyIdentifierKeywordStringOperatorThrow = { nullptr, 0, 1, @@ -251,454 +251,462 @@ static const TransformFramePlan FRAME_PLAN_19 = { {ParseResultTypeBit(ParseResultType::IDENTIFIER) | ParseResultTypeBit(ParseResultType::KEYWORD) | ParseResultTypeBit(ParseResultType::STRING) | ParseResultTypeBit(ParseResultType::OPERATOR), 0, false, true, 0, nullptr}}; -static const TransformChildPlan FRAME_CHILDREN_17[] = {{PEGRuleId::UsingExpression, - TransformChildKind::OPTIONAL, - 4, - 2, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}, - {PEGRuleId::ColumnCollation, - TransformChildKind::OPTIONAL, - 3, - 1, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}, - {PEGRuleId::Type, - TransformChildKind::OPTIONAL, - 2, - 0, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_20 = {FRAME_CHILDREN_17, 3, 3, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_18[] = {{PEGRuleId::Expression, - TransformChildKind::REQUIRED, - 1, - 0, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_21 = {FRAME_CHILDREN_18, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_19[] = {{PEGRuleId::RenameAlter, - TransformChildKind::REQUIRED, - 3, - 2, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}, - {PEGRuleId::BaseTableName, - TransformChildKind::REQUIRED, - 2, - 1, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}, - {PEGRuleId::IfExists, - TransformChildKind::OPTIONAL, - 1, - 0, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_22 = {FRAME_CHILDREN_19, 3, 3, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_20[] = {{PEGRuleId::AlterSequenceOptions, - TransformChildKind::REQUIRED, - 3, - 2, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}, - {PEGRuleId::QualifiedSequenceName, - TransformChildKind::REQUIRED, - 2, - 1, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}, - {PEGRuleId::IfExists, - TransformChildKind::OPTIONAL, - 1, - 0, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_23 = {FRAME_CHILDREN_20, 3, 3, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_21[] = {{PEGRuleId::SchemaQualification, - TransformChildKind::OPTIONAL_REPEAT, - 1, - 1, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}, - {PEGRuleId::CatalogQualification, - TransformChildKind::OPTIONAL, - 0, - 0, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_24 = {FRAME_CHILDREN_21, 2, 2, true, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_22[] = {{PEGRuleId::RenameAlter, - TransformChildKind::REQUIRED, - 0, - 0, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_25 = {FRAME_CHILDREN_22, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_23[] = {{PEGRuleId::SequenceOption, - TransformChildKind::REPEAT, - 0, - 0, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_26 = {FRAME_CHILDREN_23, 1, 1, true, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_24[] = {{PEGRuleId::IfExists, - TransformChildKind::OPTIONAL, - 1, - 0, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_27 = {FRAME_CHILDREN_24, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_25[] = {{PEGRuleId::AnalyzeTarget, - TransformChildKind::OPTIONAL, - 2, - 2, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}, - {PEGRuleId::AnalyzeVerbose, - TransformChildKind::OPTIONAL, - 1, - 1, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}, - {PEGRuleId::AnalyzeKeyword, - TransformChildKind::REQUIRED, - 0, - 0, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_28 = {FRAME_CHILDREN_25, 3, 3, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_26[] = {{PEGRuleId::NameList, - TransformChildKind::OPTIONAL, - 1, - 1, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}, - {PEGRuleId::BaseTableName, - TransformChildKind::REQUIRED, - 0, - 0, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_29 = {FRAME_CHILDREN_26, 2, 2, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_27[] = {{PEGRuleId::AttachOptions, - TransformChildKind::OPTIONAL, - 6, - 4, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}, - {PEGRuleId::AttachAlias, - TransformChildKind::OPTIONAL, - 5, - 3, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}, - {PEGRuleId::DatabasePath, - TransformChildKind::REQUIRED, - 4, - 2, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}, - {PEGRuleId::IfNotExists, - TransformChildKind::OPTIONAL, - 2, - 1, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}, - {PEGRuleId::OrReplace, - TransformChildKind::OPTIONAL, - 1, - 0, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_30 = {FRAME_CHILDREN_27, 5, 5, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_28[] = {{PEGRuleId::Expression, - TransformChildKind::REQUIRED, - 0, - 0, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_31 = {FRAME_CHILDREN_28, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_29[] = {{PEGRuleId::ColId, - TransformChildKind::REQUIRED, - 1, - 0, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_32 = {FRAME_CHILDREN_29, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_30[] = {{PEGRuleId::GenericCopyOptionList, - TransformChildKind::REQUIRED, - 0, - 0, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_33 = {FRAME_CHILDREN_30, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_31[] = {{PEGRuleId::TableFunctionArguments, - TransformChildKind::REQUIRED, - 2, - 1, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}, - {PEGRuleId::QualifiedTableFunction, - TransformChildKind::REQUIRED, - 1, - 0, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_34 = {FRAME_CHILDREN_31, 2, 2, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_32[] = {{PEGRuleId::CheckpointForce, - TransformChildKind::OPTIONAL, - 0, - 0, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_35 = {FRAME_CHILDREN_32, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_33[] = {{PEGRuleId::CommentValue, - TransformChildKind::REQUIRED, - 5, - 2, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}, - {PEGRuleId::CommentTarget, - TransformChildKind::REQUIRED, - 3, - 1, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}, - {PEGRuleId::CommentOnType, - TransformChildKind::REQUIRED, - 2, - 0, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_36 = {FRAME_CHILDREN_33, 3, 3, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_34[] = {{PEGRuleId::StringLiteralIdentifier, - TransformChildKind::REQUIRED, - 0, - 0, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_37 = {FRAME_CHILDREN_34, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_35[] = {{PEGRuleId::ColIdOrString, - TransformChildKind::REQUIRED, - 0, - 0, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_38 = {FRAME_CHILDREN_35, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_36[] = {{PEGRuleId::ArrayBounds, - TransformChildKind::OPTIONAL_REPEAT, - 1, - 1, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}, - {PEGRuleId::TypeVariations, - TransformChildKind::REQUIRED, - 0, - 0, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_39 = {FRAME_CHILDREN_36, 2, 2, true, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_37[] = {{PEGRuleId::TypeModifiers, - TransformChildKind::OPTIONAL, - 1, - 0, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_40 = {FRAME_CHILDREN_37, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_38[] = {{PEGRuleId::TypeModifiers, - TransformChildKind::OPTIONAL, - 1, - 1, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}, - {PEGRuleId::QualifiedTypeName, - TransformChildKind::REQUIRED, - 0, - 0, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_41 = {FRAME_CHILDREN_38, 2, 2, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_39[] = {{PEGRuleId::IntervalToIntervalAsType, - TransformChildKind::REQUIRED, - 1, - 0, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_42 = {FRAME_CHILDREN_39, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_40[] = {{PEGRuleId::Interval, - TransformChildKind::REQUIRED, - 1, - 0, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_43 = {FRAME_CHILDREN_40, 1, 1, false, 0, {}}; -static const TransformFramePlan FRAME_PLAN_44 = {nullptr, 0, 1, false, 0, {0, 0, false, false, 0, nullptr}}; -static const TransformChildPlan FRAME_CHILDREN_41[] = {{PEGRuleId::MonthKeyword, - TransformChildKind::REQUIRED, - 2, - 1, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}, - {PEGRuleId::YearKeyword, - TransformChildKind::REQUIRED, - 0, - 0, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_45 = {FRAME_CHILDREN_41, 2, 2, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_42[] = {{PEGRuleId::HourKeyword, - TransformChildKind::REQUIRED, - 2, - 1, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}, - {PEGRuleId::DayKeyword, - TransformChildKind::REQUIRED, - 0, - 0, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_46 = {FRAME_CHILDREN_42, 2, 2, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_43[] = {{PEGRuleId::MinuteKeyword, - TransformChildKind::REQUIRED, - 2, - 1, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}, - {PEGRuleId::DayKeyword, - TransformChildKind::REQUIRED, - 0, - 0, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_47 = {FRAME_CHILDREN_43, 2, 2, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_44[] = {{PEGRuleId::SecondKeyword, - TransformChildKind::REQUIRED, - 2, - 1, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}, - {PEGRuleId::DayKeyword, - TransformChildKind::REQUIRED, - 0, - 0, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_48 = {FRAME_CHILDREN_44, 2, 2, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_45[] = {{PEGRuleId::MinuteKeyword, - TransformChildKind::REQUIRED, - 2, - 1, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}, - {PEGRuleId::HourKeyword, - TransformChildKind::REQUIRED, - 0, - 0, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_49 = {FRAME_CHILDREN_45, 2, 2, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_46[] = {{PEGRuleId::SecondKeyword, - TransformChildKind::REQUIRED, - 2, - 1, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}, - {PEGRuleId::HourKeyword, - TransformChildKind::REQUIRED, - 0, - 0, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_50 = {FRAME_CHILDREN_46, 2, 2, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_47[] = {{PEGRuleId::SecondKeyword, - TransformChildKind::REQUIRED, - 2, - 1, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}, - {PEGRuleId::MinuteKeyword, - TransformChildKind::REQUIRED, - 0, - 0, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_51 = {FRAME_CHILDREN_47, 2, 2, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_48[] = {{PEGRuleId::Expression, - TransformChildKind::OPTIONAL_LIST, - 2, - 0, - false, - {0, TRANSFORM_PATH_END, 0}, - {1, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_52 = {FRAME_CHILDREN_48, 1, 1, true, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_49[] = {{PEGRuleId::Expression, - TransformChildKind::OPTIONAL, - 1, - 0, - false, - {0, TRANSFORM_PATH_END, 0}, - {1, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_53 = {FRAME_CHILDREN_49, 1, 1, false, 0, {}}; -static const TransformFramePlan FRAME_PLAN_54 = { +static const TransformChildPlan FRAME_CHILDREN_AlterType[] = {{PEGRuleId::UsingExpression, + TransformChildKind::OPTIONAL, + 4, + 2, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::ColumnCollation, + TransformChildKind::OPTIONAL, + 3, + 1, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::Type, + TransformChildKind::OPTIONAL, + 2, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_AlterType = {FRAME_CHILDREN_AlterType, 3, 3, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_AndExpression[] = {{PEGRuleId::Expression, + TransformChildKind::REQUIRED, + 1, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_AndExpression = {FRAME_CHILDREN_AndExpression, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_AlterViewStmt[] = {{PEGRuleId::RenameAlter, + TransformChildKind::REQUIRED, + 3, + 2, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::BaseTableName, + TransformChildKind::REQUIRED, + 2, + 1, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::IfExists, + TransformChildKind::OPTIONAL, + 1, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_AlterViewStmt = {FRAME_CHILDREN_AlterViewStmt, 3, 3, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_AlterSequenceStmt[] = {{PEGRuleId::AlterSequenceOptions, + TransformChildKind::REQUIRED, + 3, + 2, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::QualifiedSequenceName, + TransformChildKind::REQUIRED, + 2, + 1, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::IfExists, + TransformChildKind::OPTIONAL, + 1, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_AlterSequenceStmt = {FRAME_CHILDREN_AlterSequenceStmt, 3, 3, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_QualifiedSequenceName[] = {{PEGRuleId::SchemaQualification, + TransformChildKind::OPTIONAL_REPEAT, + 1, + 1, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::CatalogQualification, + TransformChildKind::OPTIONAL, + 0, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_QualifiedSequenceName = { + FRAME_CHILDREN_QualifiedSequenceName, 2, 2, true, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_RenameAlterSequenceOptions[] = {{PEGRuleId::RenameAlter, + TransformChildKind::REQUIRED, + 0, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_RenameAlterSequenceOptions = { + FRAME_CHILDREN_RenameAlterSequenceOptions, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_SetSequenceOption[] = {{PEGRuleId::SequenceOption, + TransformChildKind::REPEAT, + 0, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_SetSequenceOption = {FRAME_CHILDREN_SetSequenceOption, 1, 1, true, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_AlterDatabaseStmt[] = {{PEGRuleId::IfExists, + TransformChildKind::OPTIONAL, + 1, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_AlterDatabaseStmt = {FRAME_CHILDREN_AlterDatabaseStmt, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_AnalyzeStatement[] = {{PEGRuleId::AnalyzeTarget, + TransformChildKind::OPTIONAL, + 2, + 2, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::AnalyzeVerbose, + TransformChildKind::OPTIONAL, + 1, + 1, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::AnalyzeKeyword, + TransformChildKind::REQUIRED, + 0, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_AnalyzeStatement = {FRAME_CHILDREN_AnalyzeStatement, 3, 3, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_AnalyzeTarget[] = {{PEGRuleId::NameList, + TransformChildKind::OPTIONAL, + 1, + 1, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::BaseTableName, + TransformChildKind::REQUIRED, + 0, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_AnalyzeTarget = {FRAME_CHILDREN_AnalyzeTarget, 2, 2, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_AttachStatement[] = {{PEGRuleId::AttachOptions, + TransformChildKind::OPTIONAL, + 6, + 4, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::AttachAlias, + TransformChildKind::OPTIONAL, + 5, + 3, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::DatabasePath, + TransformChildKind::REQUIRED, + 4, + 2, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::IfNotExists, + TransformChildKind::OPTIONAL, + 2, + 1, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::OrReplace, + TransformChildKind::OPTIONAL, + 1, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_AttachStatement = {FRAME_CHILDREN_AttachStatement, 5, 5, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_DatabasePath[] = {{PEGRuleId::Expression, + TransformChildKind::REQUIRED, + 0, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_DatabasePath = {FRAME_CHILDREN_DatabasePath, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_AttachAlias[] = {{PEGRuleId::ColId, + TransformChildKind::REQUIRED, + 1, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_AttachAlias = {FRAME_CHILDREN_AttachAlias, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_AttachOptions[] = {{PEGRuleId::GenericCopyOptionList, + TransformChildKind::REQUIRED, + 0, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_AttachOptions = {FRAME_CHILDREN_AttachOptions, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_CallStatement[] = {{PEGRuleId::TableFunctionArguments, + TransformChildKind::REQUIRED, + 2, + 1, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::QualifiedTableFunction, + TransformChildKind::REQUIRED, + 1, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_CallStatement = {FRAME_CHILDREN_CallStatement, 2, 2, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_CheckpointStatement[] = {{PEGRuleId::CheckpointForce, + TransformChildKind::OPTIONAL, + 0, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_CheckpointStatement = { + FRAME_CHILDREN_CheckpointStatement, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_CommentStatement[] = {{PEGRuleId::CommentValue, + TransformChildKind::REQUIRED, + 5, + 2, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::CommentTarget, + TransformChildKind::REQUIRED, + 3, + 1, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::CommentOnType, + TransformChildKind::REQUIRED, + 2, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_CommentStatement = {FRAME_CHILDREN_CommentStatement, 3, 3, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_CommentStringLiteralIdentifier[] = {{PEGRuleId::StringLiteralIdentifier, + TransformChildKind::REQUIRED, + 0, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_CommentStringLiteralIdentifier = { + FRAME_CHILDREN_CommentStringLiteralIdentifier, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_ConstraintName[] = {{PEGRuleId::ColIdOrString, + TransformChildKind::REQUIRED, + 0, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_ConstraintName = {FRAME_CHILDREN_ConstraintName, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_NestedType[] = {{PEGRuleId::ArrayBounds, + TransformChildKind::OPTIONAL_REPEAT, + 1, + 1, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::TypeVariations, + TransformChildKind::REQUIRED, + 0, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_NestedType = {FRAME_CHILDREN_NestedType, 2, 2, true, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_CharacterSimpleType[] = {{PEGRuleId::TypeModifiers, + TransformChildKind::OPTIONAL, + 1, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_CharacterSimpleType = { + FRAME_CHILDREN_CharacterSimpleType, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_QualifiedSimpleType[] = {{PEGRuleId::TypeModifiers, + TransformChildKind::OPTIONAL, + 1, + 1, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::QualifiedTypeName, + TransformChildKind::REQUIRED, + 0, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_QualifiedSimpleType = { + FRAME_CHILDREN_QualifiedSimpleType, 2, 2, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_IntervalWithRangeSpecifier[] = {{PEGRuleId::IntervalToIntervalAsType, + TransformChildKind::REQUIRED, + 1, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_IntervalWithRangeSpecifier = { + FRAME_CHILDREN_IntervalWithRangeSpecifier, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_IntervalWithSimpleSpecifier[] = {{PEGRuleId::Interval, + TransformChildKind::REQUIRED, + 1, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_IntervalWithSimpleSpecifier = { + FRAME_CHILDREN_IntervalWithSimpleSpecifier, 1, 1, false, 0, {}}; +static const TransformFramePlan FRAME_PLAN_Choice = {nullptr, 0, 1, false, 0, {0, 0, false, false, 0, nullptr}}; +static const TransformChildPlan FRAME_CHILDREN_YearToMonth[] = {{PEGRuleId::MonthKeyword, + TransformChildKind::REQUIRED, + 2, + 1, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::YearKeyword, + TransformChildKind::REQUIRED, + 0, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_YearToMonth = {FRAME_CHILDREN_YearToMonth, 2, 2, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_DayToHour[] = {{PEGRuleId::HourKeyword, + TransformChildKind::REQUIRED, + 2, + 1, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::DayKeyword, + TransformChildKind::REQUIRED, + 0, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_DayToHour = {FRAME_CHILDREN_DayToHour, 2, 2, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_DayToMinute[] = {{PEGRuleId::MinuteKeyword, + TransformChildKind::REQUIRED, + 2, + 1, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::DayKeyword, + TransformChildKind::REQUIRED, + 0, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_DayToMinute = {FRAME_CHILDREN_DayToMinute, 2, 2, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_DayToSecond[] = {{PEGRuleId::SecondKeyword, + TransformChildKind::REQUIRED, + 2, + 1, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::DayKeyword, + TransformChildKind::REQUIRED, + 0, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_DayToSecond = {FRAME_CHILDREN_DayToSecond, 2, 2, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_HourToMinute[] = {{PEGRuleId::MinuteKeyword, + TransformChildKind::REQUIRED, + 2, + 1, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::HourKeyword, + TransformChildKind::REQUIRED, + 0, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_HourToMinute = {FRAME_CHILDREN_HourToMinute, 2, 2, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_HourToSecond[] = {{PEGRuleId::SecondKeyword, + TransformChildKind::REQUIRED, + 2, + 1, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::HourKeyword, + TransformChildKind::REQUIRED, + 0, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_HourToSecond = {FRAME_CHILDREN_HourToSecond, 2, 2, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_MinuteToSecond[] = {{PEGRuleId::SecondKeyword, + TransformChildKind::REQUIRED, + 2, + 1, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::MinuteKeyword, + TransformChildKind::REQUIRED, + 0, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_MinuteToSecond = {FRAME_CHILDREN_MinuteToSecond, 2, 2, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_BitType[] = {{PEGRuleId::Expression, + TransformChildKind::OPTIONAL_LIST, + 2, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {1, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_BitType = {FRAME_CHILDREN_BitType, 1, 1, true, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_GeometryType[] = {{PEGRuleId::Expression, + TransformChildKind::OPTIONAL, + 1, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {1, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_GeometryType = {FRAME_CHILDREN_GeometryType, 1, 1, false, 0, {}}; +static const TransformFramePlan FRAME_PLAN_ChoiceFallbackIdentifierKeywordStringOperatorChoiceListThrow = { nullptr, 0, 1, @@ -709,544 +717,561 @@ static const TransformFramePlan FRAME_PLAN_54 = { ParseResultTypeBit(ParseResultType::STRING) | ParseResultTypeBit(ParseResultType::OPERATOR) | ParseResultTypeBit(ParseResultType::CHOICE) | ParseResultTypeBit(ParseResultType::LIST), false, true, 0, nullptr}}; -static const TransformChildPlan FRAME_CHILDREN_50[] = {{PEGRuleId::ReservedSchemaQualification, - TransformChildKind::REPEAT, - 1, - 1, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}, - {PEGRuleId::CatalogQualification, - TransformChildKind::REQUIRED, - 0, - 0, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_55 = {FRAME_CHILDREN_50, 2, 2, true, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_51[] = {{PEGRuleId::SchemaQualification, - TransformChildKind::REQUIRED, - 0, - 0, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_56 = {FRAME_CHILDREN_51, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_52[] = {{PEGRuleId::Expression, - TransformChildKind::OPTIONAL_LIST, - 0, - 0, - false, - {1, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_57 = {FRAME_CHILDREN_52, 1, 1, true, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_53[] = {{PEGRuleId::ColIdTypeList, - TransformChildKind::OPTIONAL, - 1, - 0, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_58 = {FRAME_CHILDREN_53, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_54[] = {{PEGRuleId::NestedType, - TransformChildKind::REQUIRED, - 1, - 0, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_59 = {FRAME_CHILDREN_54, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_55[] = {{PEGRuleId::ColIdTypeList, - TransformChildKind::REQUIRED, - 1, - 0, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_60 = {FRAME_CHILDREN_55, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_56[] = {{PEGRuleId::ColIdType, - TransformChildKind::LIST, - 0, - 0, - false, - {1, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_61 = {FRAME_CHILDREN_56, 1, 1, true, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_57[] = {{PEGRuleId::NestedType, - TransformChildKind::OPTIONAL_LIST, - 1, - 0, - false, - {0, TRANSFORM_PATH_END, 0}, - {1, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_62 = {FRAME_CHILDREN_57, 1, 1, true, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_58[] = {{PEGRuleId::NestedType, - TransformChildKind::LIST, - 1, - 0, - false, - {1, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_63 = {FRAME_CHILDREN_58, 1, 1, true, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_59[] = {{PEGRuleId::NestedType, - TransformChildKind::REQUIRED, - 1, - 1, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}, - {PEGRuleId::ColId, - TransformChildKind::REQUIRED, - 0, - 0, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_64 = {FRAME_CHILDREN_59, 2, 2, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_60[] = {{PEGRuleId::SquareBracketsArray, - TransformChildKind::REQUIRED, - 1, - 0, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_65 = {FRAME_CHILDREN_60, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_61[] = {{PEGRuleId::Expression, - TransformChildKind::OPTIONAL, - 1, - 0, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_66 = {FRAME_CHILDREN_61, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_62[] = {{PEGRuleId::TimeZone, - TransformChildKind::OPTIONAL, - 2, - 2, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}, - {PEGRuleId::TypeModifiers, - TransformChildKind::OPTIONAL, - 1, - 1, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}, - {PEGRuleId::TimeOrTimestamp, - TransformChildKind::REQUIRED, - 0, - 0, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_67 = {FRAME_CHILDREN_62, 3, 3, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_63[] = {{PEGRuleId::WithOrWithout, - TransformChildKind::REQUIRED, - 0, - 0, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_68 = {FRAME_CHILDREN_63, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_64[] = {{PEGRuleId::SessionTarget, - TransformChildKind::OPTIONAL, - 1, - 0, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_69 = {FRAME_CHILDREN_64, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_65[] = {{PEGRuleId::GenericCopyOptionList, - TransformChildKind::OPTIONAL, - 1, - 0, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_70 = {FRAME_CHILDREN_65, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_66[] = {{PEGRuleId::CopyVariations, - TransformChildKind::REQUIRED, - 1, - 0, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_71 = {FRAME_CHILDREN_66, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_67[] = {{PEGRuleId::CopyOptions, - TransformChildKind::OPTIONAL, - 5, - 5, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}, - {PEGRuleId::CopyLegacyOption, - TransformChildKind::OPTIONAL, - 4, - 4, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}, - {PEGRuleId::CopyFileName, - TransformChildKind::REQUIRED, - 3, - 3, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}, - {PEGRuleId::FromOrTo, - TransformChildKind::REQUIRED, - 2, - 2, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}, - {PEGRuleId::InsertColumnList, - TransformChildKind::OPTIONAL, - 1, - 1, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}, - {PEGRuleId::BaseTableName, - TransformChildKind::REQUIRED, - 0, - 0, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_72 = {FRAME_CHILDREN_67, 6, 6, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_68[] = {{PEGRuleId::CopyOptions, - TransformChildKind::OPTIONAL, - 3, - 2, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}, - {PEGRuleId::CopyFileName, - TransformChildKind::REQUIRED, - 2, - 1, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}, - {PEGRuleId::SelectStatementInternal, - TransformChildKind::REQUIRED, - 0, - 0, - false, - {1, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_73 = {FRAME_CHILDREN_68, 3, 3, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_69[] = {{PEGRuleId::IdentifierColId, - TransformChildKind::REQUIRED, - 0, - 0, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_74 = {FRAME_CHILDREN_69, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_70[] = {{PEGRuleId::CopyFileNameSuffix, - TransformChildKind::REPEAT, - 1, - 0, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_75 = {FRAME_CHILDREN_70, 1, 1, true, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_71[] = {{PEGRuleId::CopyOptionList, - TransformChildKind::REQUIRED, - 1, - 0, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_76 = {FRAME_CHILDREN_71, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_72[] = {{PEGRuleId::SpecializedOptionTail, - TransformChildKind::OPTIONAL_REPEAT, - 1, - 1, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}, - {PEGRuleId::SpecializedOption, - TransformChildKind::REQUIRED, - 0, - 0, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_77 = {FRAME_CHILDREN_72, 2, 2, true, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_73[] = {{PEGRuleId::SpecializedOption, - TransformChildKind::REQUIRED, - 1, - 0, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_78 = {FRAME_CHILDREN_73, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_74[] = {{PEGRuleId::StarSymbolColumnList, - TransformChildKind::REQUIRED, - 2, - 1, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}, - {PEGRuleId::ForceQuote, - TransformChildKind::OPTIONAL, - 0, - 0, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_79 = {FRAME_CHILDREN_74, 2, 2, false, 0, {}}; -static const char *const FRAME_NAMES_0[] = {"StarSymbol"}; -static const TransformFramePlan FRAME_PLAN_80 = {nullptr, 0, 1, false, 0, {0, 0, false, true, 1, FRAME_NAMES_0}}; -static const TransformChildPlan FRAME_CHILDREN_75[] = {{PEGRuleId::PartitionByColumnList, - TransformChildKind::REQUIRED, - 2, - 0, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_81 = {FRAME_CHILDREN_75, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_76[] = {{PEGRuleId::ColumnList, - TransformChildKind::REQUIRED, - 0, - 0, - false, - {1, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_82 = {FRAME_CHILDREN_76, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_77[] = {{PEGRuleId::ColId, - TransformChildKind::REQUIRED, - 0, - 0, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_83 = {FRAME_CHILDREN_77, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_78[] = {{PEGRuleId::ColumnList, - TransformChildKind::REQUIRED, - 3, - 1, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}, - {PEGRuleId::ForceNotNull, - TransformChildKind::OPTIONAL, - 1, - 0, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_84 = {FRAME_CHILDREN_78, 2, 2, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_79[] = {{PEGRuleId::CopyGenericOption, - TransformChildKind::LIST, - 0, - 0, - false, - {1, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_85 = {FRAME_CHILDREN_79, 1, 1, true, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_80[] = {{PEGRuleId::GenericCopyOptionValue, - TransformChildKind::OPTIONAL, - 2, - 0, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_86 = {FRAME_CHILDREN_80, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_81[] = {{PEGRuleId::GenericCopyOption, - TransformChildKind::LIST, - 0, - 0, - false, - {1, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_87 = {FRAME_CHILDREN_81, 1, 1, true, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_82[] = {{PEGRuleId::GenericCopyOptionValue, - TransformChildKind::OPTIONAL, - 1, - 0, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_88 = {FRAME_CHILDREN_82, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_83[] = {{PEGRuleId::GenericCopyOptionParenthesizedExpressionList, - TransformChildKind::REQUIRED, - 0, - 0, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_89 = {FRAME_CHILDREN_83, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_84[] = {{PEGRuleId::OrderByExpressionList, - TransformChildKind::REQUIRED, - 0, - 0, - false, - {1, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_90 = {FRAME_CHILDREN_84, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_85[] = {{PEGRuleId::CopyDatabaseFlag, - TransformChildKind::REQUIRED, - 5, - 2, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}, - {PEGRuleId::ColId, - TransformChildKind::REQUIRED, - 4, - 1, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}, - {PEGRuleId::ColId, - TransformChildKind::REQUIRED, - 2, - 0, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_91 = {FRAME_CHILDREN_85, 3, 3, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_86[] = {{PEGRuleId::ColId, - TransformChildKind::REQUIRED, - 4, - 1, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}, - {PEGRuleId::ColId, - TransformChildKind::REQUIRED, - 2, - 0, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_92 = {FRAME_CHILDREN_86, 2, 2, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_87[] = {{PEGRuleId::SchemaOrData, - TransformChildKind::REQUIRED, - 0, - 0, - false, - {1, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_93 = {FRAME_CHILDREN_87, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_88[] = {{PEGRuleId::WhereClause, - TransformChildKind::OPTIONAL, - 10, - 6, - true, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}, - {PEGRuleId::WithList, - TransformChildKind::OPTIONAL, - 9, - 5, - true, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}, - {PEGRuleId::IndexElement, - TransformChildKind::LIST, - 8, - 4, - false, - {1, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}, - {PEGRuleId::IndexType, - TransformChildKind::OPTIONAL, - 7, - 3, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}, - {PEGRuleId::BaseTableName, - TransformChildKind::REQUIRED, - 6, - 2, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}, - {PEGRuleId::IfNotExists, - TransformChildKind::OPTIONAL, - 3, - 1, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}, - {PEGRuleId::UniqueIndex, - TransformChildKind::OPTIONAL, - 0, - 0, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_94 = {FRAME_CHILDREN_88, 7, 7, true, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_89[] = {{PEGRuleId::RelOptionOrOids, - TransformChildKind::REQUIRED, - 1, - 0, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_95 = {FRAME_CHILDREN_89, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_90[] = {{PEGRuleId::RelOption, - TransformChildKind::LIST, - 0, - 0, - false, - {1, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_96 = {FRAME_CHILDREN_90, 1, 1, true, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_91[] = {{PEGRuleId::WithOrWithoutOids, - TransformChildKind::REQUIRED, - 0, - 0, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_97 = {FRAME_CHILDREN_91, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_92[] = {{PEGRuleId::NullsFirstOrLast, - TransformChildKind::OPTIONAL, - 2, - 2, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}, - {PEGRuleId::DescOrAsc, - TransformChildKind::OPTIONAL, - 1, - 1, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}, - {PEGRuleId::Expression, - TransformChildKind::REQUIRED, - 0, - 0, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_98 = {FRAME_CHILDREN_92, 3, 3, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_93[] = {{PEGRuleId::RelOptionArgumentOpt, - TransformChildKind::OPTIONAL, - 1, - 1, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}, - {PEGRuleId::RelOptionName, - TransformChildKind::REQUIRED, - 0, - 0, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_99 = {FRAME_CHILDREN_93, 2, 2, false, 0, {}}; -static const char *const FRAME_NAMES_1[] = {"DottedColLabel", "StringLiteral"}; -static const TransformFramePlan FRAME_PLAN_100 = { +static const TransformChildPlan FRAME_CHILDREN_CatalogReservedSchemaIndex[] = {{PEGRuleId::ReservedSchemaQualification, + TransformChildKind::REPEAT, + 1, + 1, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::CatalogQualification, + TransformChildKind::REQUIRED, + 0, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_CatalogReservedSchemaIndex = { + FRAME_CHILDREN_CatalogReservedSchemaIndex, 2, 2, true, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_SchemaReservedFunctionName[] = {{PEGRuleId::SchemaQualification, + TransformChildKind::REQUIRED, + 0, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_SchemaReservedFunctionName = { + FRAME_CHILDREN_SchemaReservedFunctionName, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_ParenthesisExpression[] = {{PEGRuleId::Expression, + TransformChildKind::OPTIONAL_LIST, + 0, + 0, + false, + {1, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_ParenthesisExpression = { + FRAME_CHILDREN_ParenthesisExpression, 1, 1, true, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_RowType[] = {{PEGRuleId::ColIdTypeList, + TransformChildKind::OPTIONAL, + 1, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_RowType = {FRAME_CHILDREN_RowType, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_SetofType[] = {{PEGRuleId::NestedType, + TransformChildKind::REQUIRED, + 1, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_SetofType = {FRAME_CHILDREN_SetofType, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_UnionType[] = {{PEGRuleId::ColIdTypeList, + TransformChildKind::REQUIRED, + 1, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_UnionType = {FRAME_CHILDREN_UnionType, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_ColIdTypeList[] = {{PEGRuleId::ColIdType, + TransformChildKind::LIST, + 0, + 0, + false, + {1, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_ColIdTypeList = {FRAME_CHILDREN_ColIdTypeList, 1, 1, true, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_MapType[] = {{PEGRuleId::NestedType, + TransformChildKind::OPTIONAL_LIST, + 1, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {1, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_MapType = {FRAME_CHILDREN_MapType, 1, 1, true, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_TupleType[] = {{PEGRuleId::NestedType, + TransformChildKind::LIST, + 1, + 0, + false, + {1, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_TupleType = {FRAME_CHILDREN_TupleType, 1, 1, true, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_ColIdType[] = {{PEGRuleId::NestedType, + TransformChildKind::REQUIRED, + 1, + 1, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::ColId, + TransformChildKind::REQUIRED, + 0, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_ColIdType = {FRAME_CHILDREN_ColIdType, 2, 2, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_ArrayKeywordWithBounds[] = {{PEGRuleId::SquareBracketsArray, + TransformChildKind::REQUIRED, + 1, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_ArrayKeywordWithBounds = { + FRAME_CHILDREN_ArrayKeywordWithBounds, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_EndSliceBound[] = {{PEGRuleId::Expression, + TransformChildKind::OPTIONAL, + 1, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_EndSliceBound = {FRAME_CHILDREN_EndSliceBound, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_TimeType[] = {{PEGRuleId::TimeZone, + TransformChildKind::OPTIONAL, + 2, + 2, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::TypeModifiers, + TransformChildKind::OPTIONAL, + 1, + 1, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::TimeOrTimestamp, + TransformChildKind::REQUIRED, + 0, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_TimeType = {FRAME_CHILDREN_TimeType, 3, 3, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_TimeZone[] = {{PEGRuleId::WithOrWithout, + TransformChildKind::REQUIRED, + 0, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_TimeZone = {FRAME_CHILDREN_TimeZone, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_ConnectStatement[] = {{PEGRuleId::SessionTarget, + TransformChildKind::OPTIONAL, + 1, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_ConnectStatement = {FRAME_CHILDREN_ConnectStatement, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_StringSessionTarget[] = {{PEGRuleId::GenericCopyOptionList, + TransformChildKind::OPTIONAL, + 1, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_StringSessionTarget = { + FRAME_CHILDREN_StringSessionTarget, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_CopyStatement[] = {{PEGRuleId::CopyVariations, + TransformChildKind::REQUIRED, + 1, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_CopyStatement = {FRAME_CHILDREN_CopyStatement, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_CopyTable[] = {{PEGRuleId::CopyOptions, + TransformChildKind::OPTIONAL, + 5, + 5, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::CopyLegacyOption, + TransformChildKind::OPTIONAL, + 4, + 4, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::CopyFileName, + TransformChildKind::REQUIRED, + 3, + 3, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::FromOrTo, + TransformChildKind::REQUIRED, + 2, + 2, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::InsertColumnList, + TransformChildKind::OPTIONAL, + 1, + 1, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::BaseTableName, + TransformChildKind::REQUIRED, + 0, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_CopyTable = {FRAME_CHILDREN_CopyTable, 6, 6, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_CopySelect[] = {{PEGRuleId::CopyOptions, + TransformChildKind::OPTIONAL, + 3, + 2, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::CopyFileName, + TransformChildKind::REQUIRED, + 2, + 1, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::SelectStatementInternal, + TransformChildKind::REQUIRED, + 0, + 0, + false, + {1, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_CopySelect = {FRAME_CHILDREN_CopySelect, 3, 3, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_CopyFileNameIdentifierColId[] = {{PEGRuleId::IdentifierColId, + TransformChildKind::REQUIRED, + 0, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_CopyFileNameIdentifierColId = { + FRAME_CHILDREN_CopyFileNameIdentifierColId, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_IdentifierColId[] = {{PEGRuleId::CopyFileNameSuffix, + TransformChildKind::REPEAT, + 1, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_IdentifierColId = {FRAME_CHILDREN_IdentifierColId, 1, 1, true, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_CopyOptions[] = {{PEGRuleId::CopyOptionList, + TransformChildKind::REQUIRED, + 1, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_CopyOptions = {FRAME_CHILDREN_CopyOptions, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_SpecializedOptionList[] = {{PEGRuleId::SpecializedOptionTail, + TransformChildKind::OPTIONAL_REPEAT, + 1, + 1, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::SpecializedOption, + TransformChildKind::REQUIRED, + 0, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_SpecializedOptionList = { + FRAME_CHILDREN_SpecializedOptionList, 2, 2, true, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_SpecializedOptionTail[] = {{PEGRuleId::SpecializedOption, + TransformChildKind::REQUIRED, + 1, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_SpecializedOptionTail = { + FRAME_CHILDREN_SpecializedOptionTail, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_ForceQuoteOption[] = {{PEGRuleId::StarSymbolColumnList, + TransformChildKind::REQUIRED, + 2, + 1, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::ForceQuote, + TransformChildKind::OPTIONAL, + 0, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_ForceQuoteOption = {FRAME_CHILDREN_ForceQuoteOption, 2, 2, false, 0, {}}; +static const char *const FRAME_NAMES_StarSymbolColumnList[] = {"StarSymbol"}; +static const TransformFramePlan FRAME_PLAN_StarSymbolColumnList = { + nullptr, 0, 1, false, 0, {0, 0, false, true, 1, FRAME_NAMES_StarSymbolColumnList}}; +static const TransformChildPlan FRAME_CHILDREN_PartitionByOption[] = {{PEGRuleId::PartitionByColumnList, + TransformChildKind::REQUIRED, + 2, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_PartitionByOption = {FRAME_CHILDREN_PartitionByOption, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_InsertColumnList[] = {{PEGRuleId::ColumnList, + TransformChildKind::REQUIRED, + 0, + 0, + false, + {1, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_InsertColumnList = {FRAME_CHILDREN_InsertColumnList, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_ColIdDot[] = {{PEGRuleId::ColId, + TransformChildKind::REQUIRED, + 0, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_ColIdDot = {FRAME_CHILDREN_ColIdDot, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_ForceNullOption[] = {{PEGRuleId::ColumnList, + TransformChildKind::REQUIRED, + 3, + 1, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::ForceNotNull, + TransformChildKind::OPTIONAL, + 1, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_ForceNullOption = {FRAME_CHILDREN_ForceNullOption, 2, 2, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_CopyGenericOptionList[] = {{PEGRuleId::CopyGenericOption, + TransformChildKind::LIST, + 0, + 0, + false, + {1, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_CopyGenericOptionList = { + FRAME_CHILDREN_CopyGenericOptionList, 1, 1, true, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_OrderByCopyOption[] = {{PEGRuleId::GenericCopyOptionValue, + TransformChildKind::OPTIONAL, + 2, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_OrderByCopyOption = {FRAME_CHILDREN_OrderByCopyOption, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_GenericCopyOptionList[] = {{PEGRuleId::GenericCopyOption, + TransformChildKind::LIST, + 0, + 0, + false, + {1, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_GenericCopyOptionList = { + FRAME_CHILDREN_GenericCopyOptionList, 1, 1, true, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_GenericCopyOption[] = {{PEGRuleId::GenericCopyOptionValue, + TransformChildKind::OPTIONAL, + 1, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_GenericCopyOption = {FRAME_CHILDREN_GenericCopyOption, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_GenericCopyOptionOrderList[] = { + {PEGRuleId::GenericCopyOptionParenthesizedExpressionList, + TransformChildKind::REQUIRED, + 0, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_GenericCopyOptionOrderList = { + FRAME_CHILDREN_GenericCopyOptionOrderList, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_GenericCopyOptionParenthesizedExpressionList[] = { + {PEGRuleId::OrderByExpressionList, + TransformChildKind::REQUIRED, + 0, + 0, + false, + {1, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_GenericCopyOptionParenthesizedExpressionList = { + FRAME_CHILDREN_GenericCopyOptionParenthesizedExpressionList, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_CopyFromDatabaseWithFlag[] = {{PEGRuleId::CopyDatabaseFlag, + TransformChildKind::REQUIRED, + 5, + 2, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::ColId, + TransformChildKind::REQUIRED, + 4, + 1, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::ColId, + TransformChildKind::REQUIRED, + 2, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_CopyFromDatabaseWithFlag = { + FRAME_CHILDREN_CopyFromDatabaseWithFlag, 3, 3, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_CopyFromDatabaseWithoutFlag[] = {{PEGRuleId::ColId, + TransformChildKind::REQUIRED, + 4, + 1, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::ColId, + TransformChildKind::REQUIRED, + 2, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_CopyFromDatabaseWithoutFlag = { + FRAME_CHILDREN_CopyFromDatabaseWithoutFlag, 2, 2, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_CopyDatabaseFlag[] = {{PEGRuleId::SchemaOrData, + TransformChildKind::REQUIRED, + 0, + 0, + false, + {1, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_CopyDatabaseFlag = {FRAME_CHILDREN_CopyDatabaseFlag, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_CreateIndexStmt[] = {{PEGRuleId::WhereClause, + TransformChildKind::OPTIONAL, + 10, + 6, + true, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::WithList, + TransformChildKind::OPTIONAL, + 9, + 5, + true, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::IndexElement, + TransformChildKind::LIST, + 8, + 4, + false, + {1, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::IndexType, + TransformChildKind::OPTIONAL, + 7, + 3, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::BaseTableName, + TransformChildKind::REQUIRED, + 6, + 2, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::IfNotExists, + TransformChildKind::OPTIONAL, + 3, + 1, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::UniqueIndex, + TransformChildKind::OPTIONAL, + 0, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_CreateIndexStmt = {FRAME_CHILDREN_CreateIndexStmt, 7, 7, true, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_WithList[] = {{PEGRuleId::RelOptionOrOids, + TransformChildKind::REQUIRED, + 1, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_WithList = {FRAME_CHILDREN_WithList, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_RelOptionList[] = {{PEGRuleId::RelOption, + TransformChildKind::LIST, + 0, + 0, + false, + {1, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_RelOptionList = {FRAME_CHILDREN_RelOptionList, 1, 1, true, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_Oids[] = {{PEGRuleId::WithOrWithoutOids, + TransformChildKind::REQUIRED, + 0, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_Oids = {FRAME_CHILDREN_Oids, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_IndexElement[] = {{PEGRuleId::NullsFirstOrLast, + TransformChildKind::OPTIONAL, + 2, + 2, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::DescOrAsc, + TransformChildKind::OPTIONAL, + 1, + 1, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::Expression, + TransformChildKind::REQUIRED, + 0, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_IndexElement = {FRAME_CHILDREN_IndexElement, 3, 3, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_RelOption[] = {{PEGRuleId::RelOptionArgumentOpt, + TransformChildKind::OPTIONAL, + 1, + 1, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::RelOptionName, + TransformChildKind::REQUIRED, + 0, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_RelOption = {FRAME_CHILDREN_RelOption, 2, 2, false, 0, {}}; +static const char *const FRAME_NAMES_RelOptionName[] = {"DottedColLabel", "StringLiteral"}; +static const TransformFramePlan FRAME_PLAN_RelOptionName = { nullptr, 0, 1, @@ -1257,691 +1282,710 @@ static const TransformFramePlan FRAME_PLAN_100 = { ParseResultTypeBit(ParseResultType::IDENTIFIER) | ParseResultTypeBit(ParseResultType::KEYWORD) | ParseResultTypeBit(ParseResultType::STRING) | ParseResultTypeBit(ParseResultType::OPERATOR) | ParseResultTypeBit(ParseResultType::CHOICE) | ParseResultTypeBit(ParseResultType::LIST), - true, true, 2, FRAME_NAMES_1}}; -static const TransformChildPlan FRAME_CHILDREN_94[] = {{PEGRuleId::DotColLabel, - TransformChildKind::OPTIONAL_REPEAT, - 1, - 1, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}, - {PEGRuleId::ColLabel, - TransformChildKind::REQUIRED, - 0, - 0, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_101 = {FRAME_CHILDREN_94, 2, 2, true, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_95[] = {{PEGRuleId::DefArg, - TransformChildKind::REQUIRED, - 1, - 0, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_102 = {FRAME_CHILDREN_95, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_96[] = {{PEGRuleId::NullLiteral, - TransformChildKind::REQUIRED, - 0, - 0, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_103 = {FRAME_CHILDREN_96, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_97[] = {{PEGRuleId::MacroDefinition, - TransformChildKind::LIST, - 3, - 3, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}, - {PEGRuleId::QualifiedName, - TransformChildKind::REQUIRED, - 2, - 2, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}, - {PEGRuleId::IfNotExists, - TransformChildKind::OPTIONAL, - 1, - 1, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}, - {PEGRuleId::MacroOrFunction, - TransformChildKind::REQUIRED, - 0, - 0, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_104 = {FRAME_CHILDREN_97, 4, 4, true, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_98[] = {{PEGRuleId::Type, - TransformChildKind::REQUIRED, - 1, - 0, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_105 = {FRAME_CHILDREN_98, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_99[] = {{PEGRuleId::MacroDefinitionBody, - TransformChildKind::REQUIRED, - 3, - 2, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}, - {PEGRuleId::ReturnsType, - TransformChildKind::OPTIONAL, - 1, - 1, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}, - {PEGRuleId::MacroParameters, - TransformChildKind::OPTIONAL, - 0, - 0, - false, - {1, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_106 = {FRAME_CHILDREN_99, 3, 3, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_100[] = {{PEGRuleId::MacroParameter, - TransformChildKind::LIST, - 0, - 0, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_107 = {FRAME_CHILDREN_100, 1, 1, true, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_101[] = {{PEGRuleId::Type, - TransformChildKind::OPTIONAL, - 1, - 1, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}, - {PEGRuleId::TypeFuncName, - TransformChildKind::REQUIRED, - 0, - 0, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_108 = {FRAME_CHILDREN_101, 2, 2, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_102[] = {{PEGRuleId::SelectStatementInternal, - TransformChildKind::REQUIRED, - 1, - 0, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_109 = {FRAME_CHILDREN_102, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_103[] = {{PEGRuleId::WithOptionList, - TransformChildKind::OPTIONAL, - 3, - 2, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}, - {PEGRuleId::QualifiedName, - TransformChildKind::REQUIRED, - 2, - 1, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}, - {PEGRuleId::IfNotExists, - TransformChildKind::OPTIONAL, - 1, - 0, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_110 = {FRAME_CHILDREN_103, 3, 3, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_104[] = {{PEGRuleId::GenericCopyOptionList, - TransformChildKind::REQUIRED, - 4, - 3, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}, - {PEGRuleId::SecretStorageSpecifier, - TransformChildKind::OPTIONAL, - 3, - 2, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}, - {PEGRuleId::SecretName, - TransformChildKind::OPTIONAL, - 2, - 1, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}, - {PEGRuleId::IfNotExists, - TransformChildKind::OPTIONAL, - 1, - 0, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_111 = {FRAME_CHILDREN_104, 4, 4, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_105[] = {{PEGRuleId::SequenceOption, - TransformChildKind::OPTIONAL_REPEAT, - 3, - 2, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}, - {PEGRuleId::QualifiedName, - TransformChildKind::REQUIRED, - 2, - 1, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}, - {PEGRuleId::IfNotExists, - TransformChildKind::OPTIONAL, - 1, - 0, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_112 = {FRAME_CHILDREN_105, 3, 3, true, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_106[] = {{PEGRuleId::Expression, - TransformChildKind::REQUIRED, - 1, - 1, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}, - {PEGRuleId::SeqMinOrMax, - TransformChildKind::REQUIRED, - 0, - 0, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_113 = {FRAME_CHILDREN_106, 2, 2, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_107[] = {{PEGRuleId::SeqMinOrMax, - TransformChildKind::REQUIRED, - 1, - 0, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_114 = {FRAME_CHILDREN_107, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_108[] = {{PEGRuleId::QualifiedName, - TransformChildKind::REQUIRED, - 2, - 0, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_115 = {FRAME_CHILDREN_108, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_109[] = {{PEGRuleId::CreateStatementVariation, - TransformChildKind::REQUIRED, - 3, - 2, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}, - {PEGRuleId::Temporary, - TransformChildKind::OPTIONAL, - 2, - 1, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}, - {PEGRuleId::OrReplace, - TransformChildKind::OPTIONAL, - 1, - 0, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_116 = {FRAME_CHILDREN_109, 3, 3, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_110[] = {{PEGRuleId::CommitAction, - TransformChildKind::OPTIONAL, - 4, - 3, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}, - {PEGRuleId::CreateTableDefinition, - TransformChildKind::REQUIRED, - 3, - 2, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}, - {PEGRuleId::QualifiedName, - TransformChildKind::REQUIRED, - 2, - 1, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}, - {PEGRuleId::IfNotExists, - TransformChildKind::OPTIONAL, - 1, - 0, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_117 = {FRAME_CHILDREN_110, 4, 4, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_111[] = {{PEGRuleId::WithData, - TransformChildKind::OPTIONAL, - 5, - 4, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}, - {PEGRuleId::Statement, - TransformChildKind::REQUIRED, - 4, - 3, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}, - {PEGRuleId::WithList, - TransformChildKind::OPTIONAL, - 2, - 2, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}, - {PEGRuleId::PartitionSortedOptions, - TransformChildKind::OPTIONAL, - 1, - 1, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}, - {PEGRuleId::IdentifierList, - TransformChildKind::OPTIONAL, - 0, - 0, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_118 = {FRAME_CHILDREN_111, 5, 5, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_112[] = {{PEGRuleId::SortedOptions, - TransformChildKind::OPTIONAL, - 1, - 1, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}, - {PEGRuleId::PartitionOptions, - TransformChildKind::REQUIRED, - 0, - 0, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_119 = {FRAME_CHILDREN_112, 2, 2, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_113[] = {{PEGRuleId::PartitionOptions, - TransformChildKind::OPTIONAL, - 1, - 1, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}, - {PEGRuleId::SortedOptions, - TransformChildKind::REQUIRED, - 0, - 0, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_120 = {FRAME_CHILDREN_113, 2, 2, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_114[] = {{PEGRuleId::Expression, - TransformChildKind::LIST, - 2, - 0, - false, - {1, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_121 = {FRAME_CHILDREN_114, 1, 1, true, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_115[] = {{PEGRuleId::WithList, - TransformChildKind::OPTIONAL, - 2, - 2, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}, - {PEGRuleId::PartitionSortedOptions, - TransformChildKind::OPTIONAL, - 1, - 1, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}, - {PEGRuleId::CreateTableColumnList, - TransformChildKind::OPTIONAL, - 0, - 0, - false, - {1, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_122 = {FRAME_CHILDREN_115, 3, 3, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_116[] = {{PEGRuleId::ReservedIdentifierOrStringLiteral, - TransformChildKind::REQUIRED, - 1, - 1, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}, - {PEGRuleId::SchemaQualification, - TransformChildKind::REQUIRED, - 0, - 0, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_123 = {FRAME_CHILDREN_116, 2, 2, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_117[] = {{PEGRuleId::ReservedIdentifierOrStringLiteral, - TransformChildKind::REQUIRED, - 2, - 2, - true, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}, - {PEGRuleId::ReservedSchemaQualification, - TransformChildKind::REPEAT, - 1, - 1, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}, - {PEGRuleId::CatalogQualification, - TransformChildKind::REQUIRED, - 0, - 0, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_124 = {FRAME_CHILDREN_117, 3, 3, true, 0, {}}; -static const char *const FRAME_NAMES_2[] = {"StringLiteral"}; -static const TransformFramePlan FRAME_PLAN_125 = {nullptr, - 0, - 1, - false, - 0, - {ParseResultTypeBit(ParseResultType::IDENTIFIER) | - ParseResultTypeBit(ParseResultType::KEYWORD) | - ParseResultTypeBit(ParseResultType::STRING), - 0, true, true, 1, FRAME_NAMES_2}}; -static const TransformChildPlan FRAME_CHILDREN_118[] = {{PEGRuleId::CreateTableColumnElement, - TransformChildKind::LIST, - 0, - 0, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_126 = {FRAME_CHILDREN_118, 1, 1, true, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_119[] = {{PEGRuleId::ColumnDefinition, - TransformChildKind::REQUIRED, - 0, - 0, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_127 = {FRAME_CHILDREN_119, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_120[] = {{PEGRuleId::TopLevelConstraint, - TransformChildKind::REQUIRED, - 0, - 0, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_128 = {FRAME_CHILDREN_120, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_121[] = {{PEGRuleId::ColumnConstraint, - TransformChildKind::OPTIONAL_REPEAT, - 3, - 2, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}, - {PEGRuleId::GeneratedColumn, - TransformChildKind::OPTIONAL, - 2, - 1, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}, - {PEGRuleId::Type, - TransformChildKind::OPTIONAL, - 1, - 0, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_129 = {FRAME_CHILDREN_121, 3, 3, true, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_122[] = {{PEGRuleId::ColumnConstraintElement, - TransformChildKind::REQUIRED, - 1, - 0, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_130 = {FRAME_CHILDREN_122, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_123[] = {{PEGRuleId::ConstraintTiming, - TransformChildKind::OPTIONAL, - 1, - 0, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_131 = {FRAME_CHILDREN_123, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_124[] = {{PEGRuleId::ConstraintTiming, - TransformChildKind::OPTIONAL, - 2, - 0, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_132 = {FRAME_CHILDREN_124, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_125[] = {{PEGRuleId::ColumnDefaultExpr, - TransformChildKind::REQUIRED, - 1, - 0, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_133 = {FRAME_CHILDREN_125, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_126[] = {{PEGRuleId::Expression, - TransformChildKind::REQUIRED, - 1, - 0, - false, - {1, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_134 = {FRAME_CHILDREN_126, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_127[] = {{PEGRuleId::KeyActions, - TransformChildKind::OPTIONAL, - 3, - 2, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}, - {PEGRuleId::ColumnList, - TransformChildKind::OPTIONAL, - 2, - 1, - false, - {0, TRANSFORM_PATH_END, 0}, - {1, TRANSFORM_PATH_END, 0}}, - {PEGRuleId::BaseTableName, - TransformChildKind::REQUIRED, - 1, - 0, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_135 = {FRAME_CHILDREN_127, 3, 3, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_128[] = {{PEGRuleId::DottedIdentifier, - TransformChildKind::REQUIRED, - 1, - 0, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_136 = {FRAME_CHILDREN_128, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_129[] = {{PEGRuleId::DeleteAction, - TransformChildKind::OPTIONAL, - 1, - 1, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}, - {PEGRuleId::UpdateAction, - TransformChildKind::REQUIRED, - 0, - 0, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_137 = {FRAME_CHILDREN_129, 2, 2, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_130[] = {{PEGRuleId::UpdateAction, - TransformChildKind::OPTIONAL, - 1, - 1, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}, - {PEGRuleId::DeleteAction, - TransformChildKind::REQUIRED, - 0, - 0, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_138 = {FRAME_CHILDREN_130, 2, 2, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_131[] = {{PEGRuleId::KeyAction, - TransformChildKind::REQUIRED, - 2, - 0, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_139 = {FRAME_CHILDREN_131, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_132[] = {{PEGRuleId::TopLevelConstraintList, - TransformChildKind::REQUIRED, - 1, - 0, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_140 = {FRAME_CHILDREN_132, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_133[] = {{PEGRuleId::CheckConstraint, - TransformChildKind::REQUIRED, - 0, - 0, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_141 = {FRAME_CHILDREN_133, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_134[] = {{PEGRuleId::ConstraintTiming, - TransformChildKind::OPTIONAL, - 3, - 1, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}, - {PEGRuleId::ColumnIdList, - TransformChildKind::REQUIRED, - 2, - 0, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_142 = {FRAME_CHILDREN_134, 2, 2, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_135[] = {{PEGRuleId::ConstraintTiming, - TransformChildKind::OPTIONAL, - 2, - 1, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}, - {PEGRuleId::ColumnIdList, - TransformChildKind::REQUIRED, - 1, - 0, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_143 = {FRAME_CHILDREN_135, 2, 2, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_136[] = {{PEGRuleId::ForeignKeyConstraint, - TransformChildKind::REQUIRED, - 3, - 1, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}, - {PEGRuleId::ColumnIdList, - TransformChildKind::REQUIRED, - 2, - 0, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_144 = {FRAME_CHILDREN_136, 2, 2, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_137[] = { + true, true, 2, FRAME_NAMES_RelOptionName}}; +static const TransformChildPlan FRAME_CHILDREN_DottedColLabel[] = {{PEGRuleId::DotColLabel, + TransformChildKind::OPTIONAL_REPEAT, + 1, + 1, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::ColLabel, + TransformChildKind::REQUIRED, + 0, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_DottedColLabel = {FRAME_CHILDREN_DottedColLabel, 2, 2, true, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_RelOptionArgumentOpt[] = {{PEGRuleId::DefArg, + TransformChildKind::REQUIRED, + 1, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_RelOptionArgumentOpt = { + FRAME_CHILDREN_RelOptionArgumentOpt, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_DefArgNull[] = {{PEGRuleId::NullLiteral, + TransformChildKind::REQUIRED, + 0, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_DefArgNull = {FRAME_CHILDREN_DefArgNull, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_CreateMacroStmt[] = {{PEGRuleId::MacroDefinition, + TransformChildKind::LIST, + 3, + 3, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::QualifiedName, + TransformChildKind::REQUIRED, + 2, + 2, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::IfNotExists, + TransformChildKind::OPTIONAL, + 1, + 1, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::MacroOrFunction, + TransformChildKind::REQUIRED, + 0, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_CreateMacroStmt = {FRAME_CHILDREN_CreateMacroStmt, 4, 4, true, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_CastOperator[] = {{PEGRuleId::Type, + TransformChildKind::REQUIRED, + 1, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_CastOperator = {FRAME_CHILDREN_CastOperator, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_MacroDefinition[] = {{PEGRuleId::MacroDefinitionBody, + TransformChildKind::REQUIRED, + 3, + 2, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::ReturnsType, + TransformChildKind::OPTIONAL, + 1, + 1, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::MacroParameters, + TransformChildKind::OPTIONAL, + 0, + 0, + false, + {1, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_MacroDefinition = {FRAME_CHILDREN_MacroDefinition, 3, 3, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_MacroParameters[] = {{PEGRuleId::MacroParameter, + TransformChildKind::LIST, + 0, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_MacroParameters = {FRAME_CHILDREN_MacroParameters, 1, 1, true, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_SimpleParameter[] = {{PEGRuleId::Type, + TransformChildKind::OPTIONAL, + 1, + 1, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::TypeFuncName, + TransformChildKind::REQUIRED, + 0, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_SimpleParameter = {FRAME_CHILDREN_SimpleParameter, 2, 2, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_TableMacroDefinition[] = {{PEGRuleId::SelectStatementInternal, + TransformChildKind::REQUIRED, + 1, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_TableMacroDefinition = { + FRAME_CHILDREN_TableMacroDefinition, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_CreateSchemaStmt[] = {{PEGRuleId::WithOptionList, + TransformChildKind::OPTIONAL, + 3, + 2, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::QualifiedName, + TransformChildKind::REQUIRED, + 2, + 1, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::IfNotExists, + TransformChildKind::OPTIONAL, + 1, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_CreateSchemaStmt = {FRAME_CHILDREN_CreateSchemaStmt, 3, 3, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_CreateSecretStmt[] = {{PEGRuleId::GenericCopyOptionList, + TransformChildKind::REQUIRED, + 4, + 3, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::SecretStorageSpecifier, + TransformChildKind::OPTIONAL, + 3, + 2, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::SecretName, + TransformChildKind::OPTIONAL, + 2, + 1, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::IfNotExists, + TransformChildKind::OPTIONAL, + 1, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_CreateSecretStmt = {FRAME_CHILDREN_CreateSecretStmt, 4, 4, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_CreateSequenceStmt[] = {{PEGRuleId::SequenceOption, + TransformChildKind::OPTIONAL_REPEAT, + 3, + 2, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::QualifiedName, + TransformChildKind::REQUIRED, + 2, + 1, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::IfNotExists, + TransformChildKind::OPTIONAL, + 1, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_CreateSequenceStmt = {FRAME_CHILDREN_CreateSequenceStmt, 3, 3, true, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_SeqSetMinMax[] = {{PEGRuleId::Expression, + TransformChildKind::REQUIRED, + 1, + 1, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::SeqMinOrMax, + TransformChildKind::REQUIRED, + 0, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_SeqSetMinMax = {FRAME_CHILDREN_SeqSetMinMax, 2, 2, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_SeqNoMinMax[] = {{PEGRuleId::SeqMinOrMax, + TransformChildKind::REQUIRED, + 1, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_SeqNoMinMax = {FRAME_CHILDREN_SeqNoMinMax, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_SeqOwnedBy[] = {{PEGRuleId::QualifiedName, + TransformChildKind::REQUIRED, + 2, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_SeqOwnedBy = {FRAME_CHILDREN_SeqOwnedBy, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_CreateStatement[] = {{PEGRuleId::CreateStatementVariation, + TransformChildKind::REQUIRED, + 3, + 2, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::Temporary, + TransformChildKind::OPTIONAL, + 2, + 1, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::OrReplace, + TransformChildKind::OPTIONAL, + 1, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_CreateStatement = {FRAME_CHILDREN_CreateStatement, 3, 3, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_CreateTableStmt[] = {{PEGRuleId::CommitAction, + TransformChildKind::OPTIONAL, + 4, + 3, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::CreateTableDefinition, + TransformChildKind::REQUIRED, + 3, + 2, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::QualifiedName, + TransformChildKind::REQUIRED, + 2, + 1, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::IfNotExists, + TransformChildKind::OPTIONAL, + 1, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_CreateTableStmt = {FRAME_CHILDREN_CreateTableStmt, 4, 4, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_CreateTableAs[] = {{PEGRuleId::WithData, + TransformChildKind::OPTIONAL, + 5, + 4, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::Statement, + TransformChildKind::REQUIRED, + 4, + 3, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::WithList, + TransformChildKind::OPTIONAL, + 2, + 2, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::PartitionSortedOptions, + TransformChildKind::OPTIONAL, + 1, + 1, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::IdentifierList, + TransformChildKind::OPTIONAL, + 0, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_CreateTableAs = {FRAME_CHILDREN_CreateTableAs, 5, 5, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_PartitionOptSortedOptions[] = {{PEGRuleId::SortedOptions, + TransformChildKind::OPTIONAL, + 1, + 1, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::PartitionOptions, + TransformChildKind::REQUIRED, + 0, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_PartitionOptSortedOptions = { + FRAME_CHILDREN_PartitionOptSortedOptions, 2, 2, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_SortedOptPartitionOptions[] = {{PEGRuleId::PartitionOptions, + TransformChildKind::OPTIONAL, + 1, + 1, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::SortedOptions, + TransformChildKind::REQUIRED, + 0, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_SortedOptPartitionOptions = { + FRAME_CHILDREN_SortedOptPartitionOptions, 2, 2, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_PartitionOptions[] = {{PEGRuleId::Expression, + TransformChildKind::LIST, + 2, + 0, + false, + {1, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_PartitionOptions = {FRAME_CHILDREN_PartitionOptions, 1, 1, true, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_CreateColumnList[] = {{PEGRuleId::WithList, + TransformChildKind::OPTIONAL, + 2, + 2, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::PartitionSortedOptions, + TransformChildKind::OPTIONAL, + 1, + 1, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::CreateTableColumnList, + TransformChildKind::OPTIONAL, + 0, + 0, + false, + {1, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_CreateColumnList = {FRAME_CHILDREN_CreateColumnList, 3, 3, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_SchemaReservedIdentifierOrStringLiteral[] = { + {PEGRuleId::ReservedIdentifierOrStringLiteral, + TransformChildKind::REQUIRED, + 1, + 1, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::SchemaQualification, + TransformChildKind::REQUIRED, + 0, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_SchemaReservedIdentifierOrStringLiteral = { + FRAME_CHILDREN_SchemaReservedIdentifierOrStringLiteral, 2, 2, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_CatalogReservedSchemaIdentifier[] = { + {PEGRuleId::ReservedIdentifierOrStringLiteral, + TransformChildKind::REQUIRED, + 2, + 2, + true, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::ReservedSchemaQualification, + TransformChildKind::REPEAT, + 1, + 1, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::CatalogQualification, + TransformChildKind::REQUIRED, + 0, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_CatalogReservedSchemaIdentifier = { + FRAME_CHILDREN_CatalogReservedSchemaIdentifier, 3, 3, true, 0, {}}; +static const char *const FRAME_NAMES_ReservedIdentifierOrStringLiteral[] = {"StringLiteral"}; +static const TransformFramePlan FRAME_PLAN_ReservedIdentifierOrStringLiteral = { + nullptr, + 0, + 1, + false, + 0, + {ParseResultTypeBit(ParseResultType::IDENTIFIER) | ParseResultTypeBit(ParseResultType::KEYWORD) | + ParseResultTypeBit(ParseResultType::STRING), + 0, true, true, 1, FRAME_NAMES_ReservedIdentifierOrStringLiteral}}; +static const TransformChildPlan FRAME_CHILDREN_CreateTableColumnList[] = {{PEGRuleId::CreateTableColumnElement, + TransformChildKind::LIST, + 0, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_CreateTableColumnList = { + FRAME_CHILDREN_CreateTableColumnList, 1, 1, true, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_CreateTableColumnDefinition[] = {{PEGRuleId::ColumnDefinition, + TransformChildKind::REQUIRED, + 0, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_CreateTableColumnDefinition = { + FRAME_CHILDREN_CreateTableColumnDefinition, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_CreateTableConstraint[] = {{PEGRuleId::TopLevelConstraint, + TransformChildKind::REQUIRED, + 0, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_CreateTableConstraint = { + FRAME_CHILDREN_CreateTableConstraint, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_ColumnDefinition[] = {{PEGRuleId::ColumnConstraint, + TransformChildKind::OPTIONAL_REPEAT, + 3, + 2, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::GeneratedColumn, + TransformChildKind::OPTIONAL, + 2, + 1, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::Type, + TransformChildKind::OPTIONAL, + 1, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_ColumnDefinition = {FRAME_CHILDREN_ColumnDefinition, 3, 3, true, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_NameableColumnConstraint[] = {{PEGRuleId::ColumnConstraintElement, + TransformChildKind::REQUIRED, + 1, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_NameableColumnConstraint = { + FRAME_CHILDREN_NameableColumnConstraint, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_UniqueConstraint[] = {{PEGRuleId::ConstraintTiming, + TransformChildKind::OPTIONAL, + 1, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_UniqueConstraint = {FRAME_CHILDREN_UniqueConstraint, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_PrimaryKeyConstraint[] = {{PEGRuleId::ConstraintTiming, + TransformChildKind::OPTIONAL, + 2, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_PrimaryKeyConstraint = { + FRAME_CHILDREN_PrimaryKeyConstraint, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_DefaultValue[] = {{PEGRuleId::ColumnDefaultExpr, + TransformChildKind::REQUIRED, + 1, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_DefaultValue = {FRAME_CHILDREN_DefaultValue, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_CheckConstraint[] = {{PEGRuleId::Expression, + TransformChildKind::REQUIRED, + 1, + 0, + false, + {1, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_CheckConstraint = {FRAME_CHILDREN_CheckConstraint, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_ForeignKeyConstraint[] = {{PEGRuleId::KeyActions, + TransformChildKind::OPTIONAL, + 3, + 2, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::ColumnList, + TransformChildKind::OPTIONAL, + 2, + 1, + false, + {0, TRANSFORM_PATH_END, 0}, + {1, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::BaseTableName, + TransformChildKind::REQUIRED, + 1, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_ForeignKeyConstraint = { + FRAME_CHILDREN_ForeignKeyConstraint, 3, 3, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_ColumnCollation[] = {{PEGRuleId::DottedIdentifier, + TransformChildKind::REQUIRED, + 1, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_ColumnCollation = {FRAME_CHILDREN_ColumnCollation, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_UpdateFirstKeyActions[] = {{PEGRuleId::DeleteAction, + TransformChildKind::OPTIONAL, + 1, + 1, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::UpdateAction, + TransformChildKind::REQUIRED, + 0, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_UpdateFirstKeyActions = { + FRAME_CHILDREN_UpdateFirstKeyActions, 2, 2, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_DeleteFirstKeyActions[] = {{PEGRuleId::UpdateAction, + TransformChildKind::OPTIONAL, + 1, + 1, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::DeleteAction, + TransformChildKind::REQUIRED, + 0, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_DeleteFirstKeyActions = { + FRAME_CHILDREN_DeleteFirstKeyActions, 2, 2, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_DeleteAction[] = {{PEGRuleId::KeyAction, + TransformChildKind::REQUIRED, + 2, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_DeleteAction = {FRAME_CHILDREN_DeleteAction, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_TopLevelConstraint[] = {{PEGRuleId::TopLevelConstraintList, + TransformChildKind::REQUIRED, + 1, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_TopLevelConstraint = {FRAME_CHILDREN_TopLevelConstraint, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_TopCheckConstraint[] = {{PEGRuleId::CheckConstraint, + TransformChildKind::REQUIRED, + 0, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_TopCheckConstraint = {FRAME_CHILDREN_TopCheckConstraint, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_TopPrimaryKeyConstraint[] = {{PEGRuleId::ConstraintTiming, + TransformChildKind::OPTIONAL, + 3, + 1, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::ColumnIdList, + TransformChildKind::REQUIRED, + 2, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_TopPrimaryKeyConstraint = { + FRAME_CHILDREN_TopPrimaryKeyConstraint, 2, 2, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_TopUniqueConstraint[] = {{PEGRuleId::ConstraintTiming, + TransformChildKind::OPTIONAL, + 2, + 1, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::ColumnIdList, + TransformChildKind::REQUIRED, + 1, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_TopUniqueConstraint = { + FRAME_CHILDREN_TopUniqueConstraint, 2, 2, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_TopForeignKeyConstraint[] = {{PEGRuleId::ForeignKeyConstraint, + TransformChildKind::REQUIRED, + 3, + 1, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::ColumnIdList, + TransformChildKind::REQUIRED, + 2, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_TopForeignKeyConstraint = { + FRAME_CHILDREN_TopForeignKeyConstraint, 2, 2, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_ColumnIdList[] = { {PEGRuleId::ColId, TransformChildKind::LIST, 0, 0, false, {1, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_145 = {FRAME_CHILDREN_137, 1, 1, true, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_138[] = {{PEGRuleId::DotColLabel, - TransformChildKind::OPTIONAL_REPEAT, - 1, - 0, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_146 = {FRAME_CHILDREN_138, 1, 1, true, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_139[] = {{PEGRuleId::ColLabel, - TransformChildKind::REQUIRED, - 1, - 0, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_147 = {FRAME_CHILDREN_139, 1, 1, false, 0, {}}; -static const char *const FRAME_NAMES_3[] = {"UnreservedKeyword", "ColumnNameKeyword", "Identifier"}; -static const TransformFramePlan FRAME_PLAN_148 = {nullptr, - 0, - 1, - false, - 0, - {ParseResultTypeBit(ParseResultType::IDENTIFIER) | - ParseResultTypeBit(ParseResultType::KEYWORD) | - ParseResultTypeBit(ParseResultType::STRING), - 0, true, true, 3, FRAME_NAMES_3}}; -static const TransformFramePlan FRAME_PLAN_149 = {nullptr, - 0, - 1, - false, - 0, - {ParseResultTypeBit(ParseResultType::IDENTIFIER) | - ParseResultTypeBit(ParseResultType::KEYWORD) | - ParseResultTypeBit(ParseResultType::STRING), - 0, true, true, 0, nullptr}}; -static const char *const FRAME_NAMES_4[] = {"UnreservedKeyword", "TypeFuncKeyword", "Identifier"}; -static const TransformFramePlan FRAME_PLAN_150 = {nullptr, - 0, - 1, - false, - 0, - {ParseResultTypeBit(ParseResultType::IDENTIFIER) | - ParseResultTypeBit(ParseResultType::KEYWORD) | - ParseResultTypeBit(ParseResultType::STRING), - 0, true, true, 3, FRAME_NAMES_4}}; -static const char *const FRAME_NAMES_5[] = {"TypeNameKeyword", "FuncNameKeyword"}; -static const TransformFramePlan FRAME_PLAN_151 = { +static const TransformFramePlan FRAME_PLAN_ColumnIdList = {FRAME_CHILDREN_ColumnIdList, 1, 1, true, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_DottedIdentifier[] = {{PEGRuleId::DotColLabel, + TransformChildKind::OPTIONAL_REPEAT, + 1, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_DottedIdentifier = {FRAME_CHILDREN_DottedIdentifier, 1, 1, true, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_ColLabelParameter[] = {{PEGRuleId::ColLabel, + TransformChildKind::REQUIRED, + 1, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_ColLabelParameter = {FRAME_CHILDREN_ColLabelParameter, 1, 1, false, 0, {}}; +static const char *const FRAME_NAMES_ColId[] = {"UnreservedKeyword", "ColumnNameKeyword", "Identifier"}; +static const TransformFramePlan FRAME_PLAN_ColId = {nullptr, + 0, + 1, + false, + 0, + {ParseResultTypeBit(ParseResultType::IDENTIFIER) | + ParseResultTypeBit(ParseResultType::KEYWORD) | + ParseResultTypeBit(ParseResultType::STRING), + 0, true, true, 3, FRAME_NAMES_ColId}}; +static const TransformFramePlan FRAME_PLAN_ChoiceEarlyIdentifierKeywordStringEmptyNameThrow = { + nullptr, + 0, + 1, + false, + 0, + {ParseResultTypeBit(ParseResultType::IDENTIFIER) | ParseResultTypeBit(ParseResultType::KEYWORD) | + ParseResultTypeBit(ParseResultType::STRING), + 0, true, true, 0, nullptr}}; +static const char *const FRAME_NAMES_TypeFuncName[] = {"UnreservedKeyword", "TypeFuncKeyword", "Identifier"}; +static const TransformFramePlan FRAME_PLAN_TypeFuncName = {nullptr, + 0, + 1, + false, + 0, + {ParseResultTypeBit(ParseResultType::IDENTIFIER) | + ParseResultTypeBit(ParseResultType::KEYWORD) | + ParseResultTypeBit(ParseResultType::STRING), + 0, true, true, 3, FRAME_NAMES_TypeFuncName}}; +static const char *const FRAME_NAMES_TypeFuncKeyword[] = {"TypeNameKeyword", "FuncNameKeyword"}; +static const TransformFramePlan FRAME_PLAN_TypeFuncKeyword = { nullptr, 0, 1, @@ -1949,10 +1993,10 @@ static const TransformFramePlan FRAME_PLAN_151 = { 0, {ParseResultTypeBit(ParseResultType::IDENTIFIER) | ParseResultTypeBit(ParseResultType::KEYWORD) | ParseResultTypeBit(ParseResultType::STRING) | ParseResultTypeBit(ParseResultType::OPERATOR), - 0, false, true, 2, FRAME_NAMES_5}}; -static const char *const FRAME_NAMES_6[] = {"ReservedKeyword", "UnreservedKeyword", "ColumnNameKeyword", - "FuncNameKeyword", "TypeNameKeyword"}; -static const TransformFramePlan FRAME_PLAN_152 = { + 0, false, true, 2, FRAME_NAMES_TypeFuncKeyword}}; +static const char *const FRAME_NAMES_ColLabel[] = {"ReservedKeyword", "UnreservedKeyword", "ColumnNameKeyword", + "FuncNameKeyword", "TypeNameKeyword"}; +static const TransformFramePlan FRAME_PLAN_ColLabel = { nullptr, 0, 1, @@ -1960,4607 +2004,4729 @@ static const TransformFramePlan FRAME_PLAN_152 = { 0, {ParseResultTypeBit(ParseResultType::IDENTIFIER) | ParseResultTypeBit(ParseResultType::KEYWORD) | ParseResultTypeBit(ParseResultType::STRING) | ParseResultTypeBit(ParseResultType::OPERATOR), - 0, false, true, 5, FRAME_NAMES_6}}; -static const TransformChildPlan FRAME_CHILDREN_140[] = {{PEGRuleId::ColLabel, - TransformChildKind::REQUIRED, - 0, - 0, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_153 = {FRAME_CHILDREN_140, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_141[] = {{PEGRuleId::GeneratedColumnType, - TransformChildKind::OPTIONAL, - 3, - 2, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}, - {PEGRuleId::Expression, - TransformChildKind::REQUIRED, - 2, - 1, - false, - {1, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}, - {PEGRuleId::Generated, - TransformChildKind::OPTIONAL, - 0, - 0, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_154 = {FRAME_CHILDREN_141, 3, 3, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_142[] = {{PEGRuleId::PreserveOrDelete, - TransformChildKind::REQUIRED, - 2, - 0, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_155 = {FRAME_CHILDREN_142, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_143[] = {{PEGRuleId::TriggerBody, - TransformChildKind::REQUIRED, - 9, - 7, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}, - {PEGRuleId::ForEachClause, - TransformChildKind::OPTIONAL, - 8, - 6, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}, - {PEGRuleId::ReferencingClause, - TransformChildKind::OPTIONAL, - 7, - 5, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}, - {PEGRuleId::BaseTableName, - TransformChildKind::REQUIRED, - 6, - 4, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}, - {PEGRuleId::TriggerEvent, - TransformChildKind::REQUIRED, - 4, - 3, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}, - {PEGRuleId::TriggerTiming, - TransformChildKind::REQUIRED, - 3, - 2, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}, - {PEGRuleId::TriggerName, - TransformChildKind::REQUIRED, - 2, - 1, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}, - {PEGRuleId::IfNotExists, - TransformChildKind::OPTIONAL, - 1, - 0, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_156 = {FRAME_CHILDREN_143, 8, 8, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_144[] = {{PEGRuleId::ReferencingItem, - TransformChildKind::OPTIONAL, - 2, - 1, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}, - {PEGRuleId::ReferencingItem, - TransformChildKind::REQUIRED, - 1, - 0, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_157 = {FRAME_CHILDREN_144, 2, 2, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_145[] = {{PEGRuleId::ColId, - TransformChildKind::REQUIRED, - 3, - 0, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_158 = {FRAME_CHILDREN_145, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_146[] = {{PEGRuleId::TriggerColumnList, - TransformChildKind::REQUIRED, - 2, - 0, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_159 = {FRAME_CHILDREN_146, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_147[] = { + 0, false, true, 5, FRAME_NAMES_ColLabel}}; +static const TransformChildPlan FRAME_CHILDREN_ColLabelIdentifier[] = {{PEGRuleId::ColLabel, + TransformChildKind::REQUIRED, + 0, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_ColLabelIdentifier = {FRAME_CHILDREN_ColLabelIdentifier, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_GeneratedColumn[] = {{PEGRuleId::GeneratedColumnType, + TransformChildKind::OPTIONAL, + 3, + 2, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::Expression, + TransformChildKind::REQUIRED, + 2, + 1, + false, + {1, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::Generated, + TransformChildKind::OPTIONAL, + 0, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_GeneratedColumn = {FRAME_CHILDREN_GeneratedColumn, 3, 3, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_CommitAction[] = {{PEGRuleId::PreserveOrDelete, + TransformChildKind::REQUIRED, + 2, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_CommitAction = {FRAME_CHILDREN_CommitAction, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_CreateTriggerStmt[] = {{PEGRuleId::TriggerBody, + TransformChildKind::REQUIRED, + 9, + 7, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::ForEachClause, + TransformChildKind::OPTIONAL, + 8, + 6, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::ReferencingClause, + TransformChildKind::OPTIONAL, + 7, + 5, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::BaseTableName, + TransformChildKind::REQUIRED, + 6, + 4, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::TriggerEvent, + TransformChildKind::REQUIRED, + 4, + 3, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::TriggerTiming, + TransformChildKind::REQUIRED, + 3, + 2, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::TriggerName, + TransformChildKind::REQUIRED, + 2, + 1, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::IfNotExists, + TransformChildKind::OPTIONAL, + 1, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_CreateTriggerStmt = {FRAME_CHILDREN_CreateTriggerStmt, 8, 8, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_ReferencingClause[] = {{PEGRuleId::ReferencingItem, + TransformChildKind::OPTIONAL, + 2, + 1, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::ReferencingItem, + TransformChildKind::REQUIRED, + 1, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_ReferencingClause = {FRAME_CHILDREN_ReferencingClause, 2, 2, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_ReferencingNewTableAs[] = {{PEGRuleId::ColId, + TransformChildKind::REQUIRED, + 3, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_ReferencingNewTableAs = { + FRAME_CHILDREN_ReferencingNewTableAs, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_TriggerEventUpdateOf[] = {{PEGRuleId::TriggerColumnList, + TransformChildKind::REQUIRED, + 2, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_TriggerEventUpdateOf = { + FRAME_CHILDREN_TriggerEventUpdateOf, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_ColumnList[] = { {PEGRuleId::ColId, TransformChildKind::LIST, 0, 0, false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_160 = {FRAME_CHILDREN_147, 1, 1, true, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_148[] = {{PEGRuleId::CreateType, - TransformChildKind::REQUIRED, - 4, - 2, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}, - {PEGRuleId::QualifiedName, - TransformChildKind::REQUIRED, - 2, - 1, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}, - {PEGRuleId::IfNotExists, - TransformChildKind::OPTIONAL, - 1, - 0, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_161 = {FRAME_CHILDREN_148, 3, 3, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_149[] = {{PEGRuleId::Type, - TransformChildKind::REQUIRED, - 0, - 0, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_162 = {FRAME_CHILDREN_149, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_150[] = {{PEGRuleId::SelectStatementInternal, - TransformChildKind::REQUIRED, - 1, - 0, - false, - {1, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_163 = {FRAME_CHILDREN_150, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_151[] = {{PEGRuleId::ArrayBounds, - TransformChildKind::OPTIONAL_REPEAT, - 2, - 0, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_164 = {FRAME_CHILDREN_151, 1, 1, true, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_152[] = {{PEGRuleId::SelectStatementInternal, - TransformChildKind::REQUIRED, - 8, - 6, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}, - {PEGRuleId::WithList, - TransformChildKind::OPTIONAL, - 6, - 5, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}, - {PEGRuleId::InsertColumnList, - TransformChildKind::OPTIONAL, - 5, - 4, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}, - {PEGRuleId::QualifiedName, - TransformChildKind::REQUIRED, - 4, - 3, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}, - {PEGRuleId::IfNotExists, - TransformChildKind::OPTIONAL, - 3, - 2, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}, - {PEGRuleId::CreateRecursive, - TransformChildKind::OPTIONAL, - 1, - 1, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}, - {PEGRuleId::CreateSecure, - TransformChildKind::OPTIONAL, - 0, - 0, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_165 = {FRAME_CHILDREN_152, 7, 7, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_153[] = {{PEGRuleId::ColIdOrString, - TransformChildKind::REQUIRED, - 2, - 1, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}, - {PEGRuleId::DeallocatePrepare, - TransformChildKind::OPTIONAL, - 1, - 0, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_166 = {FRAME_CHILDREN_153, 2, 2, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_154[] = {{PEGRuleId::ReturningClause, - TransformChildKind::OPTIONAL, - 6, - 4, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}, - {PEGRuleId::WhereClause, - TransformChildKind::OPTIONAL, - 5, - 3, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}, - {PEGRuleId::DeleteUsingClause, - TransformChildKind::OPTIONAL, - 4, - 2, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}, - {PEGRuleId::TargetOptAlias, - TransformChildKind::REQUIRED, - 3, - 1, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}, - {PEGRuleId::WithClause, - TransformChildKind::OPTIONAL, - 0, - 0, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_167 = {FRAME_CHILDREN_154, 5, 5, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_155[] = {{PEGRuleId::TruncateOptions, - TransformChildKind::OPTIONAL, - 3, - 1, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}, - {PEGRuleId::BaseTableName, - TransformChildKind::REQUIRED, - 2, - 0, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_168 = {FRAME_CHILDREN_155, 2, 2, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_156[] = {{PEGRuleId::TruncateDropBehavior, - TransformChildKind::OPTIONAL, - 1, - 1, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}, - {PEGRuleId::TargetAlias, - TransformChildKind::REQUIRED, - 0, - 0, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_169 = {FRAME_CHILDREN_156, 2, 2, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_157[] = {{PEGRuleId::DropBehavior, - TransformChildKind::REQUIRED, - 0, - 0, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_170 = {FRAME_CHILDREN_157, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_158[] = {{PEGRuleId::TargetAlias, - TransformChildKind::OPTIONAL, - 1, - 1, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}, - {PEGRuleId::BaseTableName, - TransformChildKind::REQUIRED, - 0, - 0, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_171 = {FRAME_CHILDREN_158, 2, 2, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_159[] = {{PEGRuleId::TableRef, - TransformChildKind::LIST, - 1, - 0, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_172 = {FRAME_CHILDREN_159, 1, 1, true, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_160[] = {{PEGRuleId::ShowExternalResourcesType, - TransformChildKind::OPTIONAL, - 4, - 1, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}, - {PEGRuleId::ShowRule, - TransformChildKind::REQUIRED, - 0, - 0, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_173 = {FRAME_CHILDREN_160, 2, 2, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_161[] = {{PEGRuleId::ExternalResourceType, - TransformChildKind::REQUIRED, - 2, - 0, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_174 = {FRAME_CHILDREN_161, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_162[] = {{PEGRuleId::ShowRule, - TransformChildKind::REQUIRED, - 0, - 0, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_175 = {FRAME_CHILDREN_162, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_163[] = {{PEGRuleId::SelectStatementInternal, - TransformChildKind::REQUIRED, - 1, - 1, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}, - {PEGRuleId::ShowRule, - TransformChildKind::REQUIRED, - 0, - 0, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_176 = {FRAME_CHILDREN_163, 2, 2, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_164[] = {{PEGRuleId::SelectStatementInternal, - TransformChildKind::REQUIRED, - 1, - 1, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}, - {PEGRuleId::DescribeOrSummarize, - TransformChildKind::REQUIRED, - 0, - 0, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_177 = {FRAME_CHILDREN_164, 2, 2, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_165[] = {{PEGRuleId::ShowOrDescribe, - TransformChildKind::REQUIRED, - 0, - 0, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_178 = {FRAME_CHILDREN_165, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_166[] = {{PEGRuleId::QualifiedName, - TransformChildKind::REQUIRED, - 3, - 1, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}, - {PEGRuleId::ShowOrDescribe, - TransformChildKind::REQUIRED, - 0, - 0, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_179 = {FRAME_CHILDREN_166, 2, 2, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_167[] = {{PEGRuleId::ShowTarget, - TransformChildKind::OPTIONAL, - 1, - 1, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}, - {PEGRuleId::ShowRule, - TransformChildKind::REQUIRED, - 0, - 0, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_180 = {FRAME_CHILDREN_167, 2, 2, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_168[] = {{PEGRuleId::DescribeTarget, - TransformChildKind::OPTIONAL, - 1, - 1, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}, - {PEGRuleId::DescribeOrSummarize, - TransformChildKind::REQUIRED, - 0, - 0, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_181 = {FRAME_CHILDREN_168, 2, 2, false, 0, {}}; -static const char *const FRAME_NAMES_7[] = {"ShowSpecialForm"}; -static const TransformFramePlan FRAME_PLAN_182 = {nullptr, 0, 1, false, 0, {0, 0, false, true, 1, FRAME_NAMES_7}}; -static const TransformChildPlan FRAME_CHILDREN_169[] = {{PEGRuleId::QualifiedTableName, - TransformChildKind::REQUIRED, - 0, - 0, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_183 = {FRAME_CHILDREN_169, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_170[] = {{PEGRuleId::BaseTableName, - TransformChildKind::REQUIRED, - 0, - 0, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_184 = {FRAME_CHILDREN_170, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_171[] = {{PEGRuleId::SummarizeRule, - TransformChildKind::REQUIRED, - 0, - 0, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_185 = {FRAME_CHILDREN_171, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_172[] = {{PEGRuleId::IfExists, - TransformChildKind::OPTIONAL, - 2, - 0, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_186 = {FRAME_CHILDREN_172, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_173[] = {{PEGRuleId::DropBehavior, - TransformChildKind::OPTIONAL, - 2, - 1, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}, - {PEGRuleId::DropEntries, - TransformChildKind::REQUIRED, - 1, - 0, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_187 = {FRAME_CHILDREN_173, 2, 2, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_174[] = {{PEGRuleId::DropBehavior, - TransformChildKind::OPTIONAL, - 2, - 1, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}, - {PEGRuleId::DropMember, - TransformChildKind::REQUIRED, - 1, - 0, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_188 = {FRAME_CHILDREN_174, 2, 2, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_175[] = {{PEGRuleId::DropFunctionSignature, - TransformChildKind::REQUIRED, - 3, - 3, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}, - {PEGRuleId::QualifiedTableFunction, - TransformChildKind::REQUIRED, - 2, - 2, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}, - {PEGRuleId::IfExists, - TransformChildKind::OPTIONAL, - 1, - 1, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}, - {PEGRuleId::CommentMacroTable, - TransformChildKind::REQUIRED, - 0, - 0, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_189 = {FRAME_CHILDREN_175, 4, 4, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_176[] = {{PEGRuleId::DropFunctionSignature, - TransformChildKind::REQUIRED, - 3, - 3, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}, - {PEGRuleId::FunctionIdentifier, - TransformChildKind::REQUIRED, - 2, - 2, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}, - {PEGRuleId::IfExists, - TransformChildKind::OPTIONAL, - 1, - 1, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}, - {PEGRuleId::FunctionTypeMacro, - TransformChildKind::REQUIRED, - 0, - 0, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_190 = {FRAME_CHILDREN_176, 4, 4, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_177[] = {{PEGRuleId::BaseTableName, - TransformChildKind::REQUIRED, - 4, - 2, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}, - {PEGRuleId::TriggerName, - TransformChildKind::REQUIRED, - 2, - 1, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}, - {PEGRuleId::IfExists, - TransformChildKind::OPTIONAL, - 1, - 0, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_191 = {FRAME_CHILDREN_177, 3, 3, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_178[] = {{PEGRuleId::BaseTableName, - TransformChildKind::LIST, - 2, - 2, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}, - {PEGRuleId::IfExists, - TransformChildKind::OPTIONAL, - 1, - 1, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}, - {PEGRuleId::TableOrView, - TransformChildKind::REQUIRED, - 0, - 0, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_192 = {FRAME_CHILDREN_178, 3, 3, true, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_179[] = {{PEGRuleId::QualifiedTableFunction, - TransformChildKind::LIST, - 2, - 2, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}, - {PEGRuleId::IfExists, - TransformChildKind::OPTIONAL, - 1, - 1, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}, - {PEGRuleId::CommentMacroTable, - TransformChildKind::REQUIRED, - 0, - 0, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_193 = {FRAME_CHILDREN_179, 3, 3, true, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_180[] = {{PEGRuleId::FunctionIdentifier, - TransformChildKind::LIST, - 2, - 2, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}, - {PEGRuleId::IfExists, - TransformChildKind::OPTIONAL, - 1, - 1, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}, - {PEGRuleId::FunctionTypeMacro, - TransformChildKind::REQUIRED, - 0, - 0, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_194 = {FRAME_CHILDREN_180, 3, 3, true, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_181[] = {{PEGRuleId::DropSignatureType, - TransformChildKind::OPTIONAL_LIST, - 0, - 0, - false, - {1, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_195 = {FRAME_CHILDREN_181, 1, 1, true, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_182[] = {{PEGRuleId::QualifiedName, - TransformChildKind::LIST, - 2, - 1, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}, - {PEGRuleId::IfExists, - TransformChildKind::OPTIONAL, - 1, - 0, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_196 = {FRAME_CHILDREN_182, 2, 2, true, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_183[] = {{PEGRuleId::QualifiedIndexName, - TransformChildKind::LIST, - 2, - 1, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}, - {PEGRuleId::IfExists, - TransformChildKind::OPTIONAL, - 1, - 0, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_197 = {FRAME_CHILDREN_183, 2, 2, true, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_184[] = {{PEGRuleId::QualifiedSequenceName, - TransformChildKind::LIST, - 2, - 1, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}, - {PEGRuleId::IfExists, - TransformChildKind::OPTIONAL, - 1, - 0, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_198 = {FRAME_CHILDREN_184, 2, 2, true, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_185[] = {{PEGRuleId::CollationName, - TransformChildKind::LIST, - 2, - 1, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}, - {PEGRuleId::IfExists, - TransformChildKind::OPTIONAL, - 1, - 0, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_199 = {FRAME_CHILDREN_185, 2, 2, true, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_186[] = {{PEGRuleId::QualifiedTypeName, - TransformChildKind::LIST, - 2, - 1, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}, - {PEGRuleId::IfExists, - TransformChildKind::OPTIONAL, - 1, - 0, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_200 = {FRAME_CHILDREN_186, 2, 2, true, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_187[] = {{PEGRuleId::DropSecretStorage, - TransformChildKind::OPTIONAL, - 4, - 3, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}, - {PEGRuleId::SecretName, - TransformChildKind::REQUIRED, - 3, - 2, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}, - {PEGRuleId::IfExists, - TransformChildKind::OPTIONAL, - 2, - 1, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}, - {PEGRuleId::Temporary, - TransformChildKind::OPTIONAL, - 0, - 0, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_201 = {FRAME_CHILDREN_187, 4, 4, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_188[] = {{PEGRuleId::TableFunctionArguments, - TransformChildKind::OPTIONAL, - 2, - 1, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}, - {PEGRuleId::ColIdOrString, - TransformChildKind::REQUIRED, - 1, - 0, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_202 = {FRAME_CHILDREN_188, 2, 2, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_189[] = {{PEGRuleId::ExplainableStatements, - TransformChildKind::REQUIRED, - 3, - 2, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}, - {PEGRuleId::ExplainOptionList, - TransformChildKind::OPTIONAL, - 2, - 1, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}, - {PEGRuleId::AnalyzeKeyword, - TransformChildKind::OPTIONAL, - 1, - 0, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_203 = {FRAME_CHILDREN_189, 3, 3, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_190[] = {{PEGRuleId::ExplainOption, - TransformChildKind::LIST, - 0, - 0, - false, - {1, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_204 = {FRAME_CHILDREN_190, 1, 1, true, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_191[] = {{PEGRuleId::Expression, - TransformChildKind::OPTIONAL, - 1, - 1, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}, - {PEGRuleId::ExplainOptionName, - TransformChildKind::REQUIRED, - 0, - 0, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_205 = {FRAME_CHILDREN_191, 2, 2, false, 0, {}}; -static const char *const FRAME_NAMES_8[] = {"FuncNameKeyword", "TypeNameKeyword"}; -static const TransformFramePlan FRAME_PLAN_206 = {nullptr, - 0, - 1, - false, - 0, - {ParseResultTypeBit(ParseResultType::IDENTIFIER) | - ParseResultTypeBit(ParseResultType::KEYWORD) | - ParseResultTypeBit(ParseResultType::STRING), - 0, true, false, 2, FRAME_NAMES_8}}; -static const TransformChildPlan FRAME_CHILDREN_192[] = {{PEGRuleId::SelectStatementInternal, - TransformChildKind::REQUIRED, - 0, - 0, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_207 = {FRAME_CHILDREN_192, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_193[] = {{PEGRuleId::ExportOptions, - TransformChildKind::OPTIONAL, - 4, - 1, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}, - {PEGRuleId::ExportSource, - TransformChildKind::OPTIONAL, - 2, - 0, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_208 = {FRAME_CHILDREN_193, 2, 2, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_194[] = {{PEGRuleId::ReservedSchemaQualification, - TransformChildKind::REPEAT, - 3, - 3, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}, - {PEGRuleId::ReservedSchemaQualification, - TransformChildKind::REQUIRED, - 2, - 2, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}, - {PEGRuleId::ReservedSchemaQualification, - TransformChildKind::REQUIRED, - 1, - 1, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}, - {PEGRuleId::CatalogQualification, - TransformChildKind::REQUIRED, - 0, - 0, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_209 = {FRAME_CHILDREN_194, 4, 4, true, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_195[] = {{PEGRuleId::ReservedTableQualification, - TransformChildKind::REQUIRED, - 2, - 2, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}, - {PEGRuleId::ReservedSchemaQualification, - TransformChildKind::REQUIRED, - 1, - 1, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}, - {PEGRuleId::CatalogQualification, - TransformChildKind::REQUIRED, - 0, - 0, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_210 = {FRAME_CHILDREN_195, 3, 3, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_196[] = {{PEGRuleId::ReservedTableQualification, - TransformChildKind::REQUIRED, - 1, - 1, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}, - {PEGRuleId::SchemaQualification, - TransformChildKind::REQUIRED, - 0, - 0, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_211 = {FRAME_CHILDREN_196, 2, 2, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_197[] = {{PEGRuleId::TableQualification, - TransformChildKind::REQUIRED, - 0, - 0, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_212 = {FRAME_CHILDREN_197, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_198[] = {{PEGRuleId::OverClause, - TransformChildKind::OPTIONAL, - 5, - 4, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}, - {PEGRuleId::FilterClause, - TransformChildKind::OPTIONAL, - 3, - 3, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}, - {PEGRuleId::WithinGroupClause, - TransformChildKind::OPTIONAL, - 2, - 2, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}, - {PEGRuleId::FunctionExpressionArguments, - TransformChildKind::REQUIRED, - 1, - 1, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}, - {PEGRuleId::FunctionIdentifier, - TransformChildKind::REQUIRED, - 0, - 0, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_213 = {FRAME_CHILDREN_198, 5, 5, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_199[] = {{PEGRuleId::FunctionExpressionArgumentList, - TransformChildKind::REQUIRED, - 0, - 0, - false, - {1, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_214 = {FRAME_CHILDREN_199, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_200[] = {{PEGRuleId::IgnoreOrRespectNulls, - TransformChildKind::OPTIONAL, - 3, - 3, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}, - {PEGRuleId::OrderByClause, - TransformChildKind::OPTIONAL, - 2, - 2, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}, - {PEGRuleId::FunctionArgumentList, - TransformChildKind::OPTIONAL, - 1, - 1, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}, - {PEGRuleId::DistinctOrAll, - TransformChildKind::OPTIONAL, - 0, - 0, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_215 = {FRAME_CHILDREN_200, 4, 4, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_201[] = {{PEGRuleId::FunctionArgument, - TransformChildKind::LIST, - 0, - 0, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_216 = {FRAME_CHILDREN_201, 1, 1, true, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_202[] = {{PEGRuleId::ReservedSchemaQualification, - TransformChildKind::OPTIONAL_REPEAT, - 1, - 1, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}, - {PEGRuleId::CatalogQualification, - TransformChildKind::REQUIRED, - 0, - 0, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_217 = {FRAME_CHILDREN_202, 2, 2, true, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_203[] = {{PEGRuleId::OrderByClause, - TransformChildKind::REQUIRED, - 2, - 0, - false, - {1, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_218 = {FRAME_CHILDREN_203, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_204[] = {{PEGRuleId::FilterClauseExpression, - TransformChildKind::REQUIRED, - 1, - 0, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_219 = {FRAME_CHILDREN_204, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_205[] = {{PEGRuleId::FilterClauseContents, - TransformChildKind::REQUIRED, - 0, - 0, - false, - {1, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_220 = {FRAME_CHILDREN_205, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_206[] = {{PEGRuleId::CastArguments, - TransformChildKind::REQUIRED, - 1, - 1, - false, - {1, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}, - {PEGRuleId::CastOrTryCast, - TransformChildKind::REQUIRED, - 0, - 0, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_221 = {FRAME_CHILDREN_206, 2, 2, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_207[] = {{PEGRuleId::Type, - TransformChildKind::REQUIRED, - 2, - 1, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}, - {PEGRuleId::Expression, - TransformChildKind::REQUIRED, - 0, - 0, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_222 = {FRAME_CHILDREN_207, 2, 2, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_208[] = {{PEGRuleId::RenameList, - TransformChildKind::OPTIONAL, - 4, - 3, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}, - {PEGRuleId::ReplaceList, - TransformChildKind::OPTIONAL, - 3, - 2, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}, - {PEGRuleId::ExcludeList, - TransformChildKind::OPTIONAL, - 2, - 1, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}, - {PEGRuleId::StarQualifierList, - TransformChildKind::OPTIONAL, - 0, - 0, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_223 = {FRAME_CHILDREN_208, 4, 4, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_209[] = {{PEGRuleId::ColIdDot, - TransformChildKind::REPEAT, - 0, - 0, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_224 = {FRAME_CHILDREN_209, 1, 1, true, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_210[] = {{PEGRuleId::ExcludeNames, - TransformChildKind::REQUIRED, - 1, - 0, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_225 = {FRAME_CHILDREN_210, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_211[] = {{PEGRuleId::ExcludeName, - TransformChildKind::LIST, - 0, - 0, - false, - {1, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_226 = {FRAME_CHILDREN_211, 1, 1, true, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_212[] = {{PEGRuleId::ExcludeName, - TransformChildKind::REQUIRED, - 0, - 0, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_227 = {FRAME_CHILDREN_212, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_213[] = {{PEGRuleId::DottedIdentifier, - TransformChildKind::REQUIRED, - 0, - 0, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_228 = {FRAME_CHILDREN_213, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_214[] = {{PEGRuleId::ReplaceEntries, - TransformChildKind::REQUIRED, - 1, - 0, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_229 = {FRAME_CHILDREN_214, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_215[] = {{PEGRuleId::ReplaceEntry, - TransformChildKind::REQUIRED, - 0, - 0, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_230 = {FRAME_CHILDREN_215, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_216[] = {{PEGRuleId::ReplaceEntry, - TransformChildKind::LIST, - 0, - 0, - false, - {1, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_231 = {FRAME_CHILDREN_216, 1, 1, true, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_217[] = {{PEGRuleId::ColumnReference, - TransformChildKind::REQUIRED, - 2, - 1, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}, - {PEGRuleId::Expression, - TransformChildKind::REQUIRED, - 0, - 0, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_232 = {FRAME_CHILDREN_217, 2, 2, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_218[] = {{PEGRuleId::RenameEntries, - TransformChildKind::REQUIRED, - 1, - 0, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_233 = {FRAME_CHILDREN_218, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_219[] = {{PEGRuleId::RenameEntry, - TransformChildKind::LIST, - 0, - 0, - false, - {1, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_234 = {FRAME_CHILDREN_219, 1, 1, true, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_220[] = {{PEGRuleId::RenameEntry, - TransformChildKind::REQUIRED, - 0, - 0, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_235 = {FRAME_CHILDREN_220, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_221[] = {{PEGRuleId::SubqueryReference, - TransformChildKind::REQUIRED, - 2, - 2, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}, - {PEGRuleId::SubqueryExists, - TransformChildKind::OPTIONAL, - 1, - 1, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}, - {PEGRuleId::SubqueryNot, - TransformChildKind::OPTIONAL, - 0, - 0, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_236 = {FRAME_CHILDREN_221, 3, 3, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_222[] = {{PEGRuleId::CaseElse, - TransformChildKind::OPTIONAL, - 3, - 2, - true, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}, - {PEGRuleId::SimpleCaseWhenThen, - TransformChildKind::REPEAT, - 2, - 1, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}, - {PEGRuleId::Expression, - TransformChildKind::REQUIRED, - 1, - 0, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_237 = {FRAME_CHILDREN_222, 3, 3, true, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_223[] = {{PEGRuleId::CaseElse, - TransformChildKind::OPTIONAL, - 2, - 1, - true, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}, - {PEGRuleId::CaseWhenThen, - TransformChildKind::REPEAT, - 1, - 0, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_238 = {FRAME_CHILDREN_223, 2, 2, true, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_224[] = {{PEGRuleId::Expression, - TransformChildKind::REQUIRED, - 3, - 1, - true, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}, - {PEGRuleId::SimpleCaseWhenOperand, - TransformChildKind::LIST, - 1, - 0, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_239 = {FRAME_CHILDREN_224, 2, 2, true, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_225[] = {{PEGRuleId::Expression, - TransformChildKind::REQUIRED, - 3, - 1, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}, - {PEGRuleId::Expression, - TransformChildKind::REQUIRED, - 1, - 0, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_240 = {FRAME_CHILDREN_225, 2, 2, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_226[] = {{PEGRuleId::Interval, - TransformChildKind::OPTIONAL, - 2, - 1, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}, - {PEGRuleId::IntervalParameter, - TransformChildKind::REQUIRED, - 1, - 0, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_241 = {FRAME_CHILDREN_226, 2, 2, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_227[] = {{PEGRuleId::WindowExcludeClause, - TransformChildKind::OPTIONAL, - 2, - 2, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}, - {PEGRuleId::FrameExtent, - TransformChildKind::REQUIRED, - 1, - 1, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}, - {PEGRuleId::Framing, - TransformChildKind::REQUIRED, - 0, - 0, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_242 = {FRAME_CHILDREN_227, 3, 3, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_228[] = {{PEGRuleId::FrameBound, - TransformChildKind::REQUIRED, - 0, - 0, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_243 = {FRAME_CHILDREN_228, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_229[] = {{PEGRuleId::FrameBound, - TransformChildKind::REQUIRED, - 3, - 1, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}, - {PEGRuleId::FrameBound, - TransformChildKind::REQUIRED, - 1, - 0, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_244 = {FRAME_CHILDREN_229, 2, 2, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_230[] = {{PEGRuleId::PrecedingOrFollowing, - TransformChildKind::REQUIRED, - 1, - 0, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_245 = {FRAME_CHILDREN_230, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_231[] = {{PEGRuleId::PrecedingOrFollowing, - TransformChildKind::REQUIRED, - 1, - 1, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}, - {PEGRuleId::Expression, - TransformChildKind::REQUIRED, - 0, - 0, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_246 = {FRAME_CHILDREN_231, 2, 2, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_232[] = {{PEGRuleId::WindowExcludeElement, - TransformChildKind::REQUIRED, - 1, - 0, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_247 = {FRAME_CHILDREN_232, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_233[] = {{PEGRuleId::WindowFrameNameContents, - TransformChildKind::REQUIRED, - 0, - 0, - false, - {1, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_248 = {FRAME_CHILDREN_233, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_234[] = {{PEGRuleId::WindowFrameContents, - TransformChildKind::REQUIRED, - 1, - 1, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}, - {PEGRuleId::BaseWindowName, - TransformChildKind::OPTIONAL, - 0, - 0, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_249 = {FRAME_CHILDREN_234, 2, 2, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_235[] = {{PEGRuleId::WindowFrameContents, - TransformChildKind::REQUIRED, - 0, - 0, - false, - {1, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_250 = {FRAME_CHILDREN_235, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_236[] = {{PEGRuleId::FrameClause, - TransformChildKind::OPTIONAL, - 2, - 2, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}, - {PEGRuleId::OrderByClause, - TransformChildKind::OPTIONAL, - 1, - 1, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}, - {PEGRuleId::WindowPartition, - TransformChildKind::OPTIONAL, - 0, - 0, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_251 = {FRAME_CHILDREN_236, 3, 3, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_237[] = {{PEGRuleId::Expression, - TransformChildKind::LIST, - 2, - 0, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_252 = {FRAME_CHILDREN_237, 1, 1, true, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_238[] = {{PEGRuleId::BoundedListExpression, - TransformChildKind::REQUIRED, - 1, - 0, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_253 = {FRAME_CHILDREN_238, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_239[] = {{PEGRuleId::Expression, - TransformChildKind::OPTIONAL_LIST, - 1, - 0, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_254 = {FRAME_CHILDREN_239, 1, 1, true, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_240[] = {{PEGRuleId::StructField, - TransformChildKind::OPTIONAL_LIST, - 1, - 0, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_255 = {FRAME_CHILDREN_240, 1, 1, true, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_241[] = {{PEGRuleId::Expression, - TransformChildKind::REQUIRED, - 2, - 1, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}, - {PEGRuleId::ColIdOrString, - TransformChildKind::REQUIRED, - 0, - 0, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_256 = {FRAME_CHILDREN_241, 2, 2, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_242[] = {{PEGRuleId::MapStructExpression, - TransformChildKind::REQUIRED, - 1, - 0, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_257 = {FRAME_CHILDREN_242, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_243[] = {{PEGRuleId::MapStructField, - TransformChildKind::OPTIONAL_LIST, - 1, - 0, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_258 = {FRAME_CHILDREN_243, 1, 1, true, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_244[] = {{PEGRuleId::Expression, - TransformChildKind::REQUIRED, - 2, - 1, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}, - {PEGRuleId::Expression, - TransformChildKind::REQUIRED, - 0, - 0, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_259 = {FRAME_CHILDREN_244, 2, 2, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_245[] = {{PEGRuleId::Expression, - TransformChildKind::OPTIONAL_LIST, - 1, - 1, - false, - {1, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}, - {PEGRuleId::GroupingOrGroupingId, - TransformChildKind::REQUIRED, - 0, - 0, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_260 = {FRAME_CHILDREN_245, 2, 2, true, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_246[] = {{PEGRuleId::ListComprehensionFilter, - TransformChildKind::OPTIONAL, - 6, - 3, - true, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}, - {PEGRuleId::Expression, - TransformChildKind::REQUIRED, - 5, - 2, - true, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}, - {PEGRuleId::ColIdOrString, - TransformChildKind::LIST, - 3, - 1, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}, - {PEGRuleId::Expression, - TransformChildKind::REQUIRED, - 1, - 0, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_261 = {FRAME_CHILDREN_246, 4, 4, true, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_247[] = {{PEGRuleId::Expression, - TransformChildKind::REQUIRED, - 0, - 0, - false, - {1, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_262 = {FRAME_CHILDREN_247, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_248[] = {{PEGRuleId::FunctionExpression, - TransformChildKind::REQUIRED, - 1, - 1, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}, - {PEGRuleId::MeasureSemantics, - TransformChildKind::REQUIRED, - 0, - 0, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_263 = {FRAME_CHILDREN_248, 2, 2, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_249[] = {{PEGRuleId::LogicalOrExpression, - TransformChildKind::REQUIRED, - 0, - 0, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_264 = {FRAME_CHILDREN_249, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_250[] = {{PEGRuleId::ColDefOrExpr, - TransformChildKind::REQUIRED, - 0, - 0, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_265 = {FRAME_CHILDREN_250, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_251[] = {{PEGRuleId::LogicalOrExpressionTail, - TransformChildKind::OPTIONAL_REPEAT, - 1, - 1, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}, - {PEGRuleId::LogicalAndExpression, - TransformChildKind::REQUIRED, - 0, - 0, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_266 = {FRAME_CHILDREN_251, 2, 2, true, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_252[] = {{PEGRuleId::LogicalAndExpression, - TransformChildKind::REQUIRED, - 1, - 0, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_267 = {FRAME_CHILDREN_252, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_253[] = {{PEGRuleId::ColDefOrExpressionTail, - TransformChildKind::OPTIONAL_REPEAT, - 1, - 1, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}, - {PEGRuleId::ColDefAndExpr, - TransformChildKind::REQUIRED, - 0, - 0, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_268 = {FRAME_CHILDREN_253, 2, 2, true, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_254[] = {{PEGRuleId::ColDefAndExpr, - TransformChildKind::REQUIRED, - 1, - 0, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_269 = {FRAME_CHILDREN_254, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_255[] = {{PEGRuleId::LogicalAndExpressionTail, - TransformChildKind::OPTIONAL_REPEAT, - 1, - 1, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}, - {PEGRuleId::LogicalNotExpression, - TransformChildKind::REQUIRED, - 0, - 0, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_270 = {FRAME_CHILDREN_255, 2, 2, true, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_256[] = {{PEGRuleId::LogicalNotExpression, - TransformChildKind::REQUIRED, - 1, - 0, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_271 = {FRAME_CHILDREN_256, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_257[] = {{PEGRuleId::ColDefAndExpressionTail, - TransformChildKind::OPTIONAL_REPEAT, - 1, - 1, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}, - {PEGRuleId::IsDistinctFromExpression, - TransformChildKind::REQUIRED, - 0, - 0, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_272 = {FRAME_CHILDREN_257, 2, 2, true, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_258[] = {{PEGRuleId::IsDistinctFromExpression, - TransformChildKind::REQUIRED, - 1, - 0, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_273 = {FRAME_CHILDREN_258, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_259[] = {{PEGRuleId::IsExpression, - TransformChildKind::REQUIRED, - 1, - 1, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}, - {PEGRuleId::NotExpression, - TransformChildKind::OPTIONAL, - 0, - 0, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_274 = {FRAME_CHILDREN_259, 2, 2, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_260[] = {{PEGRuleId::NotKeyword, - TransformChildKind::REPEAT, - 0, - 0, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_275 = {FRAME_CHILDREN_260, 1, 1, true, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_261[] = {{PEGRuleId::IsExpressionContinuation, - TransformChildKind::OPTIONAL, - 1, - 1, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}, - {PEGRuleId::IsDistinctFromExpression, - TransformChildKind::REQUIRED, - 0, - 0, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_276 = {FRAME_CHILDREN_261, 2, 2, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_262[] = {{PEGRuleId::IsExpressionTail, - TransformChildKind::OPTIONAL_REPEAT, - 1, - 1, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}, - {PEGRuleId::IsTest, - TransformChildKind::REQUIRED, - 0, - 0, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_277 = {FRAME_CHILDREN_262, 2, 2, true, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_263[] = {{PEGRuleId::IsTest, - TransformChildKind::REQUIRED, - 0, - 0, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_278 = {FRAME_CHILDREN_263, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_264[] = {{PEGRuleId::IsDistinctFromTail, - TransformChildKind::REQUIRED, - 0, - 0, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_279 = {FRAME_CHILDREN_264, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_265[] = {{PEGRuleId::ComparisonExpressionTail, - TransformChildKind::REQUIRED, - 0, - 0, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_280 = {FRAME_CHILDREN_265, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_266[] = {{PEGRuleId::OtherOperatorTail, - TransformChildKind::REQUIRED, - 0, - 0, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_281 = {FRAME_CHILDREN_266, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_267[] = {{PEGRuleId::CastOperator, - TransformChildKind::REQUIRED, - 0, - 0, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_282 = {FRAME_CHILDREN_267, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_268[] = {{PEGRuleId::IsLiteralValue, - TransformChildKind::REQUIRED, - 2, - 0, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_283 = {FRAME_CHILDREN_268, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_269[] = {{PEGRuleId::IsNullOperator, - TransformChildKind::REQUIRED, - 0, - 0, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_284 = {FRAME_CHILDREN_269, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_270[] = {{PEGRuleId::IsDistinctFromTail, - TransformChildKind::OPTIONAL_REPEAT, - 1, - 1, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}, - {PEGRuleId::ComparisonExpression, - TransformChildKind::REQUIRED, - 0, - 0, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_285 = {FRAME_CHILDREN_270, 2, 2, true, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_271[] = {{PEGRuleId::ComparisonExpression, - TransformChildKind::REQUIRED, - 1, - 1, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}, - {PEGRuleId::IsDistinctFromOp, - TransformChildKind::REQUIRED, - 0, - 0, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_286 = {FRAME_CHILDREN_271, 2, 2, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_272[] = {{PEGRuleId::ComparisonExpressionTail, - TransformChildKind::OPTIONAL_REPEAT, - 1, - 1, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}, - {PEGRuleId::BetweenInLikeExpression, - TransformChildKind::REQUIRED, - 0, - 0, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_287 = {FRAME_CHILDREN_272, 2, 2, true, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_273[] = {{PEGRuleId::ComparisonOperand, - TransformChildKind::REQUIRED, - 1, - 1, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}, - {PEGRuleId::ComparisonOperator, - TransformChildKind::REQUIRED, - 0, - 0, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_288 = {FRAME_CHILDREN_273, 2, 2, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_274[] = {{PEGRuleId::IsExpression, - TransformChildKind::REQUIRED, - 1, - 1, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}, - {PEGRuleId::NotExpression, - TransformChildKind::REQUIRED, - 0, - 0, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_289 = {FRAME_CHILDREN_274, 2, 2, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_275[] = {{PEGRuleId::BetweenLikeOp, - TransformChildKind::OPTIONAL, - 2, - 2, - true, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}, - {PEGRuleId::InPredicate, - TransformChildKind::OPTIONAL_REPEAT, - 1, - 1, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}, - {PEGRuleId::OtherOperatorExpression, - TransformChildKind::REQUIRED, - 0, - 0, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_290 = {FRAME_CHILDREN_275, 3, 3, true, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_276[] = {{PEGRuleId::CastOperator, - TransformChildKind::OPTIONAL_REPEAT, - 2, - 1, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}, - {PEGRuleId::InClause, - TransformChildKind::REQUIRED, - 1, - 0, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_291 = {FRAME_CHILDREN_276, 2, 2, true, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_277[] = {{PEGRuleId::BetweenLikeOpExpression, - TransformChildKind::REQUIRED, - 1, - 0, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_292 = {FRAME_CHILDREN_277, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_278[] = {{PEGRuleId::EscapeClause, - TransformChildKind::OPTIONAL, - 2, - 2, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}, - {PEGRuleId::OtherOperatorExpression, - TransformChildKind::REQUIRED, - 1, - 1, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}, - {PEGRuleId::LikeVariations, - TransformChildKind::REQUIRED, - 0, - 0, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_293 = {FRAME_CHILDREN_278, 3, 3, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_279[] = {{PEGRuleId::OtherOperatorExpression, - TransformChildKind::REQUIRED, - 1, - 0, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_294 = {FRAME_CHILDREN_279, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_280[] = {{PEGRuleId::InExpression, - TransformChildKind::REQUIRED, - 1, - 0, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_295 = {FRAME_CHILDREN_280, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_281[] = {{PEGRuleId::OtherOperatorExpression, - TransformChildKind::REQUIRED, - 0, - 0, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_296 = {FRAME_CHILDREN_281, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_282[] = {{PEGRuleId::Expression, - TransformChildKind::LIST, - 0, - 0, - false, - {1, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_297 = {FRAME_CHILDREN_282, 1, 1, true, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_283[] = {{PEGRuleId::SelectStatementInternal, - TransformChildKind::REQUIRED, - 0, - 0, - false, - {1, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_298 = {FRAME_CHILDREN_283, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_284[] = {{PEGRuleId::OtherOperatorExpression, - TransformChildKind::REQUIRED, - 4, - 1, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}, - {PEGRuleId::OtherOperatorExpression, - TransformChildKind::REQUIRED, - 2, - 0, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_299 = {FRAME_CHILDREN_284, 2, 2, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_285[] = {{PEGRuleId::InfixOtherOperatorExpression, - TransformChildKind::REQUIRED, - 0, - 0, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_300 = {FRAME_CHILDREN_285, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_286[] = {{PEGRuleId::OtherOperatorTail, - TransformChildKind::OPTIONAL_REPEAT, - 1, - 1, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}, - {PEGRuleId::BitwiseExpression, - TransformChildKind::REQUIRED, - 0, - 0, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_301 = {FRAME_CHILDREN_286, 2, 2, true, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_287[] = {{PEGRuleId::SubqueryReference, - TransformChildKind::REQUIRED, - 1, - 1, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}, - {PEGRuleId::AnyAllParsedOperator, - TransformChildKind::REQUIRED, - 0, - 0, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_302 = {FRAME_CHILDREN_287, 2, 2, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_288[] = {{PEGRuleId::BitwiseExpression, - TransformChildKind::REQUIRED, - 1, - 1, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}, - {PEGRuleId::OtherOperator, - TransformChildKind::REQUIRED, - 0, - 0, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_303 = {FRAME_CHILDREN_288, 2, 2, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_289[] = {{PEGRuleId::SingleArrowBody, - TransformChildKind::REQUIRED, - 1, - 0, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_304 = {FRAME_CHILDREN_289, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_290[] = {{PEGRuleId::ArrowChainTail, - TransformChildKind::REPEAT, - 1, - 1, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}, - {PEGRuleId::BitwiseExpression, - TransformChildKind::REQUIRED, - 0, - 0, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_305 = {FRAME_CHILDREN_290, 2, 2, true, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_291[] = {{PEGRuleId::BitwiseExpression, - TransformChildKind::REQUIRED, - 1, - 0, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_306 = {FRAME_CHILDREN_291, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_292[] = {{PEGRuleId::AnyAllOperator, - TransformChildKind::REQUIRED, - 0, - 0, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_307 = {FRAME_CHILDREN_292, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_293[] = {{PEGRuleId::AnyOrAll, - TransformChildKind::REQUIRED, - 1, - 0, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_308 = {FRAME_CHILDREN_293, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_294[] = {{PEGRuleId::QualifiedOperatorContents, - TransformChildKind::REQUIRED, - 1, - 0, - false, - {1, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_309 = {FRAME_CHILDREN_294, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_295[] = {{PEGRuleId::ColIdDot, - TransformChildKind::OPTIONAL_REPEAT, - 0, - 0, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_310 = {FRAME_CHILDREN_295, 1, 1, true, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_296[] = {{PEGRuleId::BitwiseExpressionTail, - TransformChildKind::OPTIONAL_REPEAT, - 1, - 1, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}, - {PEGRuleId::TildeExpression, - TransformChildKind::REQUIRED, - 0, - 0, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_311 = {FRAME_CHILDREN_296, 2, 2, true, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_297[] = {{PEGRuleId::TildeExpression, - TransformChildKind::REQUIRED, - 1, - 1, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}, - {PEGRuleId::BitOperator, - TransformChildKind::REQUIRED, - 0, - 0, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_312 = {FRAME_CHILDREN_297, 2, 2, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_298[] = {{PEGRuleId::AdditiveExpression, - TransformChildKind::REQUIRED, - 1, - 1, - true, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}, - {PEGRuleId::TildePrefixOperator, - TransformChildKind::OPTIONAL_REPEAT, - 0, - 0, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_313 = {FRAME_CHILDREN_298, 2, 2, true, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_299[] = {{PEGRuleId::AdditiveExpressionTail, - TransformChildKind::OPTIONAL_REPEAT, - 1, - 1, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}, - {PEGRuleId::MultiplicativeExpression, - TransformChildKind::REQUIRED, - 0, - 0, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_314 = {FRAME_CHILDREN_299, 2, 2, true, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_300[] = {{PEGRuleId::MultiplicativeExpression, - TransformChildKind::REQUIRED, - 1, - 1, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}, - {PEGRuleId::Term, - TransformChildKind::REQUIRED, - 0, - 0, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_315 = {FRAME_CHILDREN_300, 2, 2, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_301[] = {{PEGRuleId::MultiplicativeExpressionTail, - TransformChildKind::OPTIONAL_REPEAT, - 1, - 1, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}, - {PEGRuleId::ExponentiationExpression, - TransformChildKind::REQUIRED, - 0, - 0, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_316 = {FRAME_CHILDREN_301, 2, 2, true, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_302[] = {{PEGRuleId::ExponentiationExpression, - TransformChildKind::REQUIRED, - 1, - 1, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}, - {PEGRuleId::Factor, - TransformChildKind::REQUIRED, - 0, - 0, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_317 = {FRAME_CHILDREN_302, 2, 2, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_303[] = {{PEGRuleId::ExponentiationExpressionTail, - TransformChildKind::OPTIONAL_REPEAT, - 1, - 1, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}, - {PEGRuleId::CollateExpression, - TransformChildKind::REQUIRED, - 0, - 0, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_318 = {FRAME_CHILDREN_303, 2, 2, true, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_304[] = {{PEGRuleId::CollateExpression, - TransformChildKind::REQUIRED, - 1, - 1, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}, - {PEGRuleId::ExponentOperator, - TransformChildKind::REQUIRED, - 0, - 0, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_319 = {FRAME_CHILDREN_304, 2, 2, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_305[] = {{PEGRuleId::CollateExpressionTail, - TransformChildKind::OPTIONAL_REPEAT, - 1, - 1, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}, - {PEGRuleId::AtTimeZoneExpression, - TransformChildKind::REQUIRED, - 0, - 0, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_320 = {FRAME_CHILDREN_305, 2, 2, true, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_306[] = {{PEGRuleId::AtTimeZoneExpression, - TransformChildKind::REQUIRED, - 1, - 0, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_321 = {FRAME_CHILDREN_306, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_307[] = {{PEGRuleId::AtTimeZoneExpressionTail, - TransformChildKind::OPTIONAL_REPEAT, - 1, - 1, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}, - {PEGRuleId::UnaryExpression, - TransformChildKind::REQUIRED, - 0, - 0, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_322 = {FRAME_CHILDREN_307, 2, 2, true, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_308[] = {{PEGRuleId::UnaryExpression, - TransformChildKind::REQUIRED, - 1, - 0, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_323 = {FRAME_CHILDREN_308, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_309[] = {{PEGRuleId::TildeExpression, - TransformChildKind::REQUIRED, - 1, - 0, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_324 = {FRAME_CHILDREN_309, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_310[] = {{PEGRuleId::IndirectionList, - TransformChildKind::OPTIONAL, - 1, - 1, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}, - {PEGRuleId::SingleExpression, - TransformChildKind::REQUIRED, - 0, - 0, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_325 = {FRAME_CHILDREN_310, 2, 2, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_311[] = {{PEGRuleId::Indirection, - TransformChildKind::REPEAT, - 0, - 0, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_326 = {FRAME_CHILDREN_311, 1, 1, true, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_312[] = {{PEGRuleId::MethodExpression, - TransformChildKind::REQUIRED, - 1, - 0, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_327 = {FRAME_CHILDREN_312, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_313[] = {{PEGRuleId::MethodExpressionArguments, - TransformChildKind::REQUIRED, - 1, - 1, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}, - {PEGRuleId::ColLabel, - TransformChildKind::REQUIRED, - 0, - 0, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_328 = {FRAME_CHILDREN_313, 2, 2, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_314[] = {{PEGRuleId::MethodExpressionArgumentList, - TransformChildKind::REQUIRED, - 0, - 0, - false, - {1, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_329 = {FRAME_CHILDREN_314, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_315[] = {{PEGRuleId::IgnoreOrRespectNulls, - TransformChildKind::OPTIONAL, - 3, - 3, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}, - {PEGRuleId::OrderByClause, - TransformChildKind::OPTIONAL, - 2, - 2, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}, - {PEGRuleId::MethodFunctionArguments, - TransformChildKind::OPTIONAL, - 1, - 1, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}, - {PEGRuleId::DistinctOrAll, - TransformChildKind::OPTIONAL, - 0, - 0, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_330 = {FRAME_CHILDREN_315, 4, 4, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_316[] = {{PEGRuleId::SliceBound, - TransformChildKind::REQUIRED, - 1, - 0, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_331 = {FRAME_CHILDREN_316, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_317[] = {{PEGRuleId::SliceUpperBound, - TransformChildKind::OPTIONAL, - 1, - 1, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}, - {PEGRuleId::Expression, - TransformChildKind::OPTIONAL, - 0, - 0, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_332 = {FRAME_CHILDREN_317, 2, 2, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_318[] = {{PEGRuleId::StepSliceBound, - TransformChildKind::REQUIRED, - 2, - 0, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_333 = {FRAME_CHILDREN_318, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_319[] = {{PEGRuleId::StepSliceBound, - TransformChildKind::OPTIONAL, - 1, - 1, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}, - {PEGRuleId::EndSliceBound, - TransformChildKind::REQUIRED, - 0, - 0, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_334 = {FRAME_CHILDREN_319, 2, 2, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_320[] = {{PEGRuleId::Expression, - TransformChildKind::LIST, - 1, - 0, - false, - {1, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_335 = {FRAME_CHILDREN_320, 1, 1, true, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_321[] = {{PEGRuleId::Expression, - TransformChildKind::REQUIRED, - 2, - 0, - false, - {1, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_336 = {FRAME_CHILDREN_321, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_322[] = {{PEGRuleId::ExtractArguments, - TransformChildKind::REQUIRED, - 1, - 0, - false, - {1, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_337 = {FRAME_CHILDREN_322, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_323[] = {{PEGRuleId::Expression, - TransformChildKind::REQUIRED, - 2, - 1, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}, - {PEGRuleId::ExtractArgument, - TransformChildKind::REQUIRED, - 0, - 0, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_338 = {FRAME_CHILDREN_323, 2, 2, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_324[] = {{PEGRuleId::Expression, - TransformChildKind::REQUIRED, - 3, - 1, - true, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}, - {PEGRuleId::ColIdOrString, - TransformChildKind::LIST, - 1, - 0, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_339 = {FRAME_CHILDREN_324, 2, 2, true, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_325[] = {{PEGRuleId::NullIfArguments, - TransformChildKind::REQUIRED, - 1, - 0, - false, - {1, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_340 = {FRAME_CHILDREN_325, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_326[] = {{PEGRuleId::PositionArguments, - TransformChildKind::REQUIRED, - 1, - 0, - false, - {1, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_341 = {FRAME_CHILDREN_326, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_327[] = {{PEGRuleId::Expression, - TransformChildKind::REQUIRED, - 2, - 1, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}, - {PEGRuleId::OtherOperatorExpression, - TransformChildKind::REQUIRED, - 0, - 0, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_342 = {FRAME_CHILDREN_327, 2, 2, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_328[] = {{PEGRuleId::Expression, - TransformChildKind::OPTIONAL_LIST, - 1, - 0, - false, - {1, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_343 = {FRAME_CHILDREN_328, 1, 1, true, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_329[] = {{PEGRuleId::SubstringArguments, - TransformChildKind::REQUIRED, - 1, - 0, - false, - {1, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_344 = {FRAME_CHILDREN_329, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_330[] = {{PEGRuleId::Expression, - TransformChildKind::LIST, - 0, - 0, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_345 = {FRAME_CHILDREN_330, 1, 1, true, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_331[] = {{PEGRuleId::SubstringFromFor, - TransformChildKind::REQUIRED, - 1, - 1, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}, - {PEGRuleId::Expression, - TransformChildKind::REQUIRED, - 0, - 0, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_346 = {FRAME_CHILDREN_331, 2, 2, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_332[] = {{PEGRuleId::ForExpression, - TransformChildKind::OPTIONAL, - 1, - 1, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}, - {PEGRuleId::FromExpression, - TransformChildKind::REQUIRED, - 0, - 0, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_347 = {FRAME_CHILDREN_332, 2, 2, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_333[] = {{PEGRuleId::ForExpression, - TransformChildKind::REQUIRED, - 0, - 0, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_348 = {FRAME_CHILDREN_333, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_334[] = {{PEGRuleId::TrimArguments, - TransformChildKind::REQUIRED, - 1, - 0, - false, - {1, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_349 = {FRAME_CHILDREN_334, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_335[] = {{PEGRuleId::Expression, - TransformChildKind::LIST, - 2, - 2, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}, - {PEGRuleId::TrimSource, - TransformChildKind::OPTIONAL, - 1, - 1, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}, - {PEGRuleId::TrimDirection, - TransformChildKind::OPTIONAL, - 0, - 0, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_350 = {FRAME_CHILDREN_335, 3, 3, true, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_336[] = {{PEGRuleId::Expression, - TransformChildKind::OPTIONAL, - 0, - 0, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_351 = {FRAME_CHILDREN_336, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_337[] = {{PEGRuleId::OverlayArguments, - TransformChildKind::REQUIRED, - 1, - 0, - false, - {1, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_352 = {FRAME_CHILDREN_337, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_338[] = {{PEGRuleId::ForExpression, - TransformChildKind::OPTIONAL, - 4, - 3, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}, - {PEGRuleId::FromExpression, - TransformChildKind::REQUIRED, - 3, - 2, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}, - {PEGRuleId::Expression, - TransformChildKind::REQUIRED, - 2, - 1, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}, - {PEGRuleId::Expression, - TransformChildKind::REQUIRED, - 0, - 0, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_353 = {FRAME_CHILDREN_338, 4, 4, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_339[] = {{PEGRuleId::ExtractDatePart, - TransformChildKind::REQUIRED, - 0, - 0, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_354 = {FRAME_CHILDREN_339, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_340[] = {{PEGRuleId::ExternalResourceCreationOptions, - TransformChildKind::OPTIONAL, - 4, - 2, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}, - {PEGRuleId::AttachAlias, - TransformChildKind::OPTIONAL, - 3, - 1, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}, - {PEGRuleId::ExternalResourceType, - TransformChildKind::REQUIRED, - 2, - 0, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_355 = {FRAME_CHILDREN_340, 3, 3, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_341[] = {{PEGRuleId::Expression, - TransformChildKind::REQUIRED, - 5, - 2, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}, - {PEGRuleId::AttachAlias, - TransformChildKind::OPTIONAL, - 3, - 1, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}, - {PEGRuleId::ExternalResourceType, - TransformChildKind::REQUIRED, - 2, - 0, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_356 = {FRAME_CHILDREN_341, 3, 3, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_342[] = {{PEGRuleId::ColId, - TransformChildKind::REQUIRED, - 2, - 0, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_357 = {FRAME_CHILDREN_342, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_343[] = {{PEGRuleId::BareName, - TransformChildKind::REQUIRED, - 0, - 0, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_358 = {FRAME_CHILDREN_343, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_344[] = {{PEGRuleId::AttachOptions, - TransformChildKind::OPTIONAL, - 4, - 2, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}, - {PEGRuleId::AttachAlias, - TransformChildKind::REQUIRED, - 3, - 1, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}, - {PEGRuleId::ExternalResourceSource, - TransformChildKind::REQUIRED, - 2, - 0, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_359 = {FRAME_CHILDREN_344, 3, 3, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_345[] = {{PEGRuleId::AttachOptions, - TransformChildKind::OPTIONAL, - 3, - 1, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}, - {PEGRuleId::ExternalResourceSource, - TransformChildKind::REQUIRED, - 2, - 0, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_360 = {FRAME_CHILDREN_345, 2, 2, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_346[] = {{PEGRuleId::ExternalResourceCreationOptions, - TransformChildKind::OPTIONAL, - 4, - 1, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}, - {PEGRuleId::ExternalResourceType, - TransformChildKind::REQUIRED, - 3, - 0, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_361 = {FRAME_CHILDREN_346, 2, 2, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_347[] = {{PEGRuleId::ReturningClause, - TransformChildKind::OPTIONAL, - 10, - 7, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}, - {PEGRuleId::OnConflictClause, - TransformChildKind::OPTIONAL, - 9, - 6, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}, - {PEGRuleId::InsertValues, - TransformChildKind::REQUIRED, - 8, - 5, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}, - {PEGRuleId::InsertColumnList, - TransformChildKind::OPTIONAL, - 6, - 4, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}, - {PEGRuleId::ByNameOrPosition, - TransformChildKind::OPTIONAL, - 5, - 3, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}, - {PEGRuleId::InsertTarget, - TransformChildKind::REQUIRED, - 4, - 2, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}, - {PEGRuleId::OrAction, - TransformChildKind::OPTIONAL, - 2, - 1, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}, - {PEGRuleId::WithClause, - TransformChildKind::OPTIONAL, - 0, - 0, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_362 = {FRAME_CHILDREN_347, 8, 8, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_348[] = {{PEGRuleId::InsertByName, - TransformChildKind::REQUIRED, - 1, - 0, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_363 = {FRAME_CHILDREN_348, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_349[] = {{PEGRuleId::InsertByPosition, - TransformChildKind::REQUIRED, - 1, - 0, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_364 = {FRAME_CHILDREN_349, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_350[] = {{PEGRuleId::InsertAlias, - TransformChildKind::OPTIONAL, - 1, - 1, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}, - {PEGRuleId::BaseTableName, - TransformChildKind::REQUIRED, - 0, - 0, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_365 = {FRAME_CHILDREN_350, 2, 2, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_351[] = {{PEGRuleId::OnConflictAction, - TransformChildKind::REQUIRED, - 3, - 1, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}, - {PEGRuleId::OnConflictTarget, - TransformChildKind::OPTIONAL, - 2, - 0, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_366 = {FRAME_CHILDREN_351, 2, 2, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_352[] = {{PEGRuleId::WhereClause, - TransformChildKind::OPTIONAL, - 1, - 1, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}, - {PEGRuleId::ColumnIdList, - TransformChildKind::REQUIRED, - 0, - 0, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_367 = {FRAME_CHILDREN_352, 2, 2, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_353[] = {{PEGRuleId::ConstraintName, - TransformChildKind::REQUIRED, - 2, - 0, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_368 = {FRAME_CHILDREN_353, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_354[] = {{PEGRuleId::WhereClause, - TransformChildKind::OPTIONAL, - 4, - 1, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}, - {PEGRuleId::UpdateSetClauseList, - TransformChildKind::REQUIRED, - 3, - 0, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_369 = {FRAME_CHILDREN_354, 2, 2, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_355[] = {{PEGRuleId::TargetList, - TransformChildKind::REQUIRED, - 1, - 0, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_370 = {FRAME_CHILDREN_355, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_356[] = {{PEGRuleId::ExtensionAlias, - TransformChildKind::OPTIONAL, - 3, - 2, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}, - {PEGRuleId::FromSource, - TransformChildKind::OPTIONAL, - 2, - 1, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}, - {PEGRuleId::ColIdOrString, - TransformChildKind::REQUIRED, - 1, - 0, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_371 = {FRAME_CHILDREN_356, 3, 3, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_357[] = {{PEGRuleId::VersionNumber, - TransformChildKind::OPTIONAL, - 5, - 3, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}, - {PEGRuleId::FromSource, - TransformChildKind::OPTIONAL, - 4, - 2, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}, - {PEGRuleId::IdentifierOrStringLiteral, - TransformChildKind::REQUIRED, - 3, - 1, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}, - {PEGRuleId::InstallAndLoad, - TransformChildKind::OPTIONAL, - 2, - 0, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_372 = {FRAME_CHILDREN_357, 4, 4, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_358[] = {{PEGRuleId::FromSourceName, - TransformChildKind::REQUIRED, - 1, - 0, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_373 = {FRAME_CHILDREN_358, 1, 1, false, 0, {}}; -static const char *const FRAME_NAMES_9[] = {"Identifier"}; -static const TransformFramePlan FRAME_PLAN_374 = {nullptr, - 0, - 1, - false, - 0, - {ParseResultTypeBit(ParseResultType::IDENTIFIER) | - ParseResultTypeBit(ParseResultType::KEYWORD) | - ParseResultTypeBit(ParseResultType::STRING), - 0, true, true, 1, FRAME_NAMES_9}}; -static const TransformChildPlan FRAME_CHILDREN_359[] = {{PEGRuleId::IdentifierOrStringLiteral, - TransformChildKind::REQUIRED, - 1, - 0, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_375 = {FRAME_CHILDREN_359, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_360[] = {{PEGRuleId::RepositoryPublicKey, - TransformChildKind::OPTIONAL, - 7, - 4, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}, - {PEGRuleId::RepositoryPrefix, - TransformChildKind::REQUIRED, - 6, - 3, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}, - {PEGRuleId::ExtensionRepositoryName, - TransformChildKind::REQUIRED, - 5, - 2, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}, - {PEGRuleId::IfNotExists, - TransformChildKind::OPTIONAL, - 4, - 1, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}, - {PEGRuleId::OrReplace, - TransformChildKind::OPTIONAL, - 1, - 0, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_376 = {FRAME_CHILDREN_360, 5, 5, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_361[] = {{PEGRuleId::ExtensionRepositoryName, - TransformChildKind::REQUIRED, - 5, - 2, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}, - {PEGRuleId::IfNotExists, - TransformChildKind::OPTIONAL, - 4, - 1, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}, - {PEGRuleId::OrReplace, - TransformChildKind::OPTIONAL, - 1, - 0, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_377 = {FRAME_CHILDREN_361, 3, 3, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_362[] = {{PEGRuleId::ExtensionRepositoryName, - TransformChildKind::REQUIRED, - 4, - 1, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}, - {PEGRuleId::IfExists, - TransformChildKind::OPTIONAL, - 3, - 0, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_378 = {FRAME_CHILDREN_362, 2, 2, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_363[] = {{PEGRuleId::TableAlias, - TransformChildKind::OPTIONAL, - 2, - 1, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}, - {PEGRuleId::MatchRecognizeBody, - TransformChildKind::REQUIRED, - 1, - 0, - false, - {1, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_379 = {FRAME_CHILDREN_363, 2, 2, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_364[] = {{PEGRuleId::MatchRecognizeClause, - TransformChildKind::REPEAT, - 0, - 0, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_380 = {FRAME_CHILDREN_364, 1, 1, true, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_365[] = {{PEGRuleId::WindowPartition, - TransformChildKind::REQUIRED, - 0, - 0, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_381 = {FRAME_CHILDREN_365, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_366[] = {{PEGRuleId::OrderByClause, - TransformChildKind::REQUIRED, - 0, - 0, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_382 = {FRAME_CHILDREN_366, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_367[] = {{PEGRuleId::MeasuresClause, - TransformChildKind::REQUIRED, - 0, - 0, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_383 = {FRAME_CHILDREN_367, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_368[] = {{PEGRuleId::RowsPerMatch, - TransformChildKind::REQUIRED, - 0, - 0, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_384 = {FRAME_CHILDREN_368, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_369[] = {{PEGRuleId::AfterMatchSkip, - TransformChildKind::REQUIRED, - 0, - 0, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_385 = {FRAME_CHILDREN_369, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_370[] = {{PEGRuleId::PatternClause, - TransformChildKind::REQUIRED, - 0, - 0, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_386 = {FRAME_CHILDREN_370, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_371[] = {{PEGRuleId::SubsetClause, - TransformChildKind::REQUIRED, - 0, - 0, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_387 = {FRAME_CHILDREN_371, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_372[] = {{PEGRuleId::DefineClause, - TransformChildKind::REQUIRED, - 0, - 0, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_388 = {FRAME_CHILDREN_372, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_373[] = {{PEGRuleId::MeasuresElement, - TransformChildKind::LIST, - 1, - 0, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_389 = {FRAME_CHILDREN_373, 1, 1, true, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_374[] = {{PEGRuleId::ColLabelOrString, - TransformChildKind::REQUIRED, - 2, - 1, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}, - {PEGRuleId::Expression, - TransformChildKind::REQUIRED, - 0, - 0, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_390 = {FRAME_CHILDREN_374, 2, 2, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_375[] = {{PEGRuleId::AllRowsEmptyMatches, - TransformChildKind::OPTIONAL, - 4, - 0, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_391 = {FRAME_CHILDREN_375, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_376[] = {{PEGRuleId::AfterMatchSkipTarget, - TransformChildKind::REQUIRED, - 3, - 0, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_392 = {FRAME_CHILDREN_376, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_377[] = {{PEGRuleId::ColLabelOrString, - TransformChildKind::REQUIRED, - 2, - 0, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_393 = {FRAME_CHILDREN_377, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_378[] = {{PEGRuleId::ColLabelOrString, - TransformChildKind::REQUIRED, - 1, - 0, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_394 = {FRAME_CHILDREN_378, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_379[] = {{PEGRuleId::RowPattern, - TransformChildKind::REQUIRED, - 1, - 0, - false, - {1, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_395 = {FRAME_CHILDREN_379, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_380[] = {{PEGRuleId::RowPatternAlternative, - TransformChildKind::OPTIONAL_REPEAT, - 1, - 1, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}, - {PEGRuleId::RowPatternTerm, - TransformChildKind::REQUIRED, - 0, - 0, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_396 = {FRAME_CHILDREN_380, 2, 2, true, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_381[] = {{PEGRuleId::RowPatternTerm, - TransformChildKind::REQUIRED, - 1, - 0, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_397 = {FRAME_CHILDREN_381, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_382[] = {{PEGRuleId::RowPatternFactor, - TransformChildKind::REPEAT, - 0, - 0, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_398 = {FRAME_CHILDREN_382, 1, 1, true, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_383[] = {{PEGRuleId::RowPatternQuantifier, - TransformChildKind::OPTIONAL, - 1, - 1, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}, - {PEGRuleId::RowPatternPrimary, - TransformChildKind::REQUIRED, - 0, - 0, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_399 = {FRAME_CHILDREN_383, 2, 2, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_384[] = {{PEGRuleId::RowPattern, - TransformChildKind::LIST, - 1, - 0, - false, - {1, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_400 = {FRAME_CHILDREN_384, 1, 1, true, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_385[] = {{PEGRuleId::RowPattern, - TransformChildKind::REQUIRED, - 0, - 0, - false, - {1, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_401 = {FRAME_CHILDREN_385, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_386[] = {{PEGRuleId::RowPattern, - TransformChildKind::REQUIRED, - 2, - 0, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_402 = {FRAME_CHILDREN_386, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_387[] = {{PEGRuleId::ColLabelOrString, - TransformChildKind::REQUIRED, - 0, - 0, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_403 = {FRAME_CHILDREN_387, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_388[] = {{PEGRuleId::QuantifierReluctant, - TransformChildKind::OPTIONAL, - 1, - 1, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}, - {PEGRuleId::RowPatternQuantifierKind, - TransformChildKind::REQUIRED, - 0, - 0, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_404 = {FRAME_CHILDREN_388, 2, 2, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_389[] = {{PEGRuleId::QuantifierBounds, - TransformChildKind::REQUIRED, - 1, - 0, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_405 = {FRAME_CHILDREN_389, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_390[] = {{PEGRuleId::SubsetElement, - TransformChildKind::LIST, - 1, - 0, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_406 = {FRAME_CHILDREN_390, 1, 1, true, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_391[] = {{PEGRuleId::ColLabelOrString, - TransformChildKind::LIST, - 2, - 1, - false, - {1, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}, - {PEGRuleId::ColLabelOrString, - TransformChildKind::REQUIRED, - 0, - 0, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_407 = {FRAME_CHILDREN_391, 2, 2, true, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_392[] = {{PEGRuleId::DefineElement, - TransformChildKind::LIST, - 1, - 0, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_408 = {FRAME_CHILDREN_392, 1, 1, true, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_393[] = {{PEGRuleId::Expression, - TransformChildKind::REQUIRED, - 2, - 1, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}, - {PEGRuleId::ColLabelOrString, - TransformChildKind::REQUIRED, - 0, - 0, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_409 = {FRAME_CHILDREN_393, 2, 2, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_394[] = {{PEGRuleId::ReturningClause, - TransformChildKind::OPTIONAL, - 7, - 5, - true, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}, - {PEGRuleId::MergeMatch, - TransformChildKind::REPEAT, - 6, - 4, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}, - {PEGRuleId::JoinQualifier, - TransformChildKind::REQUIRED, - 5, - 3, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}, - {PEGRuleId::MergeIntoUsingClause, - TransformChildKind::REQUIRED, - 4, - 2, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}, - {PEGRuleId::TargetOptAlias, - TransformChildKind::REQUIRED, - 3, - 1, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}, - {PEGRuleId::WithClause, - TransformChildKind::OPTIONAL, - 0, - 0, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_410 = {FRAME_CHILDREN_394, 6, 6, true, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_395[] = {{PEGRuleId::TableRef, - TransformChildKind::REQUIRED, - 1, - 0, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_411 = {FRAME_CHILDREN_395, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_396[] = {{PEGRuleId::MatchedClauseAction, - TransformChildKind::REQUIRED, - 4, - 1, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}, - {PEGRuleId::AndExpression, - TransformChildKind::OPTIONAL, - 2, - 0, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_412 = {FRAME_CHILDREN_396, 2, 2, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_397[] = {{PEGRuleId::UpdateMatchInfo, - TransformChildKind::OPTIONAL, - 1, - 0, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_413 = {FRAME_CHILDREN_397, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_398[] = {{PEGRuleId::UpdateMatchSetClause, - TransformChildKind::REQUIRED, - 0, - 0, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_414 = {FRAME_CHILDREN_398, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_399[] = {{PEGRuleId::ByNameOrPosition, - TransformChildKind::REQUIRED, - 0, - 0, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_415 = {FRAME_CHILDREN_399, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_400[] = {{PEGRuleId::InsertMatchInfo, - TransformChildKind::OPTIONAL, - 1, - 0, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_416 = {FRAME_CHILDREN_400, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_401[] = {{PEGRuleId::ByNameOrPosition, - TransformChildKind::OPTIONAL, - 0, - 0, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_417 = {FRAME_CHILDREN_401, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_402[] = {{PEGRuleId::Expression, - TransformChildKind::LIST, - 2, - 1, - false, - {1, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}, - {PEGRuleId::InsertColumnList, - TransformChildKind::OPTIONAL, - 0, - 0, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_418 = {FRAME_CHILDREN_402, 2, 2, true, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_403[] = {{PEGRuleId::UpdateMatchSetInfo, - TransformChildKind::REQUIRED, - 1, - 0, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_419 = {FRAME_CHILDREN_403, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_404[] = {{PEGRuleId::MatchedClauseAction, - TransformChildKind::REQUIRED, - 6, - 2, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}, - {PEGRuleId::AndExpression, - TransformChildKind::OPTIONAL, - 4, - 1, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}, - {PEGRuleId::BySourceOrTarget, - TransformChildKind::OPTIONAL, - 3, - 0, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_420 = {FRAME_CHILDREN_404, 3, 3, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_405[] = {{PEGRuleId::PivotColumnList, - TransformChildKind::REQUIRED, - 1, - 0, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_421 = {FRAME_CHILDREN_405, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_406[] = {{PEGRuleId::PivotColumnEntry, - TransformChildKind::LIST, - 0, - 0, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_422 = {FRAME_CHILDREN_406, 1, 1, true, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_407[] = {{PEGRuleId::SelectStatementInternal, - TransformChildKind::REQUIRED, - 2, - 1, - false, - {1, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}, - {PEGRuleId::BaseExpression, - TransformChildKind::REQUIRED, - 0, - 0, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_423 = {FRAME_CHILDREN_407, 2, 2, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_408[] = {{PEGRuleId::OptionalParensNameList, - TransformChildKind::REQUIRED, - 4, - 1, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}, - {PEGRuleId::ColIdOrString, - TransformChildKind::REQUIRED, - 2, - 0, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_424 = {FRAME_CHILDREN_408, 2, 2, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_409[] = {{PEGRuleId::ColIdOrString, - TransformChildKind::LIST, - 0, - 0, - false, - {1, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_425 = {FRAME_CHILDREN_409, 1, 1, true, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_410[] = {{PEGRuleId::ColIdOrString, - TransformChildKind::LIST, - 0, - 0, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_426 = {FRAME_CHILDREN_410, 1, 1, true, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_411[] = {{PEGRuleId::PragmaAssignOrFunction, - TransformChildKind::REQUIRED, - 1, - 0, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_427 = {FRAME_CHILDREN_411, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_412[] = {{PEGRuleId::VariableList, - TransformChildKind::REQUIRED, - 2, - 0, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_428 = {FRAME_CHILDREN_412, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_413[] = {{PEGRuleId::PragmaParameters, - TransformChildKind::OPTIONAL, - 1, - 0, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_429 = {FRAME_CHILDREN_413, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_414[] = {{PEGRuleId::Statement, - TransformChildKind::REQUIRED, - 4, - 2, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}, - {PEGRuleId::TypeList, - TransformChildKind::OPTIONAL, - 2, - 1, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}, - {PEGRuleId::ColIdOrString, - TransformChildKind::REQUIRED, - 1, - 0, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_430 = {FRAME_CHILDREN_414, 3, 3, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_415[] = { +static const TransformFramePlan FRAME_PLAN_ColumnList = {FRAME_CHILDREN_ColumnList, 1, 1, true, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_CreateTypeStmt[] = {{PEGRuleId::CreateType, + TransformChildKind::REQUIRED, + 4, + 2, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::QualifiedName, + TransformChildKind::REQUIRED, + 2, + 1, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::IfNotExists, + TransformChildKind::OPTIONAL, + 1, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_CreateTypeStmt = {FRAME_CHILDREN_CreateTypeStmt, 3, 3, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_CreateTypeFromType[] = {{PEGRuleId::Type, + TransformChildKind::REQUIRED, + 0, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_CreateTypeFromType = {FRAME_CHILDREN_CreateTypeFromType, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_ArrayParensSelect[] = {{PEGRuleId::SelectStatementInternal, + TransformChildKind::REQUIRED, + 1, + 0, + false, + {1, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_ArrayParensSelect = {FRAME_CHILDREN_ArrayParensSelect, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_EnumStringLiteralList[] = {{PEGRuleId::ArrayBounds, + TransformChildKind::OPTIONAL_REPEAT, + 2, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_EnumStringLiteralList = { + FRAME_CHILDREN_EnumStringLiteralList, 1, 1, true, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_CreateViewStmt[] = {{PEGRuleId::SelectStatementInternal, + TransformChildKind::REQUIRED, + 8, + 6, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::WithList, + TransformChildKind::OPTIONAL, + 6, + 5, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::InsertColumnList, + TransformChildKind::OPTIONAL, + 5, + 4, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::QualifiedName, + TransformChildKind::REQUIRED, + 4, + 3, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::IfNotExists, + TransformChildKind::OPTIONAL, + 3, + 2, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::CreateRecursive, + TransformChildKind::OPTIONAL, + 1, + 1, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::CreateSecure, + TransformChildKind::OPTIONAL, + 0, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_CreateViewStmt = {FRAME_CHILDREN_CreateViewStmt, 7, 7, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_DeallocateStatement[] = {{PEGRuleId::ColIdOrString, + TransformChildKind::REQUIRED, + 2, + 1, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::DeallocatePrepare, + TransformChildKind::OPTIONAL, + 1, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_DeallocateStatement = { + FRAME_CHILDREN_DeallocateStatement, 2, 2, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_DeleteStatement[] = {{PEGRuleId::ReturningClause, + TransformChildKind::OPTIONAL, + 6, + 4, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::WhereClause, + TransformChildKind::OPTIONAL, + 5, + 3, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::DeleteUsingClause, + TransformChildKind::OPTIONAL, + 4, + 2, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::TargetOptAlias, + TransformChildKind::REQUIRED, + 3, + 1, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::WithClause, + TransformChildKind::OPTIONAL, + 0, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_DeleteStatement = {FRAME_CHILDREN_DeleteStatement, 5, 5, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_TruncateStatement[] = {{PEGRuleId::TruncateOptions, + TransformChildKind::OPTIONAL, + 3, + 1, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::BaseTableName, + TransformChildKind::REQUIRED, + 2, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_TruncateStatement = {FRAME_CHILDREN_TruncateStatement, 2, 2, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_TruncateAliasOptions[] = {{PEGRuleId::TruncateDropBehavior, + TransformChildKind::OPTIONAL, + 1, + 1, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::TargetAlias, + TransformChildKind::REQUIRED, + 0, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_TruncateAliasOptions = { + FRAME_CHILDREN_TruncateAliasOptions, 2, 2, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_TruncateDropBehavior[] = {{PEGRuleId::DropBehavior, + TransformChildKind::REQUIRED, + 0, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_TruncateDropBehavior = { + FRAME_CHILDREN_TruncateDropBehavior, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_TargetOptAlias[] = {{PEGRuleId::TargetAlias, + TransformChildKind::OPTIONAL, + 1, + 1, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::BaseTableName, + TransformChildKind::REQUIRED, + 0, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_TargetOptAlias = {FRAME_CHILDREN_TargetOptAlias, 2, 2, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_DeleteUsingClause[] = {{PEGRuleId::TableRef, + TransformChildKind::LIST, + 1, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_DeleteUsingClause = {FRAME_CHILDREN_DeleteUsingClause, 1, 1, true, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_ShowExternalResources[] = {{PEGRuleId::ShowExternalResourcesType, + TransformChildKind::OPTIONAL, + 4, + 1, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::ShowRule, + TransformChildKind::REQUIRED, + 0, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_ShowExternalResources = { + FRAME_CHILDREN_ShowExternalResources, 2, 2, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_ShowExternalResourcesType[] = {{PEGRuleId::ExternalResourceType, + TransformChildKind::REQUIRED, + 2, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_ShowExternalResourcesType = { + FRAME_CHILDREN_ShowExternalResourcesType, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_ShowExternalResourceTypes[] = {{PEGRuleId::ShowRule, + TransformChildKind::REQUIRED, + 0, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_ShowExternalResourceTypes = { + FRAME_CHILDREN_ShowExternalResourceTypes, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_ShowDeprecatedSelect[] = {{PEGRuleId::SelectStatementInternal, + TransformChildKind::REQUIRED, + 1, + 1, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::ShowRule, + TransformChildKind::REQUIRED, + 0, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_ShowDeprecatedSelect = { + FRAME_CHILDREN_ShowDeprecatedSelect, 2, 2, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_DescribeSelect[] = {{PEGRuleId::SelectStatementInternal, + TransformChildKind::REQUIRED, + 1, + 1, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::DescribeOrSummarize, + TransformChildKind::REQUIRED, + 0, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_DescribeSelect = {FRAME_CHILDREN_DescribeSelect, 2, 2, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_ShowAllTables[] = {{PEGRuleId::ShowOrDescribe, + TransformChildKind::REQUIRED, + 0, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_ShowAllTables = {FRAME_CHILDREN_ShowAllTables, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_ShowTables[] = {{PEGRuleId::QualifiedName, + TransformChildKind::REQUIRED, + 3, + 1, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::ShowOrDescribe, + TransformChildKind::REQUIRED, + 0, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_ShowTables = {FRAME_CHILDREN_ShowTables, 2, 2, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_ShowByName[] = {{PEGRuleId::ShowTarget, + TransformChildKind::OPTIONAL, + 1, + 1, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::ShowRule, + TransformChildKind::REQUIRED, + 0, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_ShowByName = {FRAME_CHILDREN_ShowByName, 2, 2, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_DescribeByName[] = {{PEGRuleId::DescribeTarget, + TransformChildKind::OPTIONAL, + 1, + 1, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::DescribeOrSummarize, + TransformChildKind::REQUIRED, + 0, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_DescribeByName = {FRAME_CHILDREN_DescribeByName, 2, 2, false, 0, {}}; +static const char *const FRAME_NAMES_ShowTarget[] = {"ShowSpecialForm"}; +static const TransformFramePlan FRAME_PLAN_ShowTarget = {nullptr, 0, 1, + false, 0, {0, 0, false, true, 1, FRAME_NAMES_ShowTarget}}; +static const TransformChildPlan FRAME_CHILDREN_ShowDeprecatedQualifiedTableName[] = {{PEGRuleId::QualifiedTableName, + TransformChildKind::REQUIRED, + 0, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_ShowDeprecatedQualifiedTableName = { + FRAME_CHILDREN_ShowDeprecatedQualifiedTableName, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_BaseTableSet[] = {{PEGRuleId::BaseTableName, + TransformChildKind::REQUIRED, + 0, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_BaseTableSet = {FRAME_CHILDREN_BaseTableSet, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_Summarize[] = {{PEGRuleId::SummarizeRule, + TransformChildKind::REQUIRED, + 0, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_Summarize = {FRAME_CHILDREN_Summarize, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_DetachStatement[] = {{PEGRuleId::IfExists, + TransformChildKind::OPTIONAL, + 2, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_DetachStatement = {FRAME_CHILDREN_DetachStatement, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_DropStatement[] = {{PEGRuleId::DropBehavior, + TransformChildKind::OPTIONAL, + 2, + 1, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::DropEntries, + TransformChildKind::REQUIRED, + 1, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_DropStatement = {FRAME_CHILDREN_DropStatement, 2, 2, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_DropMemberStatement[] = {{PEGRuleId::DropBehavior, + TransformChildKind::OPTIONAL, + 2, + 1, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::DropMember, + TransformChildKind::REQUIRED, + 1, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_DropMemberStatement = { + FRAME_CHILDREN_DropMemberStatement, 2, 2, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_DropTableFunctionMember[] = {{PEGRuleId::DropFunctionSignature, + TransformChildKind::REQUIRED, + 3, + 3, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::QualifiedTableFunction, + TransformChildKind::REQUIRED, + 2, + 2, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::IfExists, + TransformChildKind::OPTIONAL, + 1, + 1, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::CommentMacroTable, + TransformChildKind::REQUIRED, + 0, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_DropTableFunctionMember = { + FRAME_CHILDREN_DropTableFunctionMember, 4, 4, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_DropFunctionMember[] = {{PEGRuleId::DropFunctionSignature, + TransformChildKind::REQUIRED, + 3, + 3, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::FunctionIdentifier, + TransformChildKind::REQUIRED, + 2, + 2, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::IfExists, + TransformChildKind::OPTIONAL, + 1, + 1, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::FunctionTypeMacro, + TransformChildKind::REQUIRED, + 0, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_DropFunctionMember = {FRAME_CHILDREN_DropFunctionMember, 4, 4, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_DropTrigger[] = {{PEGRuleId::BaseTableName, + TransformChildKind::REQUIRED, + 4, + 2, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::TriggerName, + TransformChildKind::REQUIRED, + 2, + 1, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::IfExists, + TransformChildKind::OPTIONAL, + 1, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_DropTrigger = {FRAME_CHILDREN_DropTrigger, 3, 3, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_DropTable[] = {{PEGRuleId::BaseTableName, + TransformChildKind::LIST, + 2, + 2, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::IfExists, + TransformChildKind::OPTIONAL, + 1, + 1, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::TableOrView, + TransformChildKind::REQUIRED, + 0, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_DropTable = {FRAME_CHILDREN_DropTable, 3, 3, true, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_DropTableFunction[] = {{PEGRuleId::QualifiedTableFunction, + TransformChildKind::LIST, + 2, + 2, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::IfExists, + TransformChildKind::OPTIONAL, + 1, + 1, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::CommentMacroTable, + TransformChildKind::REQUIRED, + 0, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_DropTableFunction = {FRAME_CHILDREN_DropTableFunction, 3, 3, true, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_DropFunction[] = {{PEGRuleId::FunctionIdentifier, + TransformChildKind::LIST, + 2, + 2, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::IfExists, + TransformChildKind::OPTIONAL, + 1, + 1, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::FunctionTypeMacro, + TransformChildKind::REQUIRED, + 0, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_DropFunction = {FRAME_CHILDREN_DropFunction, 3, 3, true, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_DropFunctionSignature[] = {{PEGRuleId::DropSignatureType, + TransformChildKind::OPTIONAL_LIST, + 0, + 0, + false, + {1, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_DropFunctionSignature = { + FRAME_CHILDREN_DropFunctionSignature, 1, 1, true, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_DropSchema[] = {{PEGRuleId::QualifiedName, + TransformChildKind::LIST, + 2, + 1, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::IfExists, + TransformChildKind::OPTIONAL, + 1, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_DropSchema = {FRAME_CHILDREN_DropSchema, 2, 2, true, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_DropIndex[] = {{PEGRuleId::QualifiedIndexName, + TransformChildKind::LIST, + 2, + 1, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::IfExists, + TransformChildKind::OPTIONAL, + 1, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_DropIndex = {FRAME_CHILDREN_DropIndex, 2, 2, true, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_DropSequence[] = {{PEGRuleId::QualifiedSequenceName, + TransformChildKind::LIST, + 2, + 1, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::IfExists, + TransformChildKind::OPTIONAL, + 1, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_DropSequence = {FRAME_CHILDREN_DropSequence, 2, 2, true, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_DropCollation[] = {{PEGRuleId::CollationName, + TransformChildKind::LIST, + 2, + 1, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::IfExists, + TransformChildKind::OPTIONAL, + 1, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_DropCollation = {FRAME_CHILDREN_DropCollation, 2, 2, true, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_DropType[] = {{PEGRuleId::QualifiedTypeName, + TransformChildKind::LIST, + 2, + 1, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::IfExists, + TransformChildKind::OPTIONAL, + 1, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_DropType = {FRAME_CHILDREN_DropType, 2, 2, true, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_DropSecret[] = {{PEGRuleId::DropSecretStorage, + TransformChildKind::OPTIONAL, + 4, + 3, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::SecretName, + TransformChildKind::REQUIRED, + 3, + 2, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::IfExists, + TransformChildKind::OPTIONAL, + 2, + 1, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::Temporary, + TransformChildKind::OPTIONAL, + 0, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_DropSecret = {FRAME_CHILDREN_DropSecret, 4, 4, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_ExecuteStatement[] = {{PEGRuleId::TableFunctionArguments, + TransformChildKind::OPTIONAL, + 2, + 1, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::ColIdOrString, + TransformChildKind::REQUIRED, + 1, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_ExecuteStatement = {FRAME_CHILDREN_ExecuteStatement, 2, 2, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_ExplainStatement[] = {{PEGRuleId::ExplainableStatements, + TransformChildKind::REQUIRED, + 3, + 2, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::ExplainOptionList, + TransformChildKind::OPTIONAL, + 2, + 1, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::AnalyzeKeyword, + TransformChildKind::OPTIONAL, + 1, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_ExplainStatement = {FRAME_CHILDREN_ExplainStatement, 3, 3, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_ExplainOptionList[] = {{PEGRuleId::ExplainOption, + TransformChildKind::LIST, + 0, + 0, + false, + {1, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_ExplainOptionList = {FRAME_CHILDREN_ExplainOptionList, 1, 1, true, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_ExplainOption[] = {{PEGRuleId::Expression, + TransformChildKind::OPTIONAL, + 1, + 1, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::ExplainOptionName, + TransformChildKind::REQUIRED, + 0, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_ExplainOption = {FRAME_CHILDREN_ExplainOption, 2, 2, false, 0, {}}; +static const char *const FRAME_NAMES_ExplainOptionName[] = {"FuncNameKeyword", "TypeNameKeyword"}; +static const TransformFramePlan FRAME_PLAN_ExplainOptionName = {nullptr, + 0, + 1, + false, + 0, + {ParseResultTypeBit(ParseResultType::IDENTIFIER) | + ParseResultTypeBit(ParseResultType::KEYWORD) | + ParseResultTypeBit(ParseResultType::STRING), + 0, true, false, 2, FRAME_NAMES_ExplainOptionName}}; +static const TransformChildPlan FRAME_CHILDREN_ExplainSelectStatement[] = {{PEGRuleId::SelectStatementInternal, + TransformChildKind::REQUIRED, + 0, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_ExplainSelectStatement = { + FRAME_CHILDREN_ExplainSelectStatement, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_ExportStatement[] = {{PEGRuleId::ExportOptions, + TransformChildKind::OPTIONAL, + 4, + 1, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::ExportSource, + TransformChildKind::OPTIONAL, + 2, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_ExportStatement = {FRAME_CHILDREN_ExportStatement, 2, 2, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_NestedSchemaTableColumnName[] = {{PEGRuleId::ReservedSchemaQualification, + TransformChildKind::REPEAT, + 3, + 3, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::ReservedSchemaQualification, + TransformChildKind::REQUIRED, + 2, + 2, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::ReservedSchemaQualification, + TransformChildKind::REQUIRED, + 1, + 1, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::CatalogQualification, + TransformChildKind::REQUIRED, + 0, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_NestedSchemaTableColumnName = { + FRAME_CHILDREN_NestedSchemaTableColumnName, 4, 4, true, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_CatalogReservedSchemaTableColumnName[] = { + {PEGRuleId::ReservedTableQualification, + TransformChildKind::REQUIRED, + 2, + 2, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::ReservedSchemaQualification, + TransformChildKind::REQUIRED, + 1, + 1, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::CatalogQualification, + TransformChildKind::REQUIRED, + 0, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_CatalogReservedSchemaTableColumnName = { + FRAME_CHILDREN_CatalogReservedSchemaTableColumnName, 3, 3, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_SchemaReservedTableColumnName[] = { + {PEGRuleId::ReservedTableQualification, + TransformChildKind::REQUIRED, + 1, + 1, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::SchemaQualification, + TransformChildKind::REQUIRED, + 0, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_SchemaReservedTableColumnName = { + FRAME_CHILDREN_SchemaReservedTableColumnName, 2, 2, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_TableReservedColumnName[] = {{PEGRuleId::TableQualification, + TransformChildKind::REQUIRED, + 0, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_TableReservedColumnName = { + FRAME_CHILDREN_TableReservedColumnName, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_FunctionExpression[] = {{PEGRuleId::OverClause, + TransformChildKind::OPTIONAL, + 5, + 4, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::FilterClause, + TransformChildKind::OPTIONAL, + 3, + 3, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::WithinGroupClause, + TransformChildKind::OPTIONAL, + 2, + 2, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::FunctionExpressionArguments, + TransformChildKind::REQUIRED, + 1, + 1, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::FunctionIdentifier, + TransformChildKind::REQUIRED, + 0, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_FunctionExpression = {FRAME_CHILDREN_FunctionExpression, 5, 5, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_FunctionExpressionArguments[] = { + {PEGRuleId::FunctionExpressionArgumentList, + TransformChildKind::REQUIRED, + 0, + 0, + false, + {1, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_FunctionExpressionArguments = { + FRAME_CHILDREN_FunctionExpressionArguments, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_FunctionExpressionArgumentList[] = {{PEGRuleId::IgnoreOrRespectNulls, + TransformChildKind::OPTIONAL, + 3, + 3, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::OrderByClause, + TransformChildKind::OPTIONAL, + 2, + 2, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::FunctionArgumentList, + TransformChildKind::OPTIONAL, + 1, + 1, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::DistinctOrAll, + TransformChildKind::OPTIONAL, + 0, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_FunctionExpressionArgumentList = { + FRAME_CHILDREN_FunctionExpressionArgumentList, 4, 4, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_FunctionArgumentList[] = {{PEGRuleId::FunctionArgument, + TransformChildKind::LIST, + 0, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_FunctionArgumentList = { + FRAME_CHILDREN_FunctionArgumentList, 1, 1, true, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_CatalogReservedSchemaFunctionName[] = { + {PEGRuleId::ReservedSchemaQualification, + TransformChildKind::OPTIONAL_REPEAT, + 1, + 1, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::CatalogQualification, + TransformChildKind::REQUIRED, + 0, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_CatalogReservedSchemaFunctionName = { + FRAME_CHILDREN_CatalogReservedSchemaFunctionName, 2, 2, true, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_WithinGroupClause[] = {{PEGRuleId::OrderByClause, + TransformChildKind::REQUIRED, + 2, + 0, + false, + {1, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_WithinGroupClause = {FRAME_CHILDREN_WithinGroupClause, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_FilterClause[] = {{PEGRuleId::FilterClauseExpression, + TransformChildKind::REQUIRED, + 1, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_FilterClause = {FRAME_CHILDREN_FilterClause, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_FilterClauseExpression[] = {{PEGRuleId::FilterClauseContents, + TransformChildKind::REQUIRED, + 0, + 0, + false, + {1, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_FilterClauseExpression = { + FRAME_CHILDREN_FilterClauseExpression, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_CastExpression[] = {{PEGRuleId::CastArguments, + TransformChildKind::REQUIRED, + 1, + 1, + false, + {1, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::CastOrTryCast, + TransformChildKind::REQUIRED, + 0, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_CastExpression = {FRAME_CHILDREN_CastExpression, 2, 2, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_CastArguments[] = {{PEGRuleId::Type, + TransformChildKind::REQUIRED, + 2, + 1, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::Expression, + TransformChildKind::REQUIRED, + 0, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_CastArguments = {FRAME_CHILDREN_CastArguments, 2, 2, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_StarExpression[] = {{PEGRuleId::RenameList, + TransformChildKind::OPTIONAL, + 4, + 3, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::ReplaceList, + TransformChildKind::OPTIONAL, + 3, + 2, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::ExcludeList, + TransformChildKind::OPTIONAL, + 2, + 1, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::StarQualifierList, + TransformChildKind::OPTIONAL, + 0, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_StarExpression = {FRAME_CHILDREN_StarExpression, 4, 4, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_StarQualifierList[] = {{PEGRuleId::ColIdDot, + TransformChildKind::REPEAT, + 0, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_StarQualifierList = {FRAME_CHILDREN_StarQualifierList, 1, 1, true, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_ExcludeList[] = {{PEGRuleId::ExcludeNames, + TransformChildKind::REQUIRED, + 1, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_ExcludeList = {FRAME_CHILDREN_ExcludeList, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_ExcludeNameList[] = {{PEGRuleId::ExcludeName, + TransformChildKind::LIST, + 0, + 0, + false, + {1, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_ExcludeNameList = {FRAME_CHILDREN_ExcludeNameList, 1, 1, true, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_ExcludeNameSingle[] = {{PEGRuleId::ExcludeName, + TransformChildKind::REQUIRED, + 0, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_ExcludeNameSingle = {FRAME_CHILDREN_ExcludeNameSingle, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_ExcludeDottedName[] = {{PEGRuleId::DottedIdentifier, + TransformChildKind::REQUIRED, + 0, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_ExcludeDottedName = {FRAME_CHILDREN_ExcludeDottedName, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_ReplaceList[] = {{PEGRuleId::ReplaceEntries, + TransformChildKind::REQUIRED, + 1, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_ReplaceList = {FRAME_CHILDREN_ReplaceList, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_ReplaceEntrySingle[] = {{PEGRuleId::ReplaceEntry, + TransformChildKind::REQUIRED, + 0, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_ReplaceEntrySingle = {FRAME_CHILDREN_ReplaceEntrySingle, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_ReplaceEntryList[] = {{PEGRuleId::ReplaceEntry, + TransformChildKind::LIST, + 0, + 0, + false, + {1, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_ReplaceEntryList = {FRAME_CHILDREN_ReplaceEntryList, 1, 1, true, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_ReplaceEntry[] = {{PEGRuleId::ColumnReference, + TransformChildKind::REQUIRED, + 2, + 1, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::Expression, + TransformChildKind::REQUIRED, + 0, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_ReplaceEntry = {FRAME_CHILDREN_ReplaceEntry, 2, 2, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_RenameList[] = {{PEGRuleId::RenameEntries, + TransformChildKind::REQUIRED, + 1, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_RenameList = {FRAME_CHILDREN_RenameList, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_RenameEntryList[] = {{PEGRuleId::RenameEntry, + TransformChildKind::LIST, + 0, + 0, + false, + {1, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_RenameEntryList = {FRAME_CHILDREN_RenameEntryList, 1, 1, true, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_SingleRenameEntry[] = {{PEGRuleId::RenameEntry, + TransformChildKind::REQUIRED, + 0, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_SingleRenameEntry = {FRAME_CHILDREN_SingleRenameEntry, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_SubqueryExpression[] = {{PEGRuleId::SubqueryReference, + TransformChildKind::REQUIRED, + 2, + 2, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::SubqueryExists, + TransformChildKind::OPTIONAL, + 1, + 1, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::SubqueryNot, + TransformChildKind::OPTIONAL, + 0, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_SubqueryExpression = {FRAME_CHILDREN_SubqueryExpression, 3, 3, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_SimpleCaseExpression[] = {{PEGRuleId::CaseElse, + TransformChildKind::OPTIONAL, + 3, + 2, + true, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::SimpleCaseWhenThen, + TransformChildKind::REPEAT, + 2, + 1, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::Expression, + TransformChildKind::REQUIRED, + 1, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_SimpleCaseExpression = { + FRAME_CHILDREN_SimpleCaseExpression, 3, 3, true, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_SearchedCaseExpression[] = {{PEGRuleId::CaseElse, + TransformChildKind::OPTIONAL, + 2, + 1, + true, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::CaseWhenThen, + TransformChildKind::REPEAT, + 1, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_SearchedCaseExpression = { + FRAME_CHILDREN_SearchedCaseExpression, 2, 2, true, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_SimpleCaseWhenThen[] = {{PEGRuleId::Expression, + TransformChildKind::REQUIRED, + 3, + 1, + true, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::SimpleCaseWhenOperand, + TransformChildKind::LIST, + 1, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_SimpleCaseWhenThen = {FRAME_CHILDREN_SimpleCaseWhenThen, 2, 2, true, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_CaseWhenThen[] = {{PEGRuleId::Expression, + TransformChildKind::REQUIRED, + 3, + 1, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::Expression, + TransformChildKind::REQUIRED, + 1, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_CaseWhenThen = {FRAME_CHILDREN_CaseWhenThen, 2, 2, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_IntervalLiteral[] = {{PEGRuleId::Interval, + TransformChildKind::OPTIONAL, + 2, + 1, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::IntervalParameter, + TransformChildKind::REQUIRED, + 1, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_IntervalLiteral = {FRAME_CHILDREN_IntervalLiteral, 2, 2, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_FrameClause[] = {{PEGRuleId::WindowExcludeClause, + TransformChildKind::OPTIONAL, + 2, + 2, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::FrameExtent, + TransformChildKind::REQUIRED, + 1, + 1, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::Framing, + TransformChildKind::REQUIRED, + 0, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_FrameClause = {FRAME_CHILDREN_FrameClause, 3, 3, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_SingleFrameExtent[] = {{PEGRuleId::FrameBound, + TransformChildKind::REQUIRED, + 0, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_SingleFrameExtent = {FRAME_CHILDREN_SingleFrameExtent, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_BetweenFrameExtent[] = {{PEGRuleId::FrameBound, + TransformChildKind::REQUIRED, + 3, + 1, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::FrameBound, + TransformChildKind::REQUIRED, + 1, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_BetweenFrameExtent = {FRAME_CHILDREN_BetweenFrameExtent, 2, 2, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_FrameUnbounded[] = {{PEGRuleId::PrecedingOrFollowing, + TransformChildKind::REQUIRED, + 1, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_FrameUnbounded = {FRAME_CHILDREN_FrameUnbounded, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_FrameExpression[] = {{PEGRuleId::PrecedingOrFollowing, + TransformChildKind::REQUIRED, + 1, + 1, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::Expression, + TransformChildKind::REQUIRED, + 0, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_FrameExpression = {FRAME_CHILDREN_FrameExpression, 2, 2, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_WindowExcludeClause[] = {{PEGRuleId::WindowExcludeElement, + TransformChildKind::REQUIRED, + 1, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_WindowExcludeClause = { + FRAME_CHILDREN_WindowExcludeClause, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_WindowFrameNameContentsParens[] = {{PEGRuleId::WindowFrameNameContents, + TransformChildKind::REQUIRED, + 0, + 0, + false, + {1, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_WindowFrameNameContentsParens = { + FRAME_CHILDREN_WindowFrameNameContentsParens, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_WindowFrameNameContents[] = {{PEGRuleId::WindowFrameContents, + TransformChildKind::REQUIRED, + 1, + 1, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::BaseWindowName, + TransformChildKind::OPTIONAL, + 0, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_WindowFrameNameContents = { + FRAME_CHILDREN_WindowFrameNameContents, 2, 2, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_WindowFrameContentsParens[] = {{PEGRuleId::WindowFrameContents, + TransformChildKind::REQUIRED, + 0, + 0, + false, + {1, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_WindowFrameContentsParens = { + FRAME_CHILDREN_WindowFrameContentsParens, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_WindowFrameContents[] = {{PEGRuleId::FrameClause, + TransformChildKind::OPTIONAL, + 2, + 2, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::OrderByClause, + TransformChildKind::OPTIONAL, + 1, + 1, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::WindowPartition, + TransformChildKind::OPTIONAL, + 0, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_WindowFrameContents = { + FRAME_CHILDREN_WindowFrameContents, 3, 3, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_WindowPartition[] = {{PEGRuleId::Expression, + TransformChildKind::LIST, + 2, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_WindowPartition = {FRAME_CHILDREN_WindowPartition, 1, 1, true, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_ArrayBoundedListExpression[] = {{PEGRuleId::BoundedListExpression, + TransformChildKind::REQUIRED, + 1, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_ArrayBoundedListExpression = { + FRAME_CHILDREN_ArrayBoundedListExpression, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_BoundedListExpression[] = {{PEGRuleId::Expression, + TransformChildKind::OPTIONAL_LIST, + 1, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_BoundedListExpression = { + FRAME_CHILDREN_BoundedListExpression, 1, 1, true, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_StructExpression[] = {{PEGRuleId::StructField, + TransformChildKind::OPTIONAL_LIST, + 1, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_StructExpression = {FRAME_CHILDREN_StructExpression, 1, 1, true, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_StructField[] = {{PEGRuleId::Expression, + TransformChildKind::REQUIRED, + 2, + 1, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::ColIdOrString, + TransformChildKind::REQUIRED, + 0, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_StructField = {FRAME_CHILDREN_StructField, 2, 2, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_MapExpression[] = {{PEGRuleId::MapStructExpression, + TransformChildKind::REQUIRED, + 1, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_MapExpression = {FRAME_CHILDREN_MapExpression, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_MapStructExpression[] = {{PEGRuleId::MapStructField, + TransformChildKind::OPTIONAL_LIST, + 1, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_MapStructExpression = { + FRAME_CHILDREN_MapStructExpression, 1, 1, true, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_MapStructField[] = {{PEGRuleId::Expression, + TransformChildKind::REQUIRED, + 2, + 1, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::Expression, + TransformChildKind::REQUIRED, + 0, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_MapStructField = {FRAME_CHILDREN_MapStructField, 2, 2, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_GroupingExpression[] = {{PEGRuleId::Expression, + TransformChildKind::OPTIONAL_LIST, + 1, + 1, + false, + {1, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::GroupingOrGroupingId, + TransformChildKind::REQUIRED, + 0, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_GroupingExpression = {FRAME_CHILDREN_GroupingExpression, 2, 2, true, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_ListComprehensionExpression[] = {{PEGRuleId::ListComprehensionFilter, + TransformChildKind::OPTIONAL, + 6, + 3, + true, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::Expression, + TransformChildKind::REQUIRED, + 5, + 2, + true, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::ColIdOrString, + TransformChildKind::LIST, + 3, + 1, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::Expression, + TransformChildKind::REQUIRED, + 1, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_ListComprehensionExpression = { + FRAME_CHILDREN_ListComprehensionExpression, 4, 4, true, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_ParensExpression[] = {{PEGRuleId::Expression, + TransformChildKind::REQUIRED, + 0, + 0, + false, + {1, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_ParensExpression = {FRAME_CHILDREN_ParensExpression, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_MeasureSemanticsExpression[] = {{PEGRuleId::FunctionExpression, + TransformChildKind::REQUIRED, + 1, + 1, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::MeasureSemantics, + TransformChildKind::REQUIRED, + 0, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_MeasureSemanticsExpression = { + FRAME_CHILDREN_MeasureSemanticsExpression, 2, 2, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_ArrowFullBody[] = {{PEGRuleId::LogicalOrExpression, + TransformChildKind::REQUIRED, + 0, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_ArrowFullBody = {FRAME_CHILDREN_ArrowFullBody, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_ColumnDefaultExpr[] = {{PEGRuleId::ColDefOrExpr, + TransformChildKind::REQUIRED, + 0, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_ColumnDefaultExpr = {FRAME_CHILDREN_ColumnDefaultExpr, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_LogicalOrExpression[] = {{PEGRuleId::LogicalOrExpressionTail, + TransformChildKind::OPTIONAL_REPEAT, + 1, + 1, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::LogicalAndExpression, + TransformChildKind::REQUIRED, + 0, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_LogicalOrExpression = { + FRAME_CHILDREN_LogicalOrExpression, 2, 2, true, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_LogicalOrExpressionTail[] = {{PEGRuleId::LogicalAndExpression, + TransformChildKind::REQUIRED, + 1, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_LogicalOrExpressionTail = { + FRAME_CHILDREN_LogicalOrExpressionTail, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_ColDefOrExpr[] = {{PEGRuleId::ColDefOrExpressionTail, + TransformChildKind::OPTIONAL_REPEAT, + 1, + 1, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::ColDefAndExpr, + TransformChildKind::REQUIRED, + 0, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_ColDefOrExpr = {FRAME_CHILDREN_ColDefOrExpr, 2, 2, true, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_ColDefOrExpressionTail[] = {{PEGRuleId::ColDefAndExpr, + TransformChildKind::REQUIRED, + 1, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_ColDefOrExpressionTail = { + FRAME_CHILDREN_ColDefOrExpressionTail, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_LogicalAndExpression[] = {{PEGRuleId::LogicalAndExpressionTail, + TransformChildKind::OPTIONAL_REPEAT, + 1, + 1, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::LogicalNotExpression, + TransformChildKind::REQUIRED, + 0, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_LogicalAndExpression = { + FRAME_CHILDREN_LogicalAndExpression, 2, 2, true, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_LogicalAndExpressionTail[] = {{PEGRuleId::LogicalNotExpression, + TransformChildKind::REQUIRED, + 1, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_LogicalAndExpressionTail = { + FRAME_CHILDREN_LogicalAndExpressionTail, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_ColDefAndExpr[] = {{PEGRuleId::ColDefAndExpressionTail, + TransformChildKind::OPTIONAL_REPEAT, + 1, + 1, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::IsDistinctFromExpression, + TransformChildKind::REQUIRED, + 0, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_ColDefAndExpr = {FRAME_CHILDREN_ColDefAndExpr, 2, 2, true, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_ColDefAndExpressionTail[] = {{PEGRuleId::IsDistinctFromExpression, + TransformChildKind::REQUIRED, + 1, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_ColDefAndExpressionTail = { + FRAME_CHILDREN_ColDefAndExpressionTail, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_LogicalNotExpression[] = {{PEGRuleId::IsExpression, + TransformChildKind::REQUIRED, + 1, + 1, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::NotExpression, + TransformChildKind::OPTIONAL, + 0, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_LogicalNotExpression = { + FRAME_CHILDREN_LogicalNotExpression, 2, 2, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_NotExpression[] = {{PEGRuleId::NotKeyword, + TransformChildKind::REPEAT, + 0, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_NotExpression = {FRAME_CHILDREN_NotExpression, 1, 1, true, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_IsExpression[] = {{PEGRuleId::IsExpressionContinuation, + TransformChildKind::OPTIONAL, + 1, + 1, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::IsDistinctFromExpression, + TransformChildKind::REQUIRED, + 0, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_IsExpression = {FRAME_CHILDREN_IsExpression, 2, 2, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_IsExpressionContinuation[] = {{PEGRuleId::IsExpressionTail, + TransformChildKind::OPTIONAL_REPEAT, + 1, + 1, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::IsTest, + TransformChildKind::REQUIRED, + 0, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_IsExpressionContinuation = { + FRAME_CHILDREN_IsExpressionContinuation, 2, 2, true, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_IsTestTail[] = {{PEGRuleId::IsTest, + TransformChildKind::REQUIRED, + 0, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_IsTestTail = {FRAME_CHILDREN_IsTestTail, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_IsDistinctTail[] = {{PEGRuleId::IsDistinctFromTail, + TransformChildKind::REQUIRED, + 0, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_IsDistinctTail = {FRAME_CHILDREN_IsDistinctTail, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_IsComparisonTail[] = {{PEGRuleId::ComparisonExpressionTail, + TransformChildKind::REQUIRED, + 0, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_IsComparisonTail = {FRAME_CHILDREN_IsComparisonTail, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_IsOtherOperatorTail[] = {{PEGRuleId::OtherOperatorTail, + TransformChildKind::REQUIRED, + 0, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_IsOtherOperatorTail = { + FRAME_CHILDREN_IsOtherOperatorTail, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_IsCastTail[] = {{PEGRuleId::CastOperator, + TransformChildKind::REQUIRED, + 0, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_IsCastTail = {FRAME_CHILDREN_IsCastTail, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_IsLiteral[] = {{PEGRuleId::IsLiteralValue, + TransformChildKind::REQUIRED, + 2, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_IsLiteral = {FRAME_CHILDREN_IsLiteral, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_IsNull[] = {{PEGRuleId::IsNullOperator, + TransformChildKind::REQUIRED, + 0, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_IsNull = {FRAME_CHILDREN_IsNull, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_IsDistinctFromExpression[] = {{PEGRuleId::IsDistinctFromTail, + TransformChildKind::OPTIONAL_REPEAT, + 1, + 1, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::ComparisonExpression, + TransformChildKind::REQUIRED, + 0, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_IsDistinctFromExpression = { + FRAME_CHILDREN_IsDistinctFromExpression, 2, 2, true, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_IsDistinctFromTail[] = {{PEGRuleId::ComparisonExpression, + TransformChildKind::REQUIRED, + 1, + 1, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::IsDistinctFromOp, + TransformChildKind::REQUIRED, + 0, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_IsDistinctFromTail = {FRAME_CHILDREN_IsDistinctFromTail, 2, 2, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_ComparisonExpression[] = {{PEGRuleId::ComparisonExpressionTail, + TransformChildKind::OPTIONAL_REPEAT, + 1, + 1, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::BetweenInLikeExpression, + TransformChildKind::REQUIRED, + 0, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_ComparisonExpression = { + FRAME_CHILDREN_ComparisonExpression, 2, 2, true, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_ComparisonExpressionTail[] = {{PEGRuleId::ComparisonOperand, + TransformChildKind::REQUIRED, + 1, + 1, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::ComparisonOperator, + TransformChildKind::REQUIRED, + 0, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_ComparisonExpressionTail = { + FRAME_CHILDREN_ComparisonExpressionTail, 2, 2, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_NotComparisonOperand[] = {{PEGRuleId::IsExpression, + TransformChildKind::REQUIRED, + 1, + 1, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::NotExpression, + TransformChildKind::REQUIRED, + 0, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_NotComparisonOperand = { + FRAME_CHILDREN_NotComparisonOperand, 2, 2, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_BetweenInLikeExpression[] = {{PEGRuleId::BetweenLikeOp, + TransformChildKind::OPTIONAL, + 2, + 2, + true, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::InPredicate, + TransformChildKind::OPTIONAL_REPEAT, + 1, + 1, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::OtherOperatorExpression, + TransformChildKind::REQUIRED, + 0, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_BetweenInLikeExpression = { + FRAME_CHILDREN_BetweenInLikeExpression, 3, 3, true, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_InPredicate[] = {{PEGRuleId::CastOperator, + TransformChildKind::OPTIONAL_REPEAT, + 2, + 1, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::InClause, + TransformChildKind::REQUIRED, + 1, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_InPredicate = {FRAME_CHILDREN_InPredicate, 2, 2, true, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_BetweenLikeOp[] = {{PEGRuleId::BetweenLikeOpExpression, + TransformChildKind::REQUIRED, + 1, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_BetweenLikeOp = {FRAME_CHILDREN_BetweenLikeOp, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_LikeClause[] = {{PEGRuleId::EscapeClause, + TransformChildKind::OPTIONAL, + 2, + 2, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::OtherOperatorExpression, + TransformChildKind::REQUIRED, + 1, + 1, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::LikeVariations, + TransformChildKind::REQUIRED, + 0, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_LikeClause = {FRAME_CHILDREN_LikeClause, 3, 3, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_EscapeClause[] = {{PEGRuleId::OtherOperatorExpression, + TransformChildKind::REQUIRED, + 1, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_EscapeClause = {FRAME_CHILDREN_EscapeClause, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_InClause[] = {{PEGRuleId::InExpression, + TransformChildKind::REQUIRED, + 1, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_InClause = {FRAME_CHILDREN_InClause, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_InContainsExpression[] = {{PEGRuleId::OtherOperatorExpression, + TransformChildKind::REQUIRED, + 0, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_InContainsExpression = { + FRAME_CHILDREN_InContainsExpression, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_InExpressionList[] = {{PEGRuleId::Expression, + TransformChildKind::LIST, + 0, + 0, + false, + {1, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_InExpressionList = {FRAME_CHILDREN_InExpressionList, 1, 1, true, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_CTESelectBody[] = {{PEGRuleId::SelectStatementInternal, + TransformChildKind::REQUIRED, + 0, + 0, + false, + {1, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_CTESelectBody = {FRAME_CHILDREN_CTESelectBody, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_BetweenClause[] = {{PEGRuleId::OtherOperatorExpression, + TransformChildKind::REQUIRED, + 4, + 1, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::OtherOperatorExpression, + TransformChildKind::REQUIRED, + 2, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_BetweenClause = {FRAME_CHILDREN_BetweenClause, 2, 2, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_OtherOperatorExpression[] = {{PEGRuleId::InfixOtherOperatorExpression, + TransformChildKind::REQUIRED, + 0, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_OtherOperatorExpression = { + FRAME_CHILDREN_OtherOperatorExpression, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_InfixOtherOperatorExpression[] = {{PEGRuleId::OtherOperatorTail, + TransformChildKind::OPTIONAL_REPEAT, + 1, + 1, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::BitwiseExpression, + TransformChildKind::REQUIRED, + 0, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_InfixOtherOperatorExpression = { + FRAME_CHILDREN_InfixOtherOperatorExpression, 2, 2, true, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_AnyAllSubqueryTail[] = {{PEGRuleId::SubqueryReference, + TransformChildKind::REQUIRED, + 1, + 1, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::AnyAllParsedOperator, + TransformChildKind::REQUIRED, + 0, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_AnyAllSubqueryTail = {FRAME_CHILDREN_AnyAllSubqueryTail, 2, 2, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_OtherOperatorExpressionTail[] = {{PEGRuleId::BitwiseExpression, + TransformChildKind::REQUIRED, + 1, + 1, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::OtherOperator, + TransformChildKind::REQUIRED, + 0, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_OtherOperatorExpressionTail = { + FRAME_CHILDREN_OtherOperatorExpressionTail, 2, 2, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_SingleArrowTail[] = {{PEGRuleId::SingleArrowBody, + TransformChildKind::REQUIRED, + 1, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_SingleArrowTail = {FRAME_CHILDREN_SingleArrowTail, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_ArrowChainBody[] = {{PEGRuleId::ArrowChainTail, + TransformChildKind::REPEAT, + 1, + 1, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::BitwiseExpression, + TransformChildKind::REQUIRED, + 0, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_ArrowChainBody = {FRAME_CHILDREN_ArrowChainBody, 2, 2, true, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_DoubleArrowTail[] = {{PEGRuleId::BitwiseExpression, + TransformChildKind::REQUIRED, + 1, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_DoubleArrowTail = {FRAME_CHILDREN_DoubleArrowTail, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_AnyAllParsedOperator[] = {{PEGRuleId::AnyAllOperator, + TransformChildKind::REQUIRED, + 0, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_AnyAllParsedOperator = { + FRAME_CHILDREN_AnyAllParsedOperator, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_AnyAllOperator[] = {{PEGRuleId::AnyOrAll, + TransformChildKind::REQUIRED, + 1, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_AnyAllOperator = {FRAME_CHILDREN_AnyAllOperator, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_QualifiedOperator[] = {{PEGRuleId::QualifiedOperatorContents, + TransformChildKind::REQUIRED, + 1, + 0, + false, + {1, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_QualifiedOperator = {FRAME_CHILDREN_QualifiedOperator, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_QualifiedOperatorContents[] = {{PEGRuleId::ColIdDot, + TransformChildKind::OPTIONAL_REPEAT, + 0, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_QualifiedOperatorContents = { + FRAME_CHILDREN_QualifiedOperatorContents, 1, 1, true, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_BitwiseExpression[] = {{PEGRuleId::BitwiseExpressionTail, + TransformChildKind::OPTIONAL_REPEAT, + 1, + 1, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::TildeExpression, + TransformChildKind::REQUIRED, + 0, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_BitwiseExpression = {FRAME_CHILDREN_BitwiseExpression, 2, 2, true, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_BitwiseExpressionTail[] = {{PEGRuleId::TildeExpression, + TransformChildKind::REQUIRED, + 1, + 1, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::BitOperator, + TransformChildKind::REQUIRED, + 0, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_BitwiseExpressionTail = { + FRAME_CHILDREN_BitwiseExpressionTail, 2, 2, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_TildeExpression[] = {{PEGRuleId::AdditiveExpression, + TransformChildKind::REQUIRED, + 1, + 1, + true, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::TildePrefixOperator, + TransformChildKind::OPTIONAL_REPEAT, + 0, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_TildeExpression = {FRAME_CHILDREN_TildeExpression, 2, 2, true, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_AdditiveExpression[] = {{PEGRuleId::AdditiveExpressionTail, + TransformChildKind::OPTIONAL_REPEAT, + 1, + 1, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::MultiplicativeExpression, + TransformChildKind::REQUIRED, + 0, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_AdditiveExpression = {FRAME_CHILDREN_AdditiveExpression, 2, 2, true, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_AdditiveExpressionTail[] = {{PEGRuleId::MultiplicativeExpression, + TransformChildKind::REQUIRED, + 1, + 1, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::Term, + TransformChildKind::REQUIRED, + 0, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_AdditiveExpressionTail = { + FRAME_CHILDREN_AdditiveExpressionTail, 2, 2, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_MultiplicativeExpression[] = {{PEGRuleId::MultiplicativeExpressionTail, + TransformChildKind::OPTIONAL_REPEAT, + 1, + 1, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::ExponentiationExpression, + TransformChildKind::REQUIRED, + 0, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_MultiplicativeExpression = { + FRAME_CHILDREN_MultiplicativeExpression, 2, 2, true, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_MultiplicativeExpressionTail[] = {{PEGRuleId::ExponentiationExpression, + TransformChildKind::REQUIRED, + 1, + 1, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::Factor, + TransformChildKind::REQUIRED, + 0, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_MultiplicativeExpressionTail = { + FRAME_CHILDREN_MultiplicativeExpressionTail, 2, 2, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_ExponentiationExpression[] = {{PEGRuleId::ExponentiationExpressionTail, + TransformChildKind::OPTIONAL_REPEAT, + 1, + 1, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::CollateExpression, + TransformChildKind::REQUIRED, + 0, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_ExponentiationExpression = { + FRAME_CHILDREN_ExponentiationExpression, 2, 2, true, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_ExponentiationExpressionTail[] = {{PEGRuleId::CollateExpression, + TransformChildKind::REQUIRED, + 1, + 1, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::ExponentOperator, + TransformChildKind::REQUIRED, + 0, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_ExponentiationExpressionTail = { + FRAME_CHILDREN_ExponentiationExpressionTail, 2, 2, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_CollateExpression[] = {{PEGRuleId::CollateExpressionTail, + TransformChildKind::OPTIONAL_REPEAT, + 1, + 1, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::AtTimeZoneExpression, + TransformChildKind::REQUIRED, + 0, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_CollateExpression = {FRAME_CHILDREN_CollateExpression, 2, 2, true, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_CollateExpressionTail[] = {{PEGRuleId::AtTimeZoneExpression, + TransformChildKind::REQUIRED, + 1, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_CollateExpressionTail = { + FRAME_CHILDREN_CollateExpressionTail, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_AtTimeZoneExpression[] = {{PEGRuleId::AtTimeZoneExpressionTail, + TransformChildKind::OPTIONAL_REPEAT, + 1, + 1, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::UnaryExpression, + TransformChildKind::REQUIRED, + 0, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_AtTimeZoneExpression = { + FRAME_CHILDREN_AtTimeZoneExpression, 2, 2, true, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_AtTimeZoneExpressionTail[] = {{PEGRuleId::UnaryExpression, + TransformChildKind::REQUIRED, + 1, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_AtTimeZoneExpressionTail = { + FRAME_CHILDREN_AtTimeZoneExpressionTail, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_CustomPrefixExpression[] = {{PEGRuleId::TildeExpression, + TransformChildKind::REQUIRED, + 1, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_CustomPrefixExpression = { + FRAME_CHILDREN_CustomPrefixExpression, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_BaseExpression[] = {{PEGRuleId::IndirectionList, + TransformChildKind::OPTIONAL, + 1, + 1, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::SingleExpression, + TransformChildKind::REQUIRED, + 0, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_BaseExpression = {FRAME_CHILDREN_BaseExpression, 2, 2, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_IndirectionList[] = {{PEGRuleId::Indirection, + TransformChildKind::REPEAT, + 0, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_IndirectionList = {FRAME_CHILDREN_IndirectionList, 1, 1, true, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_DotMethodOperator[] = {{PEGRuleId::MethodExpression, + TransformChildKind::REQUIRED, + 1, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_DotMethodOperator = {FRAME_CHILDREN_DotMethodOperator, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_MethodExpression[] = {{PEGRuleId::MethodExpressionArguments, + TransformChildKind::REQUIRED, + 1, + 1, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::ColLabel, + TransformChildKind::REQUIRED, + 0, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_MethodExpression = {FRAME_CHILDREN_MethodExpression, 2, 2, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_MethodExpressionArguments[] = {{PEGRuleId::MethodExpressionArgumentList, + TransformChildKind::REQUIRED, + 0, + 0, + false, + {1, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_MethodExpressionArguments = { + FRAME_CHILDREN_MethodExpressionArguments, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_MethodExpressionArgumentList[] = {{PEGRuleId::IgnoreOrRespectNulls, + TransformChildKind::OPTIONAL, + 3, + 3, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::OrderByClause, + TransformChildKind::OPTIONAL, + 2, + 2, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::MethodFunctionArguments, + TransformChildKind::OPTIONAL, + 1, + 1, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::DistinctOrAll, + TransformChildKind::OPTIONAL, + 0, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_MethodExpressionArgumentList = { + FRAME_CHILDREN_MethodExpressionArgumentList, 4, 4, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_SliceExpression[] = {{PEGRuleId::SliceBound, + TransformChildKind::REQUIRED, + 1, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_SliceExpression = {FRAME_CHILDREN_SliceExpression, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_SliceBound[] = {{PEGRuleId::SliceUpperBound, + TransformChildKind::OPTIONAL, + 1, + 1, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::Expression, + TransformChildKind::OPTIONAL, + 0, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_SliceBound = {FRAME_CHILDREN_SliceBound, 2, 2, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_MinusStepSliceBound[] = {{PEGRuleId::StepSliceBound, + TransformChildKind::REQUIRED, + 2, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_MinusStepSliceBound = { + FRAME_CHILDREN_MinusStepSliceBound, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_EndStepSliceBound[] = {{PEGRuleId::StepSliceBound, + TransformChildKind::OPTIONAL, + 1, + 1, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::EndSliceBound, + TransformChildKind::REQUIRED, + 0, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_EndStepSliceBound = {FRAME_CHILDREN_EndStepSliceBound, 2, 2, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_CoalesceExpression[] = {{PEGRuleId::Expression, + TransformChildKind::LIST, + 1, + 0, + false, + {1, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_CoalesceExpression = {FRAME_CHILDREN_CoalesceExpression, 1, 1, true, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_ColumnsExpression[] = {{PEGRuleId::Expression, + TransformChildKind::REQUIRED, + 2, + 0, + false, + {1, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_ColumnsExpression = {FRAME_CHILDREN_ColumnsExpression, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_ExtractExpression[] = {{PEGRuleId::ExtractArguments, + TransformChildKind::REQUIRED, + 1, + 0, + false, + {1, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_ExtractExpression = {FRAME_CHILDREN_ExtractExpression, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_ExtractArguments[] = {{PEGRuleId::Expression, + TransformChildKind::REQUIRED, + 2, + 1, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::ExtractArgument, + TransformChildKind::REQUIRED, + 0, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_ExtractArguments = {FRAME_CHILDREN_ExtractArguments, 2, 2, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_LambdaExpression[] = {{PEGRuleId::Expression, + TransformChildKind::REQUIRED, + 3, + 1, + true, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::ColIdOrString, + TransformChildKind::LIST, + 1, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_LambdaExpression = {FRAME_CHILDREN_LambdaExpression, 2, 2, true, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_NullIfExpression[] = {{PEGRuleId::NullIfArguments, + TransformChildKind::REQUIRED, + 1, + 0, + false, + {1, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_NullIfExpression = {FRAME_CHILDREN_NullIfExpression, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_PositionExpression[] = {{PEGRuleId::PositionArguments, + TransformChildKind::REQUIRED, + 1, + 0, + false, + {1, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_PositionExpression = {FRAME_CHILDREN_PositionExpression, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_PositionArguments[] = {{PEGRuleId::Expression, + TransformChildKind::REQUIRED, + 2, + 1, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::OtherOperatorExpression, + TransformChildKind::REQUIRED, + 0, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_PositionArguments = {FRAME_CHILDREN_PositionArguments, 2, 2, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_RowExpression[] = {{PEGRuleId::Expression, + TransformChildKind::OPTIONAL_LIST, + 1, + 0, + false, + {1, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_RowExpression = {FRAME_CHILDREN_RowExpression, 1, 1, true, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_SubstringExpression[] = {{PEGRuleId::SubstringArguments, + TransformChildKind::REQUIRED, + 1, + 0, + false, + {1, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_SubstringExpression = { + FRAME_CHILDREN_SubstringExpression, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_OverlayExpressionList[] = {{PEGRuleId::Expression, + TransformChildKind::LIST, + 0, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_OverlayExpressionList = { + FRAME_CHILDREN_OverlayExpressionList, 1, 1, true, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_SubstringParameters[] = {{PEGRuleId::SubstringFromFor, + TransformChildKind::REQUIRED, + 1, + 1, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::Expression, + TransformChildKind::REQUIRED, + 0, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_SubstringParameters = { + FRAME_CHILDREN_SubstringParameters, 2, 2, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_SubstringFromOptionalFor[] = {{PEGRuleId::ForExpression, + TransformChildKind::OPTIONAL, + 1, + 1, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::FromExpression, + TransformChildKind::REQUIRED, + 0, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_SubstringFromOptionalFor = { + FRAME_CHILDREN_SubstringFromOptionalFor, 2, 2, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_SubstringFor[] = {{PEGRuleId::ForExpression, + TransformChildKind::REQUIRED, + 0, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_SubstringFor = {FRAME_CHILDREN_SubstringFor, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_TrimExpression[] = {{PEGRuleId::TrimArguments, + TransformChildKind::REQUIRED, + 1, + 0, + false, + {1, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_TrimExpression = {FRAME_CHILDREN_TrimExpression, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_TrimArguments[] = {{PEGRuleId::Expression, + TransformChildKind::LIST, + 2, + 2, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::TrimSource, + TransformChildKind::OPTIONAL, + 1, + 1, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::TrimDirection, + TransformChildKind::OPTIONAL, + 0, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_TrimArguments = {FRAME_CHILDREN_TrimArguments, 3, 3, true, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_TrimSource[] = {{PEGRuleId::Expression, + TransformChildKind::OPTIONAL, + 0, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_TrimSource = {FRAME_CHILDREN_TrimSource, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_OverlayExpression[] = {{PEGRuleId::OverlayArguments, + TransformChildKind::REQUIRED, + 1, + 0, + false, + {1, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_OverlayExpression = {FRAME_CHILDREN_OverlayExpression, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_OverlayParameters[] = {{PEGRuleId::ForExpression, + TransformChildKind::OPTIONAL, + 4, + 3, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::FromExpression, + TransformChildKind::REQUIRED, + 3, + 2, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::Expression, + TransformChildKind::REQUIRED, + 2, + 1, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::Expression, + TransformChildKind::REQUIRED, + 0, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_OverlayParameters = {FRAME_CHILDREN_OverlayParameters, 4, 4, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_ExtractDatePartArgument[] = {{PEGRuleId::ExtractDatePart, + TransformChildKind::REQUIRED, + 0, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_ExtractDatePartArgument = { + FRAME_CHILDREN_ExtractDatePartArgument, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_CreateExternalResourceStmt[] = { + {PEGRuleId::ExternalResourceCreationOptions, + TransformChildKind::OPTIONAL, + 4, + 2, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::AttachAlias, + TransformChildKind::OPTIONAL, + 3, + 1, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::ExternalResourceType, + TransformChildKind::REQUIRED, + 2, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_CreateExternalResourceStmt = { + FRAME_CHILDREN_CreateExternalResourceStmt, 3, 3, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_RegisterExternalResourceStmt[] = {{PEGRuleId::Expression, + TransformChildKind::REQUIRED, + 5, + 2, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::AttachAlias, + TransformChildKind::OPTIONAL, + 3, + 1, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::ExternalResourceType, + TransformChildKind::REQUIRED, + 2, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_RegisterExternalResourceStmt = { + FRAME_CHILDREN_RegisterExternalResourceStmt, 3, 3, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_DestroyExternalResourceStmt[] = {{PEGRuleId::ColId, + TransformChildKind::REQUIRED, + 2, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_DestroyExternalResourceStmt = { + FRAME_CHILDREN_DestroyExternalResourceStmt, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_ExternalResourceTypeName[] = {{PEGRuleId::BareName, + TransformChildKind::REQUIRED, + 0, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_ExternalResourceTypeName = { + FRAME_CHILDREN_ExternalResourceTypeName, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_AttachToExternalResource[] = {{PEGRuleId::AttachOptions, + TransformChildKind::OPTIONAL, + 4, + 2, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::AttachAlias, + TransformChildKind::REQUIRED, + 3, + 1, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::ExternalResourceSource, + TransformChildKind::REQUIRED, + 2, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_AttachToExternalResource = { + FRAME_CHILDREN_AttachToExternalResource, 3, 3, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_ConnectToExternalResource[] = {{PEGRuleId::AttachOptions, + TransformChildKind::OPTIONAL, + 3, + 1, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::ExternalResourceSource, + TransformChildKind::REQUIRED, + 2, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_ConnectToExternalResource = { + FRAME_CHILDREN_ConnectToExternalResource, 2, 2, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_ExternalResourceCreateClause[] = { + {PEGRuleId::ExternalResourceCreationOptions, + TransformChildKind::OPTIONAL, + 4, + 1, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::ExternalResourceType, + TransformChildKind::REQUIRED, + 3, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_ExternalResourceCreateClause = { + FRAME_CHILDREN_ExternalResourceCreateClause, 2, 2, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_InsertStatement[] = {{PEGRuleId::ReturningClause, + TransformChildKind::OPTIONAL, + 10, + 7, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::OnConflictClause, + TransformChildKind::OPTIONAL, + 9, + 6, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::InsertValues, + TransformChildKind::REQUIRED, + 8, + 5, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::InsertColumnList, + TransformChildKind::OPTIONAL, + 6, + 4, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::ByNameOrPosition, + TransformChildKind::OPTIONAL, + 5, + 3, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::InsertTarget, + TransformChildKind::REQUIRED, + 4, + 2, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::OrAction, + TransformChildKind::OPTIONAL, + 2, + 1, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::WithClause, + TransformChildKind::OPTIONAL, + 0, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_InsertStatement = {FRAME_CHILDREN_InsertStatement, 8, 8, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_InsertByNameOrder[] = {{PEGRuleId::InsertByName, + TransformChildKind::REQUIRED, + 1, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_InsertByNameOrder = {FRAME_CHILDREN_InsertByNameOrder, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_InsertByPositionOrder[] = {{PEGRuleId::InsertByPosition, + TransformChildKind::REQUIRED, + 1, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_InsertByPositionOrder = { + FRAME_CHILDREN_InsertByPositionOrder, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_InsertTarget[] = {{PEGRuleId::InsertAlias, + TransformChildKind::OPTIONAL, + 1, + 1, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::BaseTableName, + TransformChildKind::REQUIRED, + 0, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_InsertTarget = {FRAME_CHILDREN_InsertTarget, 2, 2, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_OnConflictClause[] = {{PEGRuleId::OnConflictAction, + TransformChildKind::REQUIRED, + 3, + 1, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::OnConflictTarget, + TransformChildKind::OPTIONAL, + 2, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_OnConflictClause = {FRAME_CHILDREN_OnConflictClause, 2, 2, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_OnConflictExpressionTarget[] = {{PEGRuleId::WhereClause, + TransformChildKind::OPTIONAL, + 1, + 1, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::ColumnIdList, + TransformChildKind::REQUIRED, + 0, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_OnConflictExpressionTarget = { + FRAME_CHILDREN_OnConflictExpressionTarget, 2, 2, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_OnConflictIndexTarget[] = {{PEGRuleId::ConstraintName, + TransformChildKind::REQUIRED, + 2, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_OnConflictIndexTarget = { + FRAME_CHILDREN_OnConflictIndexTarget, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_OnConflictUpdate[] = {{PEGRuleId::WhereClause, + TransformChildKind::OPTIONAL, + 4, + 1, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::UpdateSetClauseList, + TransformChildKind::REQUIRED, + 3, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_OnConflictUpdate = {FRAME_CHILDREN_OnConflictUpdate, 2, 2, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_PivotUsing[] = {{PEGRuleId::TargetList, + TransformChildKind::REQUIRED, + 1, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_PivotUsing = {FRAME_CHILDREN_PivotUsing, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_LoadStatement[] = {{PEGRuleId::ExtensionAlias, + TransformChildKind::OPTIONAL, + 3, + 2, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::FromSource, + TransformChildKind::OPTIONAL, + 2, + 1, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::ColIdOrString, + TransformChildKind::REQUIRED, + 1, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_LoadStatement = {FRAME_CHILDREN_LoadStatement, 3, 3, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_InstallStatement[] = {{PEGRuleId::VersionNumber, + TransformChildKind::OPTIONAL, + 5, + 3, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::FromSource, + TransformChildKind::OPTIONAL, + 4, + 2, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::IdentifierOrStringLiteral, + TransformChildKind::REQUIRED, + 3, + 1, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::InstallAndLoad, + TransformChildKind::OPTIONAL, + 2, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_InstallStatement = {FRAME_CHILDREN_InstallStatement, 4, 4, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_FromSourceIdentifier[] = {{PEGRuleId::FromSourceName, + TransformChildKind::REQUIRED, + 1, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_FromSourceIdentifier = { + FRAME_CHILDREN_FromSourceIdentifier, 1, 1, false, 0, {}}; +static const char *const FRAME_NAMES_FromSourceName[] = {"Identifier"}; +static const TransformFramePlan FRAME_PLAN_FromSourceName = {nullptr, + 0, + 1, + false, + 0, + {ParseResultTypeBit(ParseResultType::IDENTIFIER) | + ParseResultTypeBit(ParseResultType::KEYWORD) | + ParseResultTypeBit(ParseResultType::STRING), + 0, true, true, 1, FRAME_NAMES_FromSourceName}}; +static const TransformChildPlan FRAME_CHILDREN_VersionNumber[] = {{PEGRuleId::IdentifierOrStringLiteral, + TransformChildKind::REQUIRED, + 1, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_VersionNumber = {FRAME_CHILDREN_VersionNumber, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_CreateExtensionRepositoryStmt[] = {{PEGRuleId::RepositoryPublicKey, + TransformChildKind::OPTIONAL, + 7, + 4, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::RepositoryPrefix, + TransformChildKind::REQUIRED, + 6, + 3, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::ExtensionRepositoryName, + TransformChildKind::REQUIRED, + 5, + 2, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::IfNotExists, + TransformChildKind::OPTIONAL, + 4, + 1, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::OrReplace, + TransformChildKind::OPTIONAL, + 1, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_CreateExtensionRepositoryStmt = { + FRAME_CHILDREN_CreateExtensionRepositoryStmt, 5, 5, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_CreateExtensionRepositoryFromHostStmt[] = { + {PEGRuleId::ExtensionRepositoryName, + TransformChildKind::REQUIRED, + 5, + 2, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::IfNotExists, + TransformChildKind::OPTIONAL, + 4, + 1, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::OrReplace, + TransformChildKind::OPTIONAL, + 1, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_CreateExtensionRepositoryFromHostStmt = { + FRAME_CHILDREN_CreateExtensionRepositoryFromHostStmt, 3, 3, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_DropExtensionRepositoryStmt[] = {{PEGRuleId::ExtensionRepositoryName, + TransformChildKind::REQUIRED, + 4, + 1, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::IfExists, + TransformChildKind::OPTIONAL, + 3, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_DropExtensionRepositoryStmt = { + FRAME_CHILDREN_DropExtensionRepositoryStmt, 2, 2, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_TableMatchRecognizeClause[] = {{PEGRuleId::TableAlias, + TransformChildKind::OPTIONAL, + 2, + 1, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::MatchRecognizeBody, + TransformChildKind::REQUIRED, + 1, + 0, + false, + {1, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_TableMatchRecognizeClause = { + FRAME_CHILDREN_TableMatchRecognizeClause, 2, 2, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_MatchRecognizeBody[] = {{PEGRuleId::MatchRecognizeClause, + TransformChildKind::REPEAT, + 0, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_MatchRecognizeBody = {FRAME_CHILDREN_MatchRecognizeBody, 1, 1, true, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_MRPartition[] = {{PEGRuleId::WindowPartition, + TransformChildKind::REQUIRED, + 0, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_MRPartition = {FRAME_CHILDREN_MRPartition, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_MROrderBy[] = {{PEGRuleId::OrderByClause, + TransformChildKind::REQUIRED, + 0, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_MROrderBy = {FRAME_CHILDREN_MROrderBy, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_MRMeasures[] = {{PEGRuleId::MeasuresClause, + TransformChildKind::REQUIRED, + 0, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_MRMeasures = {FRAME_CHILDREN_MRMeasures, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_MRRows[] = {{PEGRuleId::RowsPerMatch, + TransformChildKind::REQUIRED, + 0, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_MRRows = {FRAME_CHILDREN_MRRows, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_MRSkip[] = {{PEGRuleId::AfterMatchSkip, + TransformChildKind::REQUIRED, + 0, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_MRSkip = {FRAME_CHILDREN_MRSkip, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_MRPattern[] = {{PEGRuleId::PatternClause, + TransformChildKind::REQUIRED, + 0, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_MRPattern = {FRAME_CHILDREN_MRPattern, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_MRSubset[] = {{PEGRuleId::SubsetClause, + TransformChildKind::REQUIRED, + 0, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_MRSubset = {FRAME_CHILDREN_MRSubset, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_MRDefine[] = {{PEGRuleId::DefineClause, + TransformChildKind::REQUIRED, + 0, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_MRDefine = {FRAME_CHILDREN_MRDefine, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_MeasuresClause[] = {{PEGRuleId::MeasuresElement, + TransformChildKind::LIST, + 1, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_MeasuresClause = {FRAME_CHILDREN_MeasuresClause, 1, 1, true, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_ExpressionAsCollabel[] = {{PEGRuleId::ColLabelOrString, + TransformChildKind::REQUIRED, + 2, + 1, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::Expression, + TransformChildKind::REQUIRED, + 0, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_ExpressionAsCollabel = { + FRAME_CHILDREN_ExpressionAsCollabel, 2, 2, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_AllRowsPerMatch[] = {{PEGRuleId::AllRowsEmptyMatches, + TransformChildKind::OPTIONAL, + 4, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_AllRowsPerMatch = {FRAME_CHILDREN_AllRowsPerMatch, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_AfterMatchSkip[] = {{PEGRuleId::AfterMatchSkipTarget, + TransformChildKind::REQUIRED, + 3, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_AfterMatchSkip = {FRAME_CHILDREN_AfterMatchSkip, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_SkipToFirstVar[] = {{PEGRuleId::ColLabelOrString, + TransformChildKind::REQUIRED, + 2, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_SkipToFirstVar = {FRAME_CHILDREN_SkipToFirstVar, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_SkipToVar[] = {{PEGRuleId::ColLabelOrString, + TransformChildKind::REQUIRED, + 1, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_SkipToVar = {FRAME_CHILDREN_SkipToVar, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_PatternClause[] = {{PEGRuleId::RowPattern, + TransformChildKind::REQUIRED, + 1, + 0, + false, + {1, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_PatternClause = {FRAME_CHILDREN_PatternClause, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_RowPattern[] = {{PEGRuleId::RowPatternAlternative, + TransformChildKind::OPTIONAL_REPEAT, + 1, + 1, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::RowPatternTerm, + TransformChildKind::REQUIRED, + 0, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_RowPattern = {FRAME_CHILDREN_RowPattern, 2, 2, true, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_RowPatternAlternative[] = {{PEGRuleId::RowPatternTerm, + TransformChildKind::REQUIRED, + 1, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_RowPatternAlternative = { + FRAME_CHILDREN_RowPatternAlternative, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_RowPatternTerm[] = {{PEGRuleId::RowPatternFactor, + TransformChildKind::REPEAT, + 0, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_RowPatternTerm = {FRAME_CHILDREN_RowPatternTerm, 1, 1, true, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_RowPatternFactor[] = {{PEGRuleId::RowPatternQuantifier, + TransformChildKind::OPTIONAL, + 1, + 1, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::RowPatternPrimary, + TransformChildKind::REQUIRED, + 0, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_RowPatternFactor = {FRAME_CHILDREN_RowPatternFactor, 2, 2, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_RowPatternPermute[] = {{PEGRuleId::RowPattern, + TransformChildKind::LIST, + 1, + 0, + false, + {1, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_RowPatternPermute = {FRAME_CHILDREN_RowPatternPermute, 1, 1, true, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_RowPatternGroup[] = {{PEGRuleId::RowPattern, + TransformChildKind::REQUIRED, + 0, + 0, + false, + {1, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_RowPatternGroup = {FRAME_CHILDREN_RowPatternGroup, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_RowPatternExclusion[] = {{PEGRuleId::RowPattern, + TransformChildKind::REQUIRED, + 2, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_RowPatternExclusion = { + FRAME_CHILDREN_RowPatternExclusion, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_RowPatternLabel[] = {{PEGRuleId::ColLabelOrString, + TransformChildKind::REQUIRED, + 0, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_RowPatternLabel = {FRAME_CHILDREN_RowPatternLabel, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_RowPatternQuantifier[] = {{PEGRuleId::QuantifierReluctant, + TransformChildKind::OPTIONAL, + 1, + 1, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::RowPatternQuantifierKind, + TransformChildKind::REQUIRED, + 0, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_RowPatternQuantifier = { + FRAME_CHILDREN_RowPatternQuantifier, 2, 2, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_QuantifierRange[] = {{PEGRuleId::QuantifierBounds, + TransformChildKind::REQUIRED, + 1, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_QuantifierRange = {FRAME_CHILDREN_QuantifierRange, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_SubsetClause[] = {{PEGRuleId::SubsetElement, + TransformChildKind::LIST, + 1, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_SubsetClause = {FRAME_CHILDREN_SubsetClause, 1, 1, true, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_SubsetElement[] = {{PEGRuleId::ColLabelOrString, + TransformChildKind::LIST, + 2, + 1, + false, + {1, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::ColLabelOrString, + TransformChildKind::REQUIRED, + 0, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_SubsetElement = {FRAME_CHILDREN_SubsetElement, 2, 2, true, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_DefineClause[] = {{PEGRuleId::DefineElement, + TransformChildKind::LIST, + 1, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_DefineClause = {FRAME_CHILDREN_DefineClause, 1, 1, true, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_DefineElement[] = {{PEGRuleId::Expression, + TransformChildKind::REQUIRED, + 2, + 1, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::ColLabelOrString, + TransformChildKind::REQUIRED, + 0, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_DefineElement = {FRAME_CHILDREN_DefineElement, 2, 2, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_MergeIntoStatement[] = {{PEGRuleId::ReturningClause, + TransformChildKind::OPTIONAL, + 7, + 5, + true, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::MergeMatch, + TransformChildKind::REPEAT, + 6, + 4, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::JoinQualifier, + TransformChildKind::REQUIRED, + 5, + 3, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::MergeIntoUsingClause, + TransformChildKind::REQUIRED, + 4, + 2, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::TargetOptAlias, + TransformChildKind::REQUIRED, + 3, + 1, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::WithClause, + TransformChildKind::OPTIONAL, + 0, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_MergeIntoStatement = {FRAME_CHILDREN_MergeIntoStatement, 6, 6, true, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_MergeIntoUsingClause[] = {{PEGRuleId::TableRef, + TransformChildKind::REQUIRED, + 1, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_MergeIntoUsingClause = { + FRAME_CHILDREN_MergeIntoUsingClause, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_MatchedClause[] = {{PEGRuleId::MatchedClauseAction, + TransformChildKind::REQUIRED, + 4, + 1, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::AndExpression, + TransformChildKind::OPTIONAL, + 2, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_MatchedClause = {FRAME_CHILDREN_MatchedClause, 2, 2, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_UpdateMatchClause[] = {{PEGRuleId::UpdateMatchInfo, + TransformChildKind::OPTIONAL, + 1, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_UpdateMatchClause = {FRAME_CHILDREN_UpdateMatchClause, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_UpdateMatchSetAction[] = {{PEGRuleId::UpdateMatchSetClause, + TransformChildKind::REQUIRED, + 0, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_UpdateMatchSetAction = { + FRAME_CHILDREN_UpdateMatchSetAction, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_UpdateByNameOrPosition[] = {{PEGRuleId::ByNameOrPosition, + TransformChildKind::REQUIRED, + 0, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_UpdateByNameOrPosition = { + FRAME_CHILDREN_UpdateByNameOrPosition, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_InsertMatchClause[] = {{PEGRuleId::InsertMatchInfo, + TransformChildKind::OPTIONAL, + 1, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_InsertMatchClause = {FRAME_CHILDREN_InsertMatchClause, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_InsertByNameOrPosition[] = {{PEGRuleId::ByNameOrPosition, + TransformChildKind::OPTIONAL, + 0, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_InsertByNameOrPosition = { + FRAME_CHILDREN_InsertByNameOrPosition, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_InsertValuesList[] = {{PEGRuleId::Expression, + TransformChildKind::LIST, + 2, + 1, + false, + {1, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::InsertColumnList, + TransformChildKind::OPTIONAL, + 0, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_InsertValuesList = {FRAME_CHILDREN_InsertValuesList, 2, 2, true, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_UpdateMatchSetClause[] = {{PEGRuleId::UpdateMatchSetInfo, + TransformChildKind::REQUIRED, + 1, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_UpdateMatchSetClause = { + FRAME_CHILDREN_UpdateMatchSetClause, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_NotMatchedClause[] = {{PEGRuleId::MatchedClauseAction, + TransformChildKind::REQUIRED, + 6, + 2, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::AndExpression, + TransformChildKind::OPTIONAL, + 4, + 1, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::BySourceOrTarget, + TransformChildKind::OPTIONAL, + 3, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_NotMatchedClause = {FRAME_CHILDREN_NotMatchedClause, 3, 3, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_PivotOn[] = {{PEGRuleId::PivotColumnList, + TransformChildKind::REQUIRED, + 1, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_PivotOn = {FRAME_CHILDREN_PivotOn, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_PivotColumnList[] = {{PEGRuleId::PivotColumnEntry, + TransformChildKind::LIST, + 0, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_PivotColumnList = {FRAME_CHILDREN_PivotColumnList, 1, 1, true, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_PivotColumnSubquery[] = {{PEGRuleId::SelectStatementInternal, + TransformChildKind::REQUIRED, + 2, + 1, + false, + {1, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::BaseExpression, + TransformChildKind::REQUIRED, + 0, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_PivotColumnSubquery = { + FRAME_CHILDREN_PivotColumnSubquery, 2, 2, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_IntoNameValues[] = {{PEGRuleId::OptionalParensNameList, + TransformChildKind::REQUIRED, + 4, + 1, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::ColIdOrString, + TransformChildKind::REQUIRED, + 2, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_IntoNameValues = {FRAME_CHILDREN_IntoNameValues, 2, 2, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_ColumnAliases[] = {{PEGRuleId::ColIdOrString, + TransformChildKind::LIST, + 0, + 0, + false, + {1, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_ColumnAliases = {FRAME_CHILDREN_ColumnAliases, 1, 1, true, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_BareNameList[] = {{PEGRuleId::ColIdOrString, + TransformChildKind::LIST, + 0, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_BareNameList = {FRAME_CHILDREN_BareNameList, 1, 1, true, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_PragmaStatement[] = {{PEGRuleId::PragmaAssignOrFunction, + TransformChildKind::REQUIRED, + 1, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_PragmaStatement = {FRAME_CHILDREN_PragmaStatement, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_PragmaAssign[] = {{PEGRuleId::VariableList, + TransformChildKind::REQUIRED, + 2, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_PragmaAssign = {FRAME_CHILDREN_PragmaAssign, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_PragmaFunction[] = {{PEGRuleId::PragmaParameters, + TransformChildKind::OPTIONAL, + 1, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_PragmaFunction = {FRAME_CHILDREN_PragmaFunction, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_PrepareStatement[] = {{PEGRuleId::Statement, + TransformChildKind::REQUIRED, + 4, + 2, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::TypeList, + TransformChildKind::OPTIONAL, + 2, + 1, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::ColIdOrString, + TransformChildKind::REQUIRED, + 1, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_PrepareStatement = {FRAME_CHILDREN_PrepareStatement, 3, 3, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_TypeList[] = { {PEGRuleId::Type, TransformChildKind::LIST, 0, 0, false, {1, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_431 = {FRAME_CHILDREN_415, 1, 1, true, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_416[] = {{PEGRuleId::SelectSetOpChainTail, - TransformChildKind::OPTIONAL_REPEAT, - 1, - 1, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}, - {PEGRuleId::IntersectChain, - TransformChildKind::REQUIRED, - 0, - 0, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_432 = {FRAME_CHILDREN_416, 2, 2, true, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_417[] = {{PEGRuleId::IntersectChain, - TransformChildKind::REQUIRED, - 1, - 1, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}, - {PEGRuleId::SetopClause, - TransformChildKind::REQUIRED, - 0, - 0, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_433 = {FRAME_CHILDREN_417, 2, 2, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_418[] = {{PEGRuleId::IntersectChainTail, - TransformChildKind::OPTIONAL_REPEAT, - 1, - 1, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}, - {PEGRuleId::SelectAtom, - TransformChildKind::REQUIRED, - 0, - 0, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_434 = {FRAME_CHILDREN_418, 2, 2, true, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_419[] = {{PEGRuleId::SelectAtom, - TransformChildKind::REQUIRED, - 1, - 1, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}, - {PEGRuleId::SetIntersectClause, - TransformChildKind::REQUIRED, - 0, - 0, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_435 = {FRAME_CHILDREN_419, 2, 2, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_420[] = {{PEGRuleId::DistinctOrAll, - TransformChildKind::OPTIONAL, - 1, - 0, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_436 = {FRAME_CHILDREN_420, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_421[] = {{PEGRuleId::DistinctOrAll, - TransformChildKind::OPTIONAL, - 1, - 1, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}, - {PEGRuleId::SetopType, - TransformChildKind::REQUIRED, - 0, - 0, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_437 = {FRAME_CHILDREN_421, 2, 2, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_422[] = {{PEGRuleId::LimitOffset, - TransformChildKind::OPTIONAL, - 1, - 1, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}, - {PEGRuleId::OrderByClause, - TransformChildKind::OPTIONAL, - 0, - 0, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_438 = {FRAME_CHILDREN_422, 2, 2, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_423[] = {{PEGRuleId::OffsetClause, - TransformChildKind::OPTIONAL, - 1, - 1, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}, - {PEGRuleId::LimitClause, - TransformChildKind::REQUIRED, - 0, - 0, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_439 = {FRAME_CHILDREN_423, 2, 2, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_424[] = {{PEGRuleId::LimitClause, - TransformChildKind::OPTIONAL, - 1, - 1, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}, - {PEGRuleId::OffsetClause, - TransformChildKind::REQUIRED, - 0, - 0, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_440 = {FRAME_CHILDREN_424, 2, 2, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_425[] = {{PEGRuleId::FetchClause, - TransformChildKind::REQUIRED, - 1, - 1, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}, - {PEGRuleId::OffsetClause, - TransformChildKind::REQUIRED, - 0, - 0, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_441 = {FRAME_CHILDREN_425, 2, 2, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_426[] = {{PEGRuleId::OffsetClause, - TransformChildKind::REQUIRED, - 1, - 1, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}, - {PEGRuleId::FetchClause, - TransformChildKind::REQUIRED, - 0, - 0, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_442 = {FRAME_CHILDREN_426, 2, 2, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_427[] = {{PEGRuleId::FetchClause, - TransformChildKind::REQUIRED, - 0, - 0, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_443 = {FRAME_CHILDREN_427, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_428[] = {{PEGRuleId::BaseTableName, - TransformChildKind::REQUIRED, - 1, - 0, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_444 = {FRAME_CHILDREN_428, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_429[] = {{PEGRuleId::SimpleSelect, - TransformChildKind::REQUIRED, - 0, - 0, - false, - {1, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_445 = {FRAME_CHILDREN_429, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_430[] = {{PEGRuleId::FromClause, - TransformChildKind::OPTIONAL, - 1, - 1, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}, - {PEGRuleId::SelectClause, - TransformChildKind::REQUIRED, - 0, - 0, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_446 = {FRAME_CHILDREN_430, 2, 2, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_431[] = {{PEGRuleId::SelectClause, - TransformChildKind::OPTIONAL, - 1, - 1, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}, - {PEGRuleId::FromClause, - TransformChildKind::REQUIRED, - 0, - 0, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_447 = {FRAME_CHILDREN_431, 2, 2, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_432[] = {{PEGRuleId::CTEBody, - TransformChildKind::REQUIRED, - 5, - 4, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}, - {PEGRuleId::Materialized, - TransformChildKind::OPTIONAL, - 4, - 3, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}, - {PEGRuleId::UsingKey, - TransformChildKind::OPTIONAL, - 2, - 2, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}, - {PEGRuleId::ColumnAliases, - TransformChildKind::OPTIONAL, - 1, - 1, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}, - {PEGRuleId::ColIdOrString, - TransformChildKind::REQUIRED, - 0, - 0, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_448 = {FRAME_CHILDREN_432, 5, 5, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_433[] = {{PEGRuleId::Statement, - TransformChildKind::REQUIRED, - 0, - 0, - false, - {1, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_449 = {FRAME_CHILDREN_433, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_434[] = {{PEGRuleId::TargetList, - TransformChildKind::REQUIRED, - 2, - 0, - false, - {1, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_450 = {FRAME_CHILDREN_434, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_435[] = {{PEGRuleId::TargetList, - TransformChildKind::OPTIONAL, - 2, - 1, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}, - {PEGRuleId::DistinctClause, - TransformChildKind::OPTIONAL, - 1, - 0, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_451 = {FRAME_CHILDREN_435, 2, 2, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_436[] = {{PEGRuleId::AliasedExpression, - TransformChildKind::LIST, - 0, - 0, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_452 = {FRAME_CHILDREN_436, 1, 1, true, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_437[] = {{PEGRuleId::DistinctOnTargets, - TransformChildKind::OPTIONAL, - 1, - 0, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_453 = {FRAME_CHILDREN_437, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_438[] = {{PEGRuleId::SampleClause, - TransformChildKind::OPTIONAL, - 4, - 4, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}, - {PEGRuleId::TableAlias, - TransformChildKind::OPTIONAL, - 3, - 3, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}, - {PEGRuleId::SubqueryReference, - TransformChildKind::REQUIRED, - 2, - 2, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}, - {PEGRuleId::Lateral, - TransformChildKind::OPTIONAL, - 1, - 1, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}, - {PEGRuleId::TableAliasColon, - TransformChildKind::OPTIONAL, - 0, - 0, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_454 = {FRAME_CHILDREN_438, 5, 5, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_439[] = {{PEGRuleId::SampleClause, - TransformChildKind::OPTIONAL, - 4, - 4, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}, - {PEGRuleId::AtClause, - TransformChildKind::OPTIONAL, - 3, - 3, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}, - {PEGRuleId::TableAlias, - TransformChildKind::OPTIONAL, - 2, - 2, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}, - {PEGRuleId::BaseTableName, - TransformChildKind::REQUIRED, - 1, - 1, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}, - {PEGRuleId::TableAliasColon, - TransformChildKind::OPTIONAL, - 0, - 0, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_455 = {FRAME_CHILDREN_439, 5, 5, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_440[] = {{PEGRuleId::SampleClause, - TransformChildKind::OPTIONAL, - 3, - 3, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}, - {PEGRuleId::TableAlias, - TransformChildKind::OPTIONAL, - 2, - 2, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}, - {PEGRuleId::ValuesClause, - TransformChildKind::REQUIRED, - 1, - 1, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}, - {PEGRuleId::TableAliasColon, - TransformChildKind::OPTIONAL, - 0, - 0, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_456 = {FRAME_CHILDREN_440, 4, 4, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_441[] = {{PEGRuleId::SampleClause, - TransformChildKind::OPTIONAL, - 3, - 3, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}, - {PEGRuleId::TableAlias, - TransformChildKind::OPTIONAL, - 2, - 2, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}, - {PEGRuleId::JoinedTableRef, - TransformChildKind::REQUIRED, - 1, - 1, - false, - {1, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}, - {PEGRuleId::TableAliasColon, - TransformChildKind::OPTIONAL, - 0, - 0, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_457 = {FRAME_CHILDREN_441, 4, 4, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_442[] = {{PEGRuleId::JoinOrPivot, - TransformChildKind::REPEAT, - 1, - 1, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}, - {PEGRuleId::InnerTableRef, - TransformChildKind::REQUIRED, - 0, - 0, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_458 = {FRAME_CHILDREN_442, 2, 2, true, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_443[] = {{PEGRuleId::TableAlias, - TransformChildKind::OPTIONAL, - 2, - 1, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}, - {PEGRuleId::TablePivotClauseBody, - TransformChildKind::REQUIRED, - 1, - 0, - false, - {1, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_459 = {FRAME_CHILDREN_443, 2, 2, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_444[] = {{PEGRuleId::PivotGroupByList, - TransformChildKind::OPTIONAL, - 3, - 2, - true, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}, - {PEGRuleId::PivotValueList, - TransformChildKind::REPEAT, - 2, - 1, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}, - {PEGRuleId::TargetList, - TransformChildKind::REQUIRED, - 0, - 0, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_460 = {FRAME_CHILDREN_444, 3, 3, true, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_445[] = {{PEGRuleId::OptionalParensNameList, - TransformChildKind::REQUIRED, - 2, - 0, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_461 = {FRAME_CHILDREN_445, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_446[] = {{PEGRuleId::TableAlias, - TransformChildKind::OPTIONAL, - 3, - 2, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}, - {PEGRuleId::TableUnpivotClauseBody, - TransformChildKind::REQUIRED, - 2, - 1, - false, - {1, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}, - {PEGRuleId::IncludeOrExcludeNulls, - TransformChildKind::OPTIONAL, - 1, - 0, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_462 = {FRAME_CHILDREN_446, 3, 3, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_447[] = {{PEGRuleId::UnpivotValueList, - TransformChildKind::REPEAT, - 2, - 1, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}, - {PEGRuleId::UnpivotHeader, - TransformChildKind::REQUIRED, - 0, - 0, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_463 = {FRAME_CHILDREN_447, 2, 2, true, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_448[] = {{PEGRuleId::BaseExpression, - TransformChildKind::REQUIRED, - 0, - 0, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_464 = {FRAME_CHILDREN_448, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_449[] = {{PEGRuleId::PivotValueTarget, - TransformChildKind::REQUIRED, - 2, - 1, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}, - {PEGRuleId::PivotHeader, - TransformChildKind::REQUIRED, - 0, - 0, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_465 = {FRAME_CHILDREN_449, 2, 2, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_450[] = {{PEGRuleId::PivotTargetList, - TransformChildKind::REQUIRED, - 0, - 0, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_466 = {FRAME_CHILDREN_450, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_451[] = {{PEGRuleId::UnpivotTargetList, - TransformChildKind::REQUIRED, - 2, - 1, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}, - {PEGRuleId::UnpivotHeader, - TransformChildKind::REQUIRED, - 0, - 0, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_467 = {FRAME_CHILDREN_451, 2, 2, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_452[] = {{PEGRuleId::TargetList, - TransformChildKind::REQUIRED, - 0, - 0, - false, - {1, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_468 = {FRAME_CHILDREN_452, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_453[] = {{PEGRuleId::SampleClause, - TransformChildKind::OPTIONAL, - 5, - 5, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}, - {PEGRuleId::TableAlias, - TransformChildKind::OPTIONAL, - 4, - 4, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}, - {PEGRuleId::WithOrdinality, - TransformChildKind::OPTIONAL, - 3, - 3, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}, - {PEGRuleId::TableFunctionArguments, - TransformChildKind::REQUIRED, - 2, - 2, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}, - {PEGRuleId::QualifiedTableFunction, - TransformChildKind::REQUIRED, - 1, - 1, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}, - {PEGRuleId::Lateral, - TransformChildKind::OPTIONAL, - 0, - 0, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_469 = {FRAME_CHILDREN_453, 6, 6, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_454[] = {{PEGRuleId::SampleClause, - TransformChildKind::OPTIONAL, - 4, - 4, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}, - {PEGRuleId::WithOrdinality, - TransformChildKind::OPTIONAL, - 3, - 3, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}, - {PEGRuleId::TableFunctionArguments, - TransformChildKind::REQUIRED, - 2, - 2, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}, - {PEGRuleId::QualifiedTableFunction, - TransformChildKind::REQUIRED, - 1, - 1, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}, - {PEGRuleId::TableAliasColon, - TransformChildKind::REQUIRED, - 0, - 0, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_470 = {FRAME_CHILDREN_454, 5, 5, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_455[] = {{PEGRuleId::SchemaQualification, - TransformChildKind::OPTIONAL_REPEAT, - 1, - 1, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}, - {PEGRuleId::CatalogQualification, - TransformChildKind::REQUIRED, - 0, - 0, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_471 = {FRAME_CHILDREN_455, 2, 2, true, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_456[] = {{PEGRuleId::FunctionArgument, - TransformChildKind::OPTIONAL_LIST, - 0, - 0, - false, - {1, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_472 = {FRAME_CHILDREN_456, 1, 1, true, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_457[] = {{PEGRuleId::Expression, - TransformChildKind::REQUIRED, - 2, - 1, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}, - {PEGRuleId::TypeFuncName, - TransformChildKind::REQUIRED, - 0, - 0, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_473 = {FRAME_CHILDREN_457, 2, 2, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_458[] = {{PEGRuleId::Expression, - TransformChildKind::REQUIRED, - 3, - 2, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}, - {PEGRuleId::Type, - TransformChildKind::OPTIONAL, - 1, - 1, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}, - {PEGRuleId::TypeFuncName, - TransformChildKind::REQUIRED, - 0, - 0, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_474 = {FRAME_CHILDREN_458, 3, 3, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_459[] = {{PEGRuleId::ColumnAliases, - TransformChildKind::OPTIONAL, - 2, - 1, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}, - {PEGRuleId::IdentifierOrStringLiteral, - TransformChildKind::REQUIRED, - 1, - 0, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_475 = {FRAME_CHILDREN_459, 2, 2, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_460[] = {{PEGRuleId::ColumnAliases, - TransformChildKind::OPTIONAL, - 1, - 0, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_476 = {FRAME_CHILDREN_460, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_461[] = {{PEGRuleId::AtSpecifier, - TransformChildKind::REQUIRED, - 1, - 0, - false, - {1, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_477 = {FRAME_CHILDREN_461, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_462[] = {{PEGRuleId::Expression, - TransformChildKind::REQUIRED, - 2, - 1, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}, - {PEGRuleId::AtUnit, - TransformChildKind::REQUIRED, - 0, - 0, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_478 = {FRAME_CHILDREN_462, 2, 2, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_463[] = {{PEGRuleId::Expression, - TransformChildKind::REQUIRED, - 8, - 4, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}, - {PEGRuleId::DistanceOrSimilarity, - TransformChildKind::REQUIRED, - 7, - 3, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}, - {PEGRuleId::ApproxOrExact, - TransformChildKind::OPTIONAL, - 3, - 2, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}, - {PEGRuleId::TableRef, - TransformChildKind::REQUIRED, - 2, - 1, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}, - {PEGRuleId::JoinType, - TransformChildKind::OPTIONAL, - 0, - 0, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_479 = {FRAME_CHILDREN_463, 5, 5, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_464[] = {{PEGRuleId::Expression, - TransformChildKind::REQUIRED, - 8, - 4, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}, - {PEGRuleId::DistanceOrSimilarity, - TransformChildKind::REQUIRED, - 7, - 3, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}, - {PEGRuleId::ApproxOrExact, - TransformChildKind::OPTIONAL, - 3, - 2, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}, - {PEGRuleId::NearestBareTableRef, - TransformChildKind::REQUIRED, - 2, - 1, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}, - {PEGRuleId::JoinType, - TransformChildKind::OPTIONAL, - 0, - 0, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_480 = {FRAME_CHILDREN_464, 5, 5, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_465[] = {{PEGRuleId::ValuesClause, - TransformChildKind::REQUIRED, - 0, - 0, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_481 = {FRAME_CHILDREN_465, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_466[] = {{PEGRuleId::WithOrdinality, - TransformChildKind::OPTIONAL, - 3, - 3, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}, - {PEGRuleId::TableFunctionArguments, - TransformChildKind::REQUIRED, - 2, - 2, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}, - {PEGRuleId::QualifiedTableFunction, - TransformChildKind::REQUIRED, - 1, - 1, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}, - {PEGRuleId::Lateral, - TransformChildKind::OPTIONAL, - 0, - 0, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_482 = {FRAME_CHILDREN_466, 4, 4, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_467[] = {{PEGRuleId::SubqueryReference, - TransformChildKind::REQUIRED, - 1, - 1, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}, - {PEGRuleId::Lateral, - TransformChildKind::OPTIONAL, - 0, - 0, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_483 = {FRAME_CHILDREN_467, 2, 2, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_468[] = {{PEGRuleId::SampleClause, - TransformChildKind::OPTIONAL, - 2, - 2, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}, - {PEGRuleId::AtClause, - TransformChildKind::OPTIONAL, - 1, - 1, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}, - {PEGRuleId::BaseTableName, - TransformChildKind::REQUIRED, - 0, - 0, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_484 = {FRAME_CHILDREN_468, 3, 3, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_469[] = {{PEGRuleId::SampleClause, - TransformChildKind::OPTIONAL, - 1, - 1, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}, - {PEGRuleId::JoinedTableRef, - TransformChildKind::REQUIRED, - 0, - 0, - false, - {1, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_485 = {FRAME_CHILDREN_469, 2, 2, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_470[] = {{PEGRuleId::JoinQualifier, - TransformChildKind::REQUIRED, - 4, - 3, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}, - {PEGRuleId::TableRef, - TransformChildKind::REQUIRED, - 3, - 2, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}, - {PEGRuleId::JoinType, - TransformChildKind::OPTIONAL, - 1, - 1, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}, - {PEGRuleId::Asof, - TransformChildKind::OPTIONAL, - 0, - 0, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_486 = {FRAME_CHILDREN_470, 4, 4, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_471[] = { +static const TransformFramePlan FRAME_PLAN_TypeList = {FRAME_CHILDREN_TypeList, 1, 1, true, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_SelectSetOpChain[] = {{PEGRuleId::SelectSetOpChainTail, + TransformChildKind::OPTIONAL_REPEAT, + 1, + 1, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::IntersectChain, + TransformChildKind::REQUIRED, + 0, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_SelectSetOpChain = {FRAME_CHILDREN_SelectSetOpChain, 2, 2, true, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_SelectSetOpChainTail[] = {{PEGRuleId::IntersectChain, + TransformChildKind::REQUIRED, + 1, + 1, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::SetopClause, + TransformChildKind::REQUIRED, + 0, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_SelectSetOpChainTail = { + FRAME_CHILDREN_SelectSetOpChainTail, 2, 2, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_IntersectChain[] = {{PEGRuleId::IntersectChainTail, + TransformChildKind::OPTIONAL_REPEAT, + 1, + 1, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::SelectAtom, + TransformChildKind::REQUIRED, + 0, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_IntersectChain = {FRAME_CHILDREN_IntersectChain, 2, 2, true, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_IntersectChainTail[] = {{PEGRuleId::SelectAtom, + TransformChildKind::REQUIRED, + 1, + 1, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::SetIntersectClause, + TransformChildKind::REQUIRED, + 0, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_IntersectChainTail = {FRAME_CHILDREN_IntersectChainTail, 2, 2, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_SetIntersectClause[] = {{PEGRuleId::DistinctOrAll, + TransformChildKind::OPTIONAL, + 1, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_SetIntersectClause = {FRAME_CHILDREN_SetIntersectClause, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_SetopClause[] = {{PEGRuleId::DistinctOrAll, + TransformChildKind::OPTIONAL, + 1, + 1, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::SetopType, + TransformChildKind::REQUIRED, + 0, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_SetopClause = {FRAME_CHILDREN_SetopClause, 2, 2, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_ResultModifiers[] = {{PEGRuleId::LimitOffset, + TransformChildKind::OPTIONAL, + 1, + 1, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::OrderByClause, + TransformChildKind::OPTIONAL, + 0, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_ResultModifiers = {FRAME_CHILDREN_ResultModifiers, 2, 2, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_LimitOffsetClause[] = {{PEGRuleId::OffsetClause, + TransformChildKind::OPTIONAL, + 1, + 1, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::LimitClause, + TransformChildKind::REQUIRED, + 0, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_LimitOffsetClause = {FRAME_CHILDREN_LimitOffsetClause, 2, 2, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_OffsetLimitClause[] = {{PEGRuleId::LimitClause, + TransformChildKind::OPTIONAL, + 1, + 1, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::OffsetClause, + TransformChildKind::REQUIRED, + 0, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_OffsetLimitClause = {FRAME_CHILDREN_OffsetLimitClause, 2, 2, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_OffsetFetchClause[] = {{PEGRuleId::FetchClause, + TransformChildKind::REQUIRED, + 1, + 1, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::OffsetClause, + TransformChildKind::REQUIRED, + 0, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_OffsetFetchClause = {FRAME_CHILDREN_OffsetFetchClause, 2, 2, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_FetchOffsetClause[] = {{PEGRuleId::OffsetClause, + TransformChildKind::REQUIRED, + 1, + 1, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::FetchClause, + TransformChildKind::REQUIRED, + 0, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_FetchOffsetClause = {FRAME_CHILDREN_FetchOffsetClause, 2, 2, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_FetchOnlyClause[] = {{PEGRuleId::FetchClause, + TransformChildKind::REQUIRED, + 0, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_FetchOnlyClause = {FRAME_CHILDREN_FetchOnlyClause, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_TableStatement[] = {{PEGRuleId::BaseTableName, + TransformChildKind::REQUIRED, + 1, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_TableStatement = {FRAME_CHILDREN_TableStatement, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_SimpleSelectParens[] = {{PEGRuleId::SimpleSelect, + TransformChildKind::REQUIRED, + 0, + 0, + false, + {1, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_SimpleSelectParens = {FRAME_CHILDREN_SimpleSelectParens, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_SelectFromClause[] = {{PEGRuleId::FromClause, + TransformChildKind::OPTIONAL, + 1, + 1, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::SelectClause, + TransformChildKind::REQUIRED, + 0, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_SelectFromClause = {FRAME_CHILDREN_SelectFromClause, 2, 2, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_FromSelectClause[] = {{PEGRuleId::SelectClause, + TransformChildKind::OPTIONAL, + 1, + 1, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::FromClause, + TransformChildKind::REQUIRED, + 0, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_FromSelectClause = {FRAME_CHILDREN_FromSelectClause, 2, 2, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_WithStatement[] = {{PEGRuleId::CTEBody, + TransformChildKind::REQUIRED, + 5, + 4, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::Materialized, + TransformChildKind::OPTIONAL, + 4, + 3, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::UsingKey, + TransformChildKind::OPTIONAL, + 2, + 2, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::ColumnAliases, + TransformChildKind::OPTIONAL, + 1, + 1, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::ColIdOrString, + TransformChildKind::REQUIRED, + 0, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_WithStatement = {FRAME_CHILDREN_WithStatement, 5, 5, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_CTEDMLBody[] = {{PEGRuleId::Statement, + TransformChildKind::REQUIRED, + 0, + 0, + false, + {1, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_CTEDMLBody = {FRAME_CHILDREN_CTEDMLBody, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_UsingKey[] = {{PEGRuleId::TargetList, + TransformChildKind::REQUIRED, + 2, + 0, + false, + {1, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_UsingKey = {FRAME_CHILDREN_UsingKey, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_SelectClause[] = {{PEGRuleId::TargetList, + TransformChildKind::OPTIONAL, + 2, + 1, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::DistinctClause, + TransformChildKind::OPTIONAL, + 1, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_SelectClause = {FRAME_CHILDREN_SelectClause, 2, 2, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_TargetList[] = {{PEGRuleId::AliasedExpression, + TransformChildKind::LIST, + 0, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_TargetList = {FRAME_CHILDREN_TargetList, 1, 1, true, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_DistinctOn[] = {{PEGRuleId::DistinctOnTargets, + TransformChildKind::OPTIONAL, + 1, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_DistinctOn = {FRAME_CHILDREN_DistinctOn, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_TableSubquery[] = {{PEGRuleId::SampleClause, + TransformChildKind::OPTIONAL, + 4, + 4, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::TableAlias, + TransformChildKind::OPTIONAL, + 3, + 3, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::SubqueryReference, + TransformChildKind::REQUIRED, + 2, + 2, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::Lateral, + TransformChildKind::OPTIONAL, + 1, + 1, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::TableAliasColon, + TransformChildKind::OPTIONAL, + 0, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_TableSubquery = {FRAME_CHILDREN_TableSubquery, 5, 5, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_BaseTableRef[] = {{PEGRuleId::SampleClause, + TransformChildKind::OPTIONAL, + 4, + 4, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::AtClause, + TransformChildKind::OPTIONAL, + 3, + 3, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::TableAlias, + TransformChildKind::OPTIONAL, + 2, + 2, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::BaseTableName, + TransformChildKind::REQUIRED, + 1, + 1, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::TableAliasColon, + TransformChildKind::OPTIONAL, + 0, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_BaseTableRef = {FRAME_CHILDREN_BaseTableRef, 5, 5, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_ValuesRef[] = {{PEGRuleId::SampleClause, + TransformChildKind::OPTIONAL, + 3, + 3, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::TableAlias, + TransformChildKind::OPTIONAL, + 2, + 2, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::ValuesClause, + TransformChildKind::REQUIRED, + 1, + 1, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::TableAliasColon, + TransformChildKind::OPTIONAL, + 0, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_ValuesRef = {FRAME_CHILDREN_ValuesRef, 4, 4, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_ParensTableRef[] = {{PEGRuleId::SampleClause, + TransformChildKind::OPTIONAL, + 3, + 3, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::TableAlias, + TransformChildKind::OPTIONAL, + 2, + 2, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::JoinedTableRef, + TransformChildKind::REQUIRED, + 1, + 1, + false, + {1, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::TableAliasColon, + TransformChildKind::OPTIONAL, + 0, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_ParensTableRef = {FRAME_CHILDREN_ParensTableRef, 4, 4, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_JoinedTableRefChain[] = {{PEGRuleId::JoinOrPivot, + TransformChildKind::REPEAT, + 1, + 1, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::InnerTableRef, + TransformChildKind::REQUIRED, + 0, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_JoinedTableRefChain = { + FRAME_CHILDREN_JoinedTableRefChain, 2, 2, true, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_TablePivotClause[] = {{PEGRuleId::TableAlias, + TransformChildKind::OPTIONAL, + 2, + 1, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::TablePivotClauseBody, + TransformChildKind::REQUIRED, + 1, + 0, + false, + {1, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_TablePivotClause = {FRAME_CHILDREN_TablePivotClause, 2, 2, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_TablePivotClauseBody[] = {{PEGRuleId::PivotGroupByList, + TransformChildKind::OPTIONAL, + 3, + 2, + true, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::PivotValueList, + TransformChildKind::REPEAT, + 2, + 1, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::TargetList, + TransformChildKind::REQUIRED, + 0, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_TablePivotClauseBody = { + FRAME_CHILDREN_TablePivotClauseBody, 3, 3, true, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_PivotGroupByList[] = {{PEGRuleId::OptionalParensNameList, + TransformChildKind::REQUIRED, + 2, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_PivotGroupByList = {FRAME_CHILDREN_PivotGroupByList, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_TableUnpivotClause[] = {{PEGRuleId::TableAlias, + TransformChildKind::OPTIONAL, + 3, + 2, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::TableUnpivotClauseBody, + TransformChildKind::REQUIRED, + 2, + 1, + false, + {1, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::IncludeOrExcludeNulls, + TransformChildKind::OPTIONAL, + 1, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_TableUnpivotClause = {FRAME_CHILDREN_TableUnpivotClause, 3, 3, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_TableUnpivotClauseBody[] = {{PEGRuleId::UnpivotValueList, + TransformChildKind::REPEAT, + 2, + 1, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::UnpivotHeader, + TransformChildKind::REQUIRED, + 0, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_TableUnpivotClauseBody = { + FRAME_CHILDREN_TableUnpivotClauseBody, 2, 2, true, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_PivotHeader[] = {{PEGRuleId::BaseExpression, + TransformChildKind::REQUIRED, + 0, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_PivotHeader = {FRAME_CHILDREN_PivotHeader, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_PivotValueList[] = {{PEGRuleId::PivotValueTarget, + TransformChildKind::REQUIRED, + 2, + 1, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::PivotHeader, + TransformChildKind::REQUIRED, + 0, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_PivotValueList = {FRAME_CHILDREN_PivotValueList, 2, 2, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_PivotListTarget[] = {{PEGRuleId::PivotTargetList, + TransformChildKind::REQUIRED, + 0, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_PivotListTarget = {FRAME_CHILDREN_PivotListTarget, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_UnpivotValueList[] = {{PEGRuleId::UnpivotTargetList, + TransformChildKind::REQUIRED, + 2, + 1, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::UnpivotHeader, + TransformChildKind::REQUIRED, + 0, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_UnpivotValueList = {FRAME_CHILDREN_UnpivotValueList, 2, 2, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_PivotTargetList[] = {{PEGRuleId::TargetList, + TransformChildKind::REQUIRED, + 0, + 0, + false, + {1, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_PivotTargetList = {FRAME_CHILDREN_PivotTargetList, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_TableFunctionLateralOpt[] = {{PEGRuleId::SampleClause, + TransformChildKind::OPTIONAL, + 5, + 5, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::TableAlias, + TransformChildKind::OPTIONAL, + 4, + 4, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::WithOrdinality, + TransformChildKind::OPTIONAL, + 3, + 3, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::TableFunctionArguments, + TransformChildKind::REQUIRED, + 2, + 2, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::QualifiedTableFunction, + TransformChildKind::REQUIRED, + 1, + 1, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::Lateral, + TransformChildKind::OPTIONAL, + 0, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_TableFunctionLateralOpt = { + FRAME_CHILDREN_TableFunctionLateralOpt, 6, 6, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_TableFunctionAliasColon[] = {{PEGRuleId::SampleClause, + TransformChildKind::OPTIONAL, + 4, + 4, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::WithOrdinality, + TransformChildKind::OPTIONAL, + 3, + 3, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::TableFunctionArguments, + TransformChildKind::REQUIRED, + 2, + 2, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::QualifiedTableFunction, + TransformChildKind::REQUIRED, + 1, + 1, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::TableAliasColon, + TransformChildKind::REQUIRED, + 0, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_TableFunctionAliasColon = { + FRAME_CHILDREN_TableFunctionAliasColon, 5, 5, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_CatalogReservedSchemaTableFunctionName[] = { + {PEGRuleId::SchemaQualification, + TransformChildKind::OPTIONAL_REPEAT, + 1, + 1, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::CatalogQualification, + TransformChildKind::REQUIRED, + 0, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_CatalogReservedSchemaTableFunctionName = { + FRAME_CHILDREN_CatalogReservedSchemaTableFunctionName, 2, 2, true, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_TableFunctionArguments[] = {{PEGRuleId::FunctionArgument, + TransformChildKind::OPTIONAL_LIST, + 0, + 0, + false, + {1, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_TableFunctionArguments = { + FRAME_CHILDREN_TableFunctionArguments, 1, 1, true, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_NamedFunctionArgument[] = {{PEGRuleId::Expression, + TransformChildKind::REQUIRED, + 2, + 1, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::TypeFuncName, + TransformChildKind::REQUIRED, + 0, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_NamedFunctionArgument = { + FRAME_CHILDREN_NamedFunctionArgument, 2, 2, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_NamedParameter[] = {{PEGRuleId::Expression, + TransformChildKind::REQUIRED, + 3, + 2, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::Type, + TransformChildKind::OPTIONAL, + 1, + 1, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::TypeFuncName, + TransformChildKind::REQUIRED, + 0, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_NamedParameter = {FRAME_CHILDREN_NamedParameter, 3, 3, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_TableAliasAs[] = {{PEGRuleId::ColumnAliases, + TransformChildKind::OPTIONAL, + 2, + 1, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::IdentifierOrStringLiteral, + TransformChildKind::REQUIRED, + 1, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_TableAliasAs = {FRAME_CHILDREN_TableAliasAs, 2, 2, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_TableAliasWithoutAs[] = {{PEGRuleId::ColumnAliases, + TransformChildKind::OPTIONAL, + 1, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_TableAliasWithoutAs = { + FRAME_CHILDREN_TableAliasWithoutAs, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_AtClause[] = {{PEGRuleId::AtSpecifier, + TransformChildKind::REQUIRED, + 1, + 0, + false, + {1, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_AtClause = {FRAME_CHILDREN_AtClause, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_AtSpecifier[] = {{PEGRuleId::Expression, + TransformChildKind::REQUIRED, + 2, + 1, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::AtUnit, + TransformChildKind::REQUIRED, + 0, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_AtSpecifier = {FRAME_CHILDREN_AtSpecifier, 2, 2, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_NearestJoinAliased[] = {{PEGRuleId::Expression, + TransformChildKind::REQUIRED, + 8, + 4, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::DistanceOrSimilarity, + TransformChildKind::REQUIRED, + 7, + 3, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::ApproxOrExact, + TransformChildKind::OPTIONAL, + 3, + 2, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::TableRef, + TransformChildKind::REQUIRED, + 2, + 1, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::JoinType, + TransformChildKind::OPTIONAL, + 0, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_NearestJoinAliased = {FRAME_CHILDREN_NearestJoinAliased, 5, 5, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_NearestJoinBare[] = {{PEGRuleId::Expression, + TransformChildKind::REQUIRED, + 8, + 4, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::DistanceOrSimilarity, + TransformChildKind::REQUIRED, + 7, + 3, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::ApproxOrExact, + TransformChildKind::OPTIONAL, + 3, + 2, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::NearestBareTableRef, + TransformChildKind::REQUIRED, + 2, + 1, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::JoinType, + TransformChildKind::OPTIONAL, + 0, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_NearestJoinBare = {FRAME_CHILDREN_NearestJoinBare, 5, 5, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_NearestValuesRef[] = {{PEGRuleId::ValuesClause, + TransformChildKind::REQUIRED, + 0, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_NearestValuesRef = {FRAME_CHILDREN_NearestValuesRef, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_NearestTableFunction[] = {{PEGRuleId::WithOrdinality, + TransformChildKind::OPTIONAL, + 3, + 3, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::TableFunctionArguments, + TransformChildKind::REQUIRED, + 2, + 2, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::QualifiedTableFunction, + TransformChildKind::REQUIRED, + 1, + 1, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::Lateral, + TransformChildKind::OPTIONAL, + 0, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_NearestTableFunction = { + FRAME_CHILDREN_NearestTableFunction, 4, 4, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_NearestTableSubquery[] = {{PEGRuleId::SubqueryReference, + TransformChildKind::REQUIRED, + 1, + 1, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::Lateral, + TransformChildKind::OPTIONAL, + 0, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_NearestTableSubquery = { + FRAME_CHILDREN_NearestTableSubquery, 2, 2, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_NearestBaseTableRef[] = {{PEGRuleId::SampleClause, + TransformChildKind::OPTIONAL, + 2, + 2, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::AtClause, + TransformChildKind::OPTIONAL, + 1, + 1, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::BaseTableName, + TransformChildKind::REQUIRED, + 0, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_NearestBaseTableRef = { + FRAME_CHILDREN_NearestBaseTableRef, 3, 3, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_NearestParensTableRef[] = {{PEGRuleId::SampleClause, + TransformChildKind::OPTIONAL, + 1, + 1, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::JoinedTableRef, + TransformChildKind::REQUIRED, + 0, + 0, + false, + {1, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_NearestParensTableRef = { + FRAME_CHILDREN_NearestParensTableRef, 2, 2, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_RegularJoinClause[] = {{PEGRuleId::JoinQualifier, + TransformChildKind::REQUIRED, + 4, + 3, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::TableRef, + TransformChildKind::REQUIRED, + 3, + 2, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::JoinType, + TransformChildKind::OPTIONAL, + 1, + 1, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::Asof, + TransformChildKind::OPTIONAL, + 0, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_RegularJoinClause = {FRAME_CHILDREN_RegularJoinClause, 4, 4, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_JoinByClause[] = { {PEGRuleId::JoinQualifier, TransformChildKind::REQUIRED, 4, @@ -6576,100 +6742,102 @@ static const TransformChildPlan FRAME_CHILDREN_471[] = { {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}, {PEGRuleId::ColLabel, TransformChildKind::REQUIRED, 2, 0, false, {1, 1, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_487 = {FRAME_CHILDREN_471, 3, 3, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_472[] = {{PEGRuleId::InnerTableRef, - TransformChildKind::REQUIRED, - 2, - 1, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}, - {PEGRuleId::JoinPrefix, - TransformChildKind::REQUIRED, - 0, - 0, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_488 = {FRAME_CHILDREN_472, 2, 2, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_473[] = {{PEGRuleId::UsingColumnName, - TransformChildKind::LIST, - 1, - 0, - false, - {1, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_489 = {FRAME_CHILDREN_473, 1, 1, true, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_474[] = {{PEGRuleId::JoinType, - TransformChildKind::OPTIONAL, - 1, - 0, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_490 = {FRAME_CHILDREN_474, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_475[] = {{PEGRuleId::GroupByExpressions, - TransformChildKind::REQUIRED, - 2, - 0, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_491 = {FRAME_CHILDREN_475, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_476[] = {{PEGRuleId::SampleEntry, - TransformChildKind::REQUIRED, - 1, - 0, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_492 = {FRAME_CHILDREN_476, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_477[] = {{PEGRuleId::WindowDefinition, - TransformChildKind::LIST, - 1, - 0, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_493 = {FRAME_CHILDREN_477, 1, 1, true, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_478[] = {{PEGRuleId::SampleProperties, - TransformChildKind::OPTIONAL, - 1, - 1, - false, - {0, TRANSFORM_PATH_END, 0}, - {1, TRANSFORM_PATH_END, 0}}, - {PEGRuleId::SampleCount, - TransformChildKind::REQUIRED, - 0, - 0, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_494 = {FRAME_CHILDREN_478, 2, 2, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_479[] = {{PEGRuleId::RepeatableSample, - TransformChildKind::OPTIONAL, - 2, - 2, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}, - {PEGRuleId::SampleCount, - TransformChildKind::REQUIRED, - 1, - 1, - false, - {1, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}, - {PEGRuleId::SampleFunction, - TransformChildKind::OPTIONAL, - 0, - 0, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_495 = {FRAME_CHILDREN_479, 3, 3, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_480[] = { +static const TransformFramePlan FRAME_PLAN_JoinByClause = {FRAME_CHILDREN_JoinByClause, 3, 3, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_JoinWithoutOnClause[] = {{PEGRuleId::InnerTableRef, + TransformChildKind::REQUIRED, + 2, + 1, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::JoinPrefix, + TransformChildKind::REQUIRED, + 0, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_JoinWithoutOnClause = { + FRAME_CHILDREN_JoinWithoutOnClause, 2, 2, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_UsingClause[] = {{PEGRuleId::UsingColumnName, + TransformChildKind::LIST, + 1, + 0, + false, + {1, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_UsingClause = {FRAME_CHILDREN_UsingClause, 1, 1, true, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_NaturalJoinPrefix[] = {{PEGRuleId::JoinType, + TransformChildKind::OPTIONAL, + 1, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_NaturalJoinPrefix = {FRAME_CHILDREN_NaturalJoinPrefix, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_GroupByClause[] = {{PEGRuleId::GroupByExpressions, + TransformChildKind::REQUIRED, + 2, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_GroupByClause = {FRAME_CHILDREN_GroupByClause, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_SampleClause[] = {{PEGRuleId::SampleEntry, + TransformChildKind::REQUIRED, + 1, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_SampleClause = {FRAME_CHILDREN_SampleClause, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_WindowClause[] = {{PEGRuleId::WindowDefinition, + TransformChildKind::LIST, + 1, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_WindowClause = {FRAME_CHILDREN_WindowClause, 1, 1, true, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_SampleEntryCount[] = {{PEGRuleId::SampleProperties, + TransformChildKind::OPTIONAL, + 1, + 1, + false, + {0, TRANSFORM_PATH_END, 0}, + {1, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::SampleCount, + TransformChildKind::REQUIRED, + 0, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_SampleEntryCount = {FRAME_CHILDREN_SampleEntryCount, 2, 2, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_SampleEntryFunction[] = {{PEGRuleId::RepeatableSample, + TransformChildKind::OPTIONAL, + 2, + 2, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::SampleCount, + TransformChildKind::REQUIRED, + 1, + 1, + false, + {1, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::SampleFunction, + TransformChildKind::OPTIONAL, + 0, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_SampleEntryFunction = { + FRAME_CHILDREN_SampleEntryFunction, 3, 3, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_SampleProperties[] = { {PEGRuleId::SampleSeed, TransformChildKind::OPTIONAL, 1, 1, false, {0, TRANSFORM_PATH_END, 0}, {0, 1, 0}}, {PEGRuleId::ColId, TransformChildKind::REQUIRED, @@ -6678,414 +6846,424 @@ static const TransformChildPlan FRAME_CHILDREN_480[] = { false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_496 = {FRAME_CHILDREN_480, 2, 2, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_481[] = {{PEGRuleId::SampleSeed, - TransformChildKind::REQUIRED, - 1, - 0, - false, - {1, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_497 = {FRAME_CHILDREN_481, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_482[] = {{PEGRuleId::SampleUnit, - TransformChildKind::OPTIONAL, - 1, - 1, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}, - {PEGRuleId::SampleValue, - TransformChildKind::REQUIRED, - 0, - 0, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_498 = {FRAME_CHILDREN_482, 2, 2, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_483[] = {{PEGRuleId::GroupByExpression, - TransformChildKind::LIST, - 0, - 0, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_499 = {FRAME_CHILDREN_483, 1, 1, true, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_484[] = {{PEGRuleId::Expression, - TransformChildKind::OPTIONAL_LIST, - 1, - 1, - false, - {1, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}, - {PEGRuleId::CubeOrRollup, - TransformChildKind::REQUIRED, - 0, - 0, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_500 = {FRAME_CHILDREN_484, 2, 2, true, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_485[] = {{PEGRuleId::GroupByExpression, - TransformChildKind::LIST, - 2, - 0, - false, - {1, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_501 = {FRAME_CHILDREN_485, 1, 1, true, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_486[] = {{PEGRuleId::OrderByExpressions, - TransformChildKind::REQUIRED, - 2, - 0, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_502 = {FRAME_CHILDREN_486, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_487[] = {{PEGRuleId::OrderByExpression, - TransformChildKind::LIST, - 0, - 0, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_503 = {FRAME_CHILDREN_487, 1, 1, true, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_488[] = {{PEGRuleId::NullsFirstOrLast, - TransformChildKind::OPTIONAL, - 2, - 1, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}, - {PEGRuleId::DescOrAsc, - TransformChildKind::OPTIONAL, - 1, - 0, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_504 = {FRAME_CHILDREN_488, 2, 2, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_489[] = {{PEGRuleId::LimitValue, - TransformChildKind::REQUIRED, - 1, - 0, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_505 = {FRAME_CHILDREN_489, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_490[] = {{PEGRuleId::OffsetValue, - TransformChildKind::REQUIRED, - 1, - 0, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_506 = {FRAME_CHILDREN_490, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_491[] = {{PEGRuleId::FetchValue, - TransformChildKind::REQUIRED, - 2, - 0, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_507 = {FRAME_CHILDREN_491, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_492[] = {{PEGRuleId::Expression, - TransformChildKind::REQUIRED, - 2, - 1, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}, - {PEGRuleId::ColId, - TransformChildKind::REQUIRED, - 0, - 0, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_508 = {FRAME_CHILDREN_492, 2, 2, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_493[] = {{PEGRuleId::ValuesExpressions, - TransformChildKind::LIST, - 1, - 0, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_509 = {FRAME_CHILDREN_493, 1, 1, true, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_494[] = {{PEGRuleId::SetAssignmentOrTimeZone, - TransformChildKind::REQUIRED, - 1, - 0, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_510 = {FRAME_CHILDREN_494, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_495[] = {{PEGRuleId::Expression, - TransformChildKind::REQUIRED, - 3, - 0, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_511 = {FRAME_CHILDREN_495, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_496[] = {{PEGRuleId::ResetTarget, - TransformChildKind::REQUIRED, - 1, - 0, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_512 = {FRAME_CHILDREN_496, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_497[] = {{PEGRuleId::SettingScope, - TransformChildKind::OPTIONAL, - 0, - 0, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_513 = {FRAME_CHILDREN_497, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_498[] = {{PEGRuleId::SetVariableOrSetting, - TransformChildKind::REQUIRED, - 0, - 0, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_514 = {FRAME_CHILDREN_498, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_499[] = {{PEGRuleId::SetAssignment, - TransformChildKind::REQUIRED, - 1, - 1, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}, - {PEGRuleId::SetVariableOrSetting, - TransformChildKind::REQUIRED, - 0, - 0, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_515 = {FRAME_CHILDREN_499, 2, 2, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_500[] = {{PEGRuleId::ZoneValue, - TransformChildKind::REQUIRED, - 3, - 1, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}, - {PEGRuleId::SettingScope, - TransformChildKind::OPTIONAL, - 0, - 0, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_516 = {FRAME_CHILDREN_500, 2, 2, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_501[] = {{PEGRuleId::Interval, - TransformChildKind::OPTIONAL, - 2, - 0, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_517 = {FRAME_CHILDREN_501, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_502[] = {{PEGRuleId::VariableScope, - TransformChildKind::REQUIRED, - 0, - 0, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_518 = {FRAME_CHILDREN_502, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_503[] = {{PEGRuleId::VariableList, - TransformChildKind::REQUIRED, - 1, - 0, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_519 = {FRAME_CHILDREN_503, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_504[] = {{PEGRuleId::ReadOrWrite, - TransformChildKind::OPTIONAL, - 2, - 0, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_520 = {FRAME_CHILDREN_504, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_505[] = {{PEGRuleId::ReadOnlyOrReadWrite, - TransformChildKind::REQUIRED, - 1, - 0, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_521 = {FRAME_CHILDREN_505, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_506[] = {{PEGRuleId::ReturningClause, - TransformChildKind::OPTIONAL, - 6, - 5, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}, - {PEGRuleId::WhereClause, - TransformChildKind::OPTIONAL, - 5, - 4, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}, - {PEGRuleId::FromClause, - TransformChildKind::OPTIONAL, - 4, - 3, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}, - {PEGRuleId::UpdateSetClauseList, - TransformChildKind::REQUIRED, - 3, - 2, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}, - {PEGRuleId::UpdateTarget, - TransformChildKind::REQUIRED, - 2, - 1, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}, - {PEGRuleId::WithClause, - TransformChildKind::OPTIONAL, - 0, - 0, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_522 = {FRAME_CHILDREN_506, 6, 6, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_507[] = {{PEGRuleId::UpdateAlias, - TransformChildKind::OPTIONAL, - 1, - 1, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}, - {PEGRuleId::BaseTableName, - TransformChildKind::REQUIRED, - 0, - 0, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_523 = {FRAME_CHILDREN_507, 2, 2, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_508[] = {{PEGRuleId::UpdateSetClause, - TransformChildKind::LIST, - 0, - 0, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_524 = {FRAME_CHILDREN_508, 1, 1, true, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_509[] = {{PEGRuleId::Expression, - TransformChildKind::REQUIRED, - 2, - 1, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}, - {PEGRuleId::UpdateSetColumnTarget, - TransformChildKind::REQUIRED, - 0, - 0, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_525 = {FRAME_CHILDREN_509, 2, 2, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_510[] = {{PEGRuleId::DotIdentifier, - TransformChildKind::OPTIONAL_REPEAT, - 1, - 0, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_526 = {FRAME_CHILDREN_510, 1, 1, true, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_511[] = {{PEGRuleId::UseTarget, - TransformChildKind::REQUIRED, - 1, - 0, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_527 = {FRAME_CHILDREN_511, 1, 1, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_512[] = {{PEGRuleId::DotIdentifier, - TransformChildKind::OPTIONAL_REPEAT, - 3, - 0, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_528 = {FRAME_CHILDREN_512, 1, 1, true, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_513[] = {{PEGRuleId::AnalyzeTarget, - TransformChildKind::OPTIONAL, - 2, - 1, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}, - {PEGRuleId::VacuumOptions, - TransformChildKind::OPTIONAL, - 1, - 0, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_529 = {FRAME_CHILDREN_513, 2, 2, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_514[] = {{PEGRuleId::VacuumOption, - TransformChildKind::LIST, - 0, - 0, - false, - {1, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_530 = {FRAME_CHILDREN_514, 1, 1, true, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_515[] = {{PEGRuleId::OptAnalyze, - TransformChildKind::OPTIONAL, - 3, - 3, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}, - {PEGRuleId::OptVerbose, - TransformChildKind::OPTIONAL, - 2, - 2, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}, - {PEGRuleId::OptFreeze, - TransformChildKind::OPTIONAL, - 1, - 1, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}, - {PEGRuleId::OptFull, - TransformChildKind::OPTIONAL, - 0, - 0, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_531 = {FRAME_CHILDREN_515, 4, 4, false, 0, {}}; -static const TransformChildPlan FRAME_CHILDREN_516[] = {{PEGRuleId::AnalyzeKeyword, - TransformChildKind::REQUIRED, - 0, - 0, - false, - {0, TRANSFORM_PATH_END, 0}, - {0, TRANSFORM_PATH_END, 0}}}; -static const TransformFramePlan FRAME_PLAN_532 = {FRAME_CHILDREN_516, 1, 1, false, 0, {}}; +static const TransformFramePlan FRAME_PLAN_SampleProperties = {FRAME_CHILDREN_SampleProperties, 2, 2, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_RepeatableSample[] = {{PEGRuleId::SampleSeed, + TransformChildKind::REQUIRED, + 1, + 0, + false, + {1, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_RepeatableSample = {FRAME_CHILDREN_RepeatableSample, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_SampleCount[] = {{PEGRuleId::SampleUnit, + TransformChildKind::OPTIONAL, + 1, + 1, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::SampleValue, + TransformChildKind::REQUIRED, + 0, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_SampleCount = {FRAME_CHILDREN_SampleCount, 2, 2, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_GroupByList[] = {{PEGRuleId::GroupByExpression, + TransformChildKind::LIST, + 0, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_GroupByList = {FRAME_CHILDREN_GroupByList, 1, 1, true, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_CubeOrRollupClause[] = {{PEGRuleId::Expression, + TransformChildKind::OPTIONAL_LIST, + 1, + 1, + false, + {1, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::CubeOrRollup, + TransformChildKind::REQUIRED, + 0, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_CubeOrRollupClause = {FRAME_CHILDREN_CubeOrRollupClause, 2, 2, true, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_GroupingSetsClause[] = {{PEGRuleId::GroupByExpression, + TransformChildKind::LIST, + 2, + 0, + false, + {1, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_GroupingSetsClause = {FRAME_CHILDREN_GroupingSetsClause, 1, 1, true, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_OrderByClause[] = {{PEGRuleId::OrderByExpressions, + TransformChildKind::REQUIRED, + 2, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_OrderByClause = {FRAME_CHILDREN_OrderByClause, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_OrderByExpressionList[] = {{PEGRuleId::OrderByExpression, + TransformChildKind::LIST, + 0, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_OrderByExpressionList = { + FRAME_CHILDREN_OrderByExpressionList, 1, 1, true, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_OrderByAll[] = {{PEGRuleId::NullsFirstOrLast, + TransformChildKind::OPTIONAL, + 2, + 1, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::DescOrAsc, + TransformChildKind::OPTIONAL, + 1, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_OrderByAll = {FRAME_CHILDREN_OrderByAll, 2, 2, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_LimitClause[] = {{PEGRuleId::LimitValue, + TransformChildKind::REQUIRED, + 1, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_LimitClause = {FRAME_CHILDREN_LimitClause, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_OffsetClause[] = {{PEGRuleId::OffsetValue, + TransformChildKind::REQUIRED, + 1, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_OffsetClause = {FRAME_CHILDREN_OffsetClause, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_FetchClauseWithValue[] = {{PEGRuleId::FetchValue, + TransformChildKind::REQUIRED, + 2, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_FetchClauseWithValue = { + FRAME_CHILDREN_FetchClauseWithValue, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_ColIdExpression[] = {{PEGRuleId::Expression, + TransformChildKind::REQUIRED, + 2, + 1, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::ColId, + TransformChildKind::REQUIRED, + 0, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_ColIdExpression = {FRAME_CHILDREN_ColIdExpression, 2, 2, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_ValuesClause[] = {{PEGRuleId::ValuesExpressions, + TransformChildKind::LIST, + 1, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_ValuesClause = {FRAME_CHILDREN_ValuesClause, 1, 1, true, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_SetKeywordStatement[] = {{PEGRuleId::SetAssignmentOrTimeZone, + TransformChildKind::REQUIRED, + 1, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_SetKeywordStatement = { + FRAME_CHILDREN_SetKeywordStatement, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_VariableAssignment[] = {{PEGRuleId::Expression, + TransformChildKind::REQUIRED, + 3, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_VariableAssignment = {FRAME_CHILDREN_VariableAssignment, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_ResetStatement[] = {{PEGRuleId::ResetTarget, + TransformChildKind::REQUIRED, + 1, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_ResetStatement = {FRAME_CHILDREN_ResetStatement, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_ResetTimeZone[] = {{PEGRuleId::SettingScope, + TransformChildKind::OPTIONAL, + 0, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_ResetTimeZone = {FRAME_CHILDREN_ResetTimeZone, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_ResetVariableOrSetting[] = {{PEGRuleId::SetVariableOrSetting, + TransformChildKind::REQUIRED, + 0, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_ResetVariableOrSetting = { + FRAME_CHILDREN_ResetVariableOrSetting, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_StandardAssignment[] = {{PEGRuleId::SetAssignment, + TransformChildKind::REQUIRED, + 1, + 1, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::SetVariableOrSetting, + TransformChildKind::REQUIRED, + 0, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_StandardAssignment = {FRAME_CHILDREN_StandardAssignment, 2, 2, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_SetTimeZone[] = {{PEGRuleId::ZoneValue, + TransformChildKind::REQUIRED, + 3, + 1, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::SettingScope, + TransformChildKind::OPTIONAL, + 0, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_SetTimeZone = {FRAME_CHILDREN_SetTimeZone, 2, 2, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_ZoneIntervalWithInterval[] = {{PEGRuleId::Interval, + TransformChildKind::OPTIONAL, + 2, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_ZoneIntervalWithInterval = { + FRAME_CHILDREN_ZoneIntervalWithInterval, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_SetVariable[] = {{PEGRuleId::VariableScope, + TransformChildKind::REQUIRED, + 0, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_SetVariable = {FRAME_CHILDREN_SetVariable, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_SetAssignment[] = {{PEGRuleId::VariableList, + TransformChildKind::REQUIRED, + 1, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_SetAssignment = {FRAME_CHILDREN_SetAssignment, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_BeginTransaction[] = {{PEGRuleId::ReadOrWrite, + TransformChildKind::OPTIONAL, + 2, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_BeginTransaction = {FRAME_CHILDREN_BeginTransaction, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_ReadOrWrite[] = {{PEGRuleId::ReadOnlyOrReadWrite, + TransformChildKind::REQUIRED, + 1, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_ReadOrWrite = {FRAME_CHILDREN_ReadOrWrite, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_UpdateStatement[] = {{PEGRuleId::ReturningClause, + TransformChildKind::OPTIONAL, + 6, + 5, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::WhereClause, + TransformChildKind::OPTIONAL, + 5, + 4, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::FromClause, + TransformChildKind::OPTIONAL, + 4, + 3, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::UpdateSetClauseList, + TransformChildKind::REQUIRED, + 3, + 2, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::UpdateTarget, + TransformChildKind::REQUIRED, + 2, + 1, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::WithClause, + TransformChildKind::OPTIONAL, + 0, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_UpdateStatement = {FRAME_CHILDREN_UpdateStatement, 6, 6, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_BaseTableAliasSet[] = {{PEGRuleId::UpdateAlias, + TransformChildKind::OPTIONAL, + 1, + 1, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::BaseTableName, + TransformChildKind::REQUIRED, + 0, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_BaseTableAliasSet = {FRAME_CHILDREN_BaseTableAliasSet, 2, 2, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_UpdateSetClauseList[] = {{PEGRuleId::UpdateSetClause, + TransformChildKind::LIST, + 0, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_UpdateSetClauseList = { + FRAME_CHILDREN_UpdateSetClauseList, 1, 1, true, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_UpdateSetElement[] = {{PEGRuleId::Expression, + TransformChildKind::REQUIRED, + 2, + 1, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::UpdateSetColumnTarget, + TransformChildKind::REQUIRED, + 0, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_UpdateSetElement = {FRAME_CHILDREN_UpdateSetElement, 2, 2, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_UpdateSetColumnTarget[] = {{PEGRuleId::DotIdentifier, + TransformChildKind::OPTIONAL_REPEAT, + 1, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_UpdateSetColumnTarget = { + FRAME_CHILDREN_UpdateSetColumnTarget, 1, 1, true, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_UseStatement[] = {{PEGRuleId::UseTarget, + TransformChildKind::REQUIRED, + 1, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_UseStatement = {FRAME_CHILDREN_UseStatement, 1, 1, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_UseTargetCatalogSchema[] = {{PEGRuleId::DotIdentifier, + TransformChildKind::OPTIONAL_REPEAT, + 3, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_UseTargetCatalogSchema = { + FRAME_CHILDREN_UseTargetCatalogSchema, 1, 1, true, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_VacuumStatement[] = {{PEGRuleId::AnalyzeTarget, + TransformChildKind::OPTIONAL, + 2, + 1, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::VacuumOptions, + TransformChildKind::OPTIONAL, + 1, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_VacuumStatement = {FRAME_CHILDREN_VacuumStatement, 2, 2, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_VacuumParensOptions[] = {{PEGRuleId::VacuumOption, + TransformChildKind::LIST, + 0, + 0, + false, + {1, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_VacuumParensOptions = { + FRAME_CHILDREN_VacuumParensOptions, 1, 1, true, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_VacuumLegacyOptions[] = {{PEGRuleId::OptAnalyze, + TransformChildKind::OPTIONAL, + 3, + 3, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::OptVerbose, + TransformChildKind::OPTIONAL, + 2, + 2, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::OptFreeze, + TransformChildKind::OPTIONAL, + 1, + 1, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::OptFull, + TransformChildKind::OPTIONAL, + 0, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_VacuumLegacyOptions = { + FRAME_CHILDREN_VacuumLegacyOptions, 4, 4, false, 0, {}}; +static const TransformChildPlan FRAME_CHILDREN_OptAnalyze[] = {{PEGRuleId::AnalyzeKeyword, + TransformChildKind::REQUIRED, + 0, + 0, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}}; +static const TransformFramePlan FRAME_PLAN_OptAnalyze = {FRAME_CHILDREN_OptAnalyze, 1, 1, false, 0, {}}; static const TransformFrameOps GENERATED_FRAME_OPS[] = { {"Statement", &PEGTransformerFactory::InitializeStatementTrampoline, @@ -7113,2347 +7291,2377 @@ static const TransformFrameOps GENERATED_FRAME_OPS[] = { {"SettingName", &PEGTransformerFactory::InitializeIdentifierOrKeywordTrampoline, &PEGTransformerFactory::FinalizeIdentifierOrKeywordTrampoline, nullptr}, {"AlterStatement", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeAlterStatementTrampoline, &FRAME_PLAN_0}, + &PEGTransformerFactory::FinalizeAlterStatementTrampoline, &FRAME_PLAN_AlterStatement}, {"AlterOptions", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, - &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, + &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_ChoiceThrow}, {"AlterTableStmt", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeAlterTableStmtTrampoline, &FRAME_PLAN_2}, + &PEGTransformerFactory::FinalizeAlterTableStmtTrampoline, &FRAME_PLAN_AlterTableStmt}, {"AlterSchemaStmt", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeAlterSchemaStmtTrampoline, &FRAME_PLAN_3}, + &PEGTransformerFactory::FinalizeAlterSchemaStmtTrampoline, &FRAME_PLAN_AlterSchemaStmt}, {"AlterSchemaOptions", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, - &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, + &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_ChoiceThrow}, {"AlterTableOptions", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, - &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, + &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_ChoiceThrow}, {"AddConstraint", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeAddConstraintTrampoline, &FRAME_PLAN_4}, + &PEGTransformerFactory::FinalizeAddConstraintTrampoline, &FRAME_PLAN_AddConstraint}, {"DropConstraint", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeDropConstraintTrampoline, &FRAME_PLAN_5}, + &PEGTransformerFactory::FinalizeDropConstraintTrampoline, &FRAME_PLAN_DropConstraint}, {"AddColumn", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeAddColumnTrampoline, &FRAME_PLAN_6}, + &PEGTransformerFactory::FinalizeAddColumnTrampoline, &FRAME_PLAN_AddColumn}, {"AddColumnEntry", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeAddColumnEntryTrampoline, &FRAME_PLAN_7}, + &PEGTransformerFactory::FinalizeAddColumnEntryTrampoline, &FRAME_PLAN_AddColumnEntry}, {"DropColumn", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeDropColumnTrampoline, &FRAME_PLAN_8}, + &PEGTransformerFactory::FinalizeDropColumnTrampoline, &FRAME_PLAN_DropColumn}, {"AlterColumn", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeAlterColumnTrampoline, &FRAME_PLAN_9}, + &PEGTransformerFactory::FinalizeAlterColumnTrampoline, &FRAME_PLAN_AlterColumn}, {"RenameColumn", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeRenameColumnTrampoline, &FRAME_PLAN_10}, + &PEGTransformerFactory::FinalizeRenameColumnTrampoline, &FRAME_PLAN_RenameColumn}, {"NestedColumnName", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeNestedColumnNameTrampoline, &FRAME_PLAN_11}, + &PEGTransformerFactory::FinalizeNestedColumnNameTrampoline, &FRAME_PLAN_NestedColumnName}, {"IdentifierDot", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeIdentifierDotTrampoline, &FRAME_PLAN_12}, + &PEGTransformerFactory::FinalizeIdentifierDotTrampoline, &FRAME_PLAN_Leaf}, {"RenameAlter", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeRenameAlterTrampoline, &FRAME_PLAN_13}, + &PEGTransformerFactory::FinalizeRenameAlterTrampoline, &FRAME_PLAN_ColumnCompression}, {"SetPartitionedBy", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeSetPartitionedByTrampoline, &FRAME_PLAN_14}, + &PEGTransformerFactory::FinalizeSetPartitionedByTrampoline, &FRAME_PLAN_SetPartitionedBy}, {"ResetPartitionedBy", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeResetPartitionedByTrampoline, &FRAME_PLAN_12}, + &PEGTransformerFactory::FinalizeResetPartitionedByTrampoline, &FRAME_PLAN_Leaf}, {"SetSortedBy", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeSetSortedByTrampoline, &FRAME_PLAN_15}, + &PEGTransformerFactory::FinalizeSetSortedByTrampoline, &FRAME_PLAN_SetSortedBy}, {"ResetSortedBy", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeResetSortedByTrampoline, &FRAME_PLAN_12}, + &PEGTransformerFactory::FinalizeResetSortedByTrampoline, &FRAME_PLAN_Leaf}, {"SetOptions", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeSetOptionsTrampoline, &FRAME_PLAN_16}, + &PEGTransformerFactory::FinalizeSetOptionsTrampoline, &FRAME_PLAN_ResetOptions}, {"ResetOptions", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeResetOptionsTrampoline, &FRAME_PLAN_16}, + &PEGTransformerFactory::FinalizeResetOptionsTrampoline, &FRAME_PLAN_ResetOptions}, {"AlterColumnEntry", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, - &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, + &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_ChoiceThrow}, {"AddOrDropDefault", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, - &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, + &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_ChoiceThrow}, {"AddDefault", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeAddDefaultTrampoline, &FRAME_PLAN_17}, + &PEGTransformerFactory::FinalizeAddDefaultTrampoline, &FRAME_PLAN_AddDefault}, {"DropDefault", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeDropDefaultTrampoline, &FRAME_PLAN_12}, + &PEGTransformerFactory::FinalizeDropDefaultTrampoline, &FRAME_PLAN_Leaf}, {"ChangeNullability", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeChangeNullabilityTrampoline, &FRAME_PLAN_18}, + &PEGTransformerFactory::FinalizeChangeNullabilityTrampoline, &FRAME_PLAN_ChangeNullability}, {"DropOrSet", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, - &PEGTransformerFactory::FinalizeDropOrSetTrampoline, &FRAME_PLAN_19}, + &PEGTransformerFactory::FinalizeDropOrSetTrampoline, &FRAME_PLAN_ChoiceEarlyIdentifierKeywordStringOperatorThrow}, {"DropNullability", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeDropNullabilityTrampoline, &FRAME_PLAN_12}, + &PEGTransformerFactory::FinalizeDropNullabilityTrampoline, &FRAME_PLAN_Leaf}, {"SetNullability", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeSetNullabilityTrampoline, &FRAME_PLAN_12}, + &PEGTransformerFactory::FinalizeSetNullabilityTrampoline, &FRAME_PLAN_Leaf}, {"AlterType", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeAlterTypeTrampoline, &FRAME_PLAN_20}, + &PEGTransformerFactory::FinalizeAlterTypeTrampoline, &FRAME_PLAN_AlterType}, {"UsingExpression", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeUsingExpressionTrampoline, &FRAME_PLAN_21}, + &PEGTransformerFactory::FinalizeUsingExpressionTrampoline, &FRAME_PLAN_AndExpression}, {"AlterViewStmt", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeAlterViewStmtTrampoline, &FRAME_PLAN_22}, + &PEGTransformerFactory::FinalizeAlterViewStmtTrampoline, &FRAME_PLAN_AlterViewStmt}, {"AlterSequenceStmt", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeAlterSequenceStmtTrampoline, &FRAME_PLAN_23}, + &PEGTransformerFactory::FinalizeAlterSequenceStmtTrampoline, &FRAME_PLAN_AlterSequenceStmt}, {"QualifiedSequenceName", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeQualifiedSequenceNameTrampoline, &FRAME_PLAN_24}, + &PEGTransformerFactory::FinalizeQualifiedSequenceNameTrampoline, &FRAME_PLAN_QualifiedSequenceName}, {"AlterSequenceOptions", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, - &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, + &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_ChoiceThrow}, {"RenameAlterSequenceOptions", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeRenameAlterSequenceOptionsTrampoline, &FRAME_PLAN_25}, + &PEGTransformerFactory::FinalizeRenameAlterSequenceOptionsTrampoline, &FRAME_PLAN_RenameAlterSequenceOptions}, {"SetSequenceOption", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeSetSequenceOptionTrampoline, &FRAME_PLAN_26}, + &PEGTransformerFactory::FinalizeSetSequenceOptionTrampoline, &FRAME_PLAN_SetSequenceOption}, {"AlterDatabaseStmt", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeAlterDatabaseStmtTrampoline, &FRAME_PLAN_27}, + &PEGTransformerFactory::FinalizeAlterDatabaseStmtTrampoline, &FRAME_PLAN_AlterDatabaseStmt}, {"AnalyzeStatement", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeAnalyzeStatementTrampoline, &FRAME_PLAN_28}, + &PEGTransformerFactory::FinalizeAnalyzeStatementTrampoline, &FRAME_PLAN_AnalyzeStatement}, {"AnalyzeTarget", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeAnalyzeTargetTrampoline, &FRAME_PLAN_29}, + &PEGTransformerFactory::FinalizeAnalyzeTargetTrampoline, &FRAME_PLAN_AnalyzeTarget}, {"AnalyzeVerbose", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeAnalyzeVerboseTrampoline, &FRAME_PLAN_12}, + &PEGTransformerFactory::FinalizeAnalyzeVerboseTrampoline, &FRAME_PLAN_Leaf}, {"AttachStatement", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeAttachStatementTrampoline, &FRAME_PLAN_30}, + &PEGTransformerFactory::FinalizeAttachStatementTrampoline, &FRAME_PLAN_AttachStatement}, {"DatabasePath", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeDatabasePathTrampoline, &FRAME_PLAN_31}, + &PEGTransformerFactory::FinalizeDatabasePathTrampoline, &FRAME_PLAN_DatabasePath}, {"AttachAlias", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeAttachAliasTrampoline, &FRAME_PLAN_32}, + &PEGTransformerFactory::FinalizeAttachAliasTrampoline, &FRAME_PLAN_AttachAlias}, {"AttachOptions", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeAttachOptionsTrampoline, &FRAME_PLAN_33}, + &PEGTransformerFactory::FinalizeAttachOptionsTrampoline, &FRAME_PLAN_AttachOptions}, {"CallStatement", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeCallStatementTrampoline, &FRAME_PLAN_34}, + &PEGTransformerFactory::FinalizeCallStatementTrampoline, &FRAME_PLAN_CallStatement}, {"CheckpointStatement", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeCheckpointStatementTrampoline, &FRAME_PLAN_35}, + &PEGTransformerFactory::FinalizeCheckpointStatementTrampoline, &FRAME_PLAN_CheckpointStatement}, {"CheckpointForce", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeCheckpointForceTrampoline, &FRAME_PLAN_12}, + &PEGTransformerFactory::FinalizeCheckpointForceTrampoline, &FRAME_PLAN_Leaf}, {"CommentStatement", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeCommentStatementTrampoline, &FRAME_PLAN_36}, + &PEGTransformerFactory::FinalizeCommentStatementTrampoline, &FRAME_PLAN_CommentStatement}, {"CommentTarget", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, - &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, + &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_ChoiceThrow}, {"CommentStringLiteralIdentifier", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeCommentStringLiteralIdentifierTrampoline, &FRAME_PLAN_37}, + &PEGTransformerFactory::FinalizeCommentStringLiteralIdentifierTrampoline, + &FRAME_PLAN_CommentStringLiteralIdentifier}, {"CommentOnType", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, - &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, + &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_ChoiceThrow}, {"CommentTable", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeCommentTableTrampoline, &FRAME_PLAN_12}, + &PEGTransformerFactory::FinalizeCommentTableTrampoline, &FRAME_PLAN_Leaf}, {"CommentSequence", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeCommentSequenceTrampoline, &FRAME_PLAN_12}, + &PEGTransformerFactory::FinalizeCommentSequenceTrampoline, &FRAME_PLAN_Leaf}, {"CommentFunction", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeCommentFunctionTrampoline, &FRAME_PLAN_12}, + &PEGTransformerFactory::FinalizeCommentFunctionTrampoline, &FRAME_PLAN_Leaf}, {"CommentMacroTable", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeCommentMacroTableTrampoline, &FRAME_PLAN_12}, + &PEGTransformerFactory::FinalizeCommentMacroTableTrampoline, &FRAME_PLAN_Leaf}, {"CommentMacro", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeCommentMacroTrampoline, &FRAME_PLAN_12}, + &PEGTransformerFactory::FinalizeCommentMacroTrampoline, &FRAME_PLAN_Leaf}, {"CommentView", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeCommentViewTrampoline, &FRAME_PLAN_12}, + &PEGTransformerFactory::FinalizeCommentViewTrampoline, &FRAME_PLAN_Leaf}, {"CommentDatabase", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeCommentDatabaseTrampoline, &FRAME_PLAN_12}, + &PEGTransformerFactory::FinalizeCommentDatabaseTrampoline, &FRAME_PLAN_Leaf}, {"CommentIndex", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeCommentIndexTrampoline, &FRAME_PLAN_12}, + &PEGTransformerFactory::FinalizeCommentIndexTrampoline, &FRAME_PLAN_Leaf}, {"CommentSchema", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeCommentSchemaTrampoline, &FRAME_PLAN_12}, + &PEGTransformerFactory::FinalizeCommentSchemaTrampoline, &FRAME_PLAN_Leaf}, {"CommentType", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeCommentTypeTrampoline, &FRAME_PLAN_12}, + &PEGTransformerFactory::FinalizeCommentTypeTrampoline, &FRAME_PLAN_Leaf}, {"CommentColumn", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeCommentColumnTrampoline, &FRAME_PLAN_12}, + &PEGTransformerFactory::FinalizeCommentColumnTrampoline, &FRAME_PLAN_Leaf}, {"CommentValue", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, - &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, + &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_ChoiceThrow}, {"StringLiteralValue", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeStringLiteralValueTrampoline, &FRAME_PLAN_12}, + &PEGTransformerFactory::FinalizeStringLiteralValueTrampoline, &FRAME_PLAN_Leaf}, {"AnalyzeKeyword", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeAnalyzeKeywordTrampoline, &FRAME_PLAN_12}, + &PEGTransformerFactory::FinalizeAnalyzeKeywordTrampoline, &FRAME_PLAN_Leaf}, {"IndexName", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeIndexNameTrampoline, &FRAME_PLAN_12}, + &PEGTransformerFactory::FinalizeIndexNameTrampoline, &FRAME_PLAN_Leaf}, {"ConstraintName", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeConstraintNameTrampoline, &FRAME_PLAN_38}, + &PEGTransformerFactory::FinalizeConstraintNameTrampoline, &FRAME_PLAN_ConstraintName}, {"SequenceName", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeSequenceNameTrampoline, &FRAME_PLAN_12}, + &PEGTransformerFactory::FinalizeSequenceNameTrampoline, &FRAME_PLAN_Leaf}, {"CollationName", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeCollationNameTrampoline, &FRAME_PLAN_12}, + &PEGTransformerFactory::FinalizeCollationNameTrampoline, &FRAME_PLAN_Leaf}, {"NumberLiteral", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeNumberLiteralTrampoline, &FRAME_PLAN_12}, + &PEGTransformerFactory::FinalizeNumberLiteralTrampoline, &FRAME_PLAN_Leaf}, {"StringLiteral", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeStringLiteralTrampoline, &FRAME_PLAN_12}, + &PEGTransformerFactory::FinalizeStringLiteralTrampoline, &FRAME_PLAN_Leaf}, {"Type", &PEGTransformerFactory::InitializePlannedTrampoline, &PEGTransformerFactory::FinalizeTypeTrampoline, - &FRAME_PLAN_39}, + &FRAME_PLAN_NestedType}, {"TypeVariations", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, - &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, + &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_ChoiceThrow}, {"SimpleType", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, - &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, + &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_ChoiceThrow}, {"CharacterSimpleType", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeCharacterSimpleTypeTrampoline, &FRAME_PLAN_40}, + &PEGTransformerFactory::FinalizeCharacterSimpleTypeTrampoline, &FRAME_PLAN_CharacterSimpleType}, {"QualifiedSimpleType", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeQualifiedSimpleTypeTrampoline, &FRAME_PLAN_41}, + &PEGTransformerFactory::FinalizeQualifiedSimpleTypeTrampoline, &FRAME_PLAN_QualifiedSimpleType}, {"IntervalType", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, - &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, + &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_ChoiceThrow}, {"IntervalInterval", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, - &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, + &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_ChoiceThrow}, {"IntervalWithSpecifier", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, - &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, + &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_ChoiceThrow}, {"IntervalWithRangeSpecifier", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeIntervalWithRangeSpecifierTrampoline, &FRAME_PLAN_42}, + &PEGTransformerFactory::FinalizeIntervalWithRangeSpecifierTrampoline, &FRAME_PLAN_IntervalWithRangeSpecifier}, {"IntervalWithSimpleSpecifier", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeIntervalWithSimpleSpecifierTrampoline, &FRAME_PLAN_43}, + &PEGTransformerFactory::FinalizeIntervalWithSimpleSpecifierTrampoline, &FRAME_PLAN_IntervalWithSimpleSpecifier}, {"IntervalWithoutSpecifier", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeIntervalWithoutSpecifierTrampoline, &FRAME_PLAN_12}, + &PEGTransformerFactory::FinalizeIntervalWithoutSpecifierTrampoline, &FRAME_PLAN_Leaf}, {"IntervalToIntervalAsType", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, - &PEGTransformerFactory::FinalizeIntervalToIntervalAsTypeTrampoline, &FRAME_PLAN_44}, + &PEGTransformerFactory::FinalizeIntervalToIntervalAsTypeTrampoline, &FRAME_PLAN_Choice}, {"YearKeyword", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeYearKeywordTrampoline, &FRAME_PLAN_12}, + &PEGTransformerFactory::FinalizeYearKeywordTrampoline, &FRAME_PLAN_Leaf}, {"MonthKeyword", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeMonthKeywordTrampoline, &FRAME_PLAN_12}, + &PEGTransformerFactory::FinalizeMonthKeywordTrampoline, &FRAME_PLAN_Leaf}, {"DayKeyword", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeDayKeywordTrampoline, &FRAME_PLAN_12}, + &PEGTransformerFactory::FinalizeDayKeywordTrampoline, &FRAME_PLAN_Leaf}, {"HourKeyword", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeHourKeywordTrampoline, &FRAME_PLAN_12}, + &PEGTransformerFactory::FinalizeHourKeywordTrampoline, &FRAME_PLAN_Leaf}, {"MinuteKeyword", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeMinuteKeywordTrampoline, &FRAME_PLAN_12}, + &PEGTransformerFactory::FinalizeMinuteKeywordTrampoline, &FRAME_PLAN_Leaf}, {"SecondKeyword", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeSecondKeywordTrampoline, &FRAME_PLAN_12}, + &PEGTransformerFactory::FinalizeSecondKeywordTrampoline, &FRAME_PLAN_Leaf}, {"MillisecondKeyword", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeMillisecondKeywordTrampoline, &FRAME_PLAN_12}, + &PEGTransformerFactory::FinalizeMillisecondKeywordTrampoline, &FRAME_PLAN_Leaf}, {"MicrosecondKeyword", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeMicrosecondKeywordTrampoline, &FRAME_PLAN_12}, + &PEGTransformerFactory::FinalizeMicrosecondKeywordTrampoline, &FRAME_PLAN_Leaf}, {"WeekKeyword", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeWeekKeywordTrampoline, &FRAME_PLAN_12}, + &PEGTransformerFactory::FinalizeWeekKeywordTrampoline, &FRAME_PLAN_Leaf}, {"QuarterKeyword", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeQuarterKeywordTrampoline, &FRAME_PLAN_12}, + &PEGTransformerFactory::FinalizeQuarterKeywordTrampoline, &FRAME_PLAN_Leaf}, {"DecadeKeyword", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeDecadeKeywordTrampoline, &FRAME_PLAN_12}, + &PEGTransformerFactory::FinalizeDecadeKeywordTrampoline, &FRAME_PLAN_Leaf}, {"CenturyKeyword", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeCenturyKeywordTrampoline, &FRAME_PLAN_12}, + &PEGTransformerFactory::FinalizeCenturyKeywordTrampoline, &FRAME_PLAN_Leaf}, {"MillenniumKeyword", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeMillenniumKeywordTrampoline, &FRAME_PLAN_12}, + &PEGTransformerFactory::FinalizeMillenniumKeywordTrampoline, &FRAME_PLAN_Leaf}, {"Interval", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, - &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, + &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_ChoiceThrow}, {"IntervalToInterval", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, - &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, + &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_ChoiceThrow}, {"YearToMonth", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeYearToMonthTrampoline, &FRAME_PLAN_45}, + &PEGTransformerFactory::FinalizeYearToMonthTrampoline, &FRAME_PLAN_YearToMonth}, {"DayToHour", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeDayToHourTrampoline, &FRAME_PLAN_46}, + &PEGTransformerFactory::FinalizeDayToHourTrampoline, &FRAME_PLAN_DayToHour}, {"DayToMinute", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeDayToMinuteTrampoline, &FRAME_PLAN_47}, + &PEGTransformerFactory::FinalizeDayToMinuteTrampoline, &FRAME_PLAN_DayToMinute}, {"DayToSecond", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeDayToSecondTrampoline, &FRAME_PLAN_48}, + &PEGTransformerFactory::FinalizeDayToSecondTrampoline, &FRAME_PLAN_DayToSecond}, {"HourToMinute", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeHourToMinuteTrampoline, &FRAME_PLAN_49}, + &PEGTransformerFactory::FinalizeHourToMinuteTrampoline, &FRAME_PLAN_HourToMinute}, {"HourToSecond", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeHourToSecondTrampoline, &FRAME_PLAN_50}, + &PEGTransformerFactory::FinalizeHourToSecondTrampoline, &FRAME_PLAN_HourToSecond}, {"MinuteToSecond", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeMinuteToSecondTrampoline, &FRAME_PLAN_51}, + &PEGTransformerFactory::FinalizeMinuteToSecondTrampoline, &FRAME_PLAN_MinuteToSecond}, {"BitType", &PEGTransformerFactory::InitializePlannedTrampoline, &PEGTransformerFactory::FinalizeBitTypeTrampoline, - &FRAME_PLAN_52}, + &FRAME_PLAN_BitType}, {"GeometryType", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeGeometryTypeTrampoline, &FRAME_PLAN_53}, + &PEGTransformerFactory::FinalizeGeometryTypeTrampoline, &FRAME_PLAN_GeometryType}, {"VariantType", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeVariantTypeTrampoline, &FRAME_PLAN_12}, + &PEGTransformerFactory::FinalizeVariantTypeTrampoline, &FRAME_PLAN_Leaf}, {"NumericType", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, - &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, + &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_ChoiceThrow}, {"SimpleNumericType", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, - &PEGTransformerFactory::FinalizeSimpleNumericTypeTrampoline, &FRAME_PLAN_54}, + &PEGTransformerFactory::FinalizeSimpleNumericTypeTrampoline, + &FRAME_PLAN_ChoiceFallbackIdentifierKeywordStringOperatorChoiceListThrow}, {"DecimalNumericType", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, - &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, + &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_ChoiceThrow}, {"IntType", &PEGTransformerFactory::InitializePlannedTrampoline, &PEGTransformerFactory::FinalizeIntTypeTrampoline, - &FRAME_PLAN_12}, + &FRAME_PLAN_Leaf}, {"IntegerType", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeIntegerTypeTrampoline, &FRAME_PLAN_12}, + &PEGTransformerFactory::FinalizeIntegerTypeTrampoline, &FRAME_PLAN_Leaf}, {"SmallintType", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeSmallintTypeTrampoline, &FRAME_PLAN_12}, + &PEGTransformerFactory::FinalizeSmallintTypeTrampoline, &FRAME_PLAN_Leaf}, {"BigintType", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeBigintTypeTrampoline, &FRAME_PLAN_12}, + &PEGTransformerFactory::FinalizeBigintTypeTrampoline, &FRAME_PLAN_Leaf}, {"RealType", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeRealTypeTrampoline, &FRAME_PLAN_12}, + &PEGTransformerFactory::FinalizeRealTypeTrampoline, &FRAME_PLAN_Leaf}, {"BooleanType", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeBooleanTypeTrampoline, &FRAME_PLAN_12}, + &PEGTransformerFactory::FinalizeBooleanTypeTrampoline, &FRAME_PLAN_Leaf}, {"DoubleType", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeDoubleTypeTrampoline, &FRAME_PLAN_12}, + &PEGTransformerFactory::FinalizeDoubleTypeTrampoline, &FRAME_PLAN_Leaf}, {"FloatType", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeFloatTypeTrampoline, &FRAME_PLAN_12}, + &PEGTransformerFactory::FinalizeFloatTypeTrampoline, &FRAME_PLAN_Leaf}, {"DecimalType", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeDecimalTypeTrampoline, &FRAME_PLAN_40}, + &PEGTransformerFactory::FinalizeDecimalTypeTrampoline, &FRAME_PLAN_CharacterSimpleType}, {"DecType", &PEGTransformerFactory::InitializePlannedTrampoline, &PEGTransformerFactory::FinalizeDecTypeTrampoline, - &FRAME_PLAN_40}, + &FRAME_PLAN_CharacterSimpleType}, {"NumericModType", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeNumericModTypeTrampoline, &FRAME_PLAN_40}, + &PEGTransformerFactory::FinalizeNumericModTypeTrampoline, &FRAME_PLAN_CharacterSimpleType}, {"QualifiedTypeName", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, - &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, + &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_ChoiceThrow}, {"TypeNameAsQualifiedName", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeTypeNameAsQualifiedNameTrampoline, &FRAME_PLAN_12}, + &PEGTransformerFactory::FinalizeTypeNameAsQualifiedNameTrampoline, &FRAME_PLAN_Leaf}, {"CatalogReservedSchemaTypeName", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeCatalogReservedSchemaTypeNameTrampoline, &FRAME_PLAN_55}, + &PEGTransformerFactory::FinalizeCatalogReservedSchemaTypeNameTrampoline, &FRAME_PLAN_CatalogReservedSchemaIndex}, {"SchemaReservedTypeName", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeSchemaReservedTypeNameTrampoline, &FRAME_PLAN_56}, + &PEGTransformerFactory::FinalizeSchemaReservedTypeNameTrampoline, &FRAME_PLAN_SchemaReservedFunctionName}, {"TypeModifiers", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeTypeModifiersTrampoline, &FRAME_PLAN_57}, + &PEGTransformerFactory::FinalizeTypeModifiersTrampoline, &FRAME_PLAN_ParenthesisExpression}, {"NestedType", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeNestedTypeTrampoline, &FRAME_PLAN_39}, + &PEGTransformerFactory::FinalizeNestedTypeTrampoline, &FRAME_PLAN_NestedType}, {"RowType", &PEGTransformerFactory::InitializePlannedTrampoline, &PEGTransformerFactory::FinalizeRowTypeTrampoline, - &FRAME_PLAN_58}, + &FRAME_PLAN_RowType}, {"SetofType", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeSetofTypeTrampoline, &FRAME_PLAN_59}, + &PEGTransformerFactory::FinalizeSetofTypeTrampoline, &FRAME_PLAN_SetofType}, {"UnionType", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeUnionTypeTrampoline, &FRAME_PLAN_60}, + &PEGTransformerFactory::FinalizeUnionTypeTrampoline, &FRAME_PLAN_UnionType}, {"ColIdTypeList", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeColIdTypeListTrampoline, &FRAME_PLAN_61}, + &PEGTransformerFactory::FinalizeColIdTypeListTrampoline, &FRAME_PLAN_ColIdTypeList}, {"MapType", &PEGTransformerFactory::InitializePlannedTrampoline, &PEGTransformerFactory::FinalizeMapTypeTrampoline, - &FRAME_PLAN_62}, + &FRAME_PLAN_MapType}, {"TupleType", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeTupleTypeTrampoline, &FRAME_PLAN_63}, + &PEGTransformerFactory::FinalizeTupleTypeTrampoline, &FRAME_PLAN_TupleType}, {"ColIdType", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeColIdTypeTrampoline, &FRAME_PLAN_64}, + &PEGTransformerFactory::FinalizeColIdTypeTrampoline, &FRAME_PLAN_ColIdType}, {"ArrayBounds", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, - &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, + &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_ChoiceThrow}, {"ArrayKeyword", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeArrayKeywordTrampoline, &FRAME_PLAN_12}, + &PEGTransformerFactory::FinalizeArrayKeywordTrampoline, &FRAME_PLAN_Leaf}, {"ArrayKeywordWithBounds", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeArrayKeywordWithBoundsTrampoline, &FRAME_PLAN_65}, + &PEGTransformerFactory::FinalizeArrayKeywordWithBoundsTrampoline, &FRAME_PLAN_ArrayKeywordWithBounds}, {"SquareBracketsArray", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeSquareBracketsArrayTrampoline, &FRAME_PLAN_66}, + &PEGTransformerFactory::FinalizeSquareBracketsArrayTrampoline, &FRAME_PLAN_EndSliceBound}, {"TimeType", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeTimeTypeTrampoline, &FRAME_PLAN_67}, + &PEGTransformerFactory::FinalizeTimeTypeTrampoline, &FRAME_PLAN_TimeType}, {"TimeOrTimestamp", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, - &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, + &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_ChoiceThrow}, {"TimeTypeId", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeTimeTypeIdTrampoline, &FRAME_PLAN_12}, + &PEGTransformerFactory::FinalizeTimeTypeIdTrampoline, &FRAME_PLAN_Leaf}, {"TimestampTypeId", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeTimestampTypeIdTrampoline, &FRAME_PLAN_12}, + &PEGTransformerFactory::FinalizeTimestampTypeIdTrampoline, &FRAME_PLAN_Leaf}, {"TimeZone", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeTimeZoneTrampoline, &FRAME_PLAN_68}, + &PEGTransformerFactory::FinalizeTimeZoneTrampoline, &FRAME_PLAN_TimeZone}, {"WithOrWithout", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, - &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, + &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_ChoiceThrow}, {"WithRule", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeWithRuleTrampoline, &FRAME_PLAN_12}, + &PEGTransformerFactory::FinalizeWithRuleTrampoline, &FRAME_PLAN_Leaf}, {"WithoutRule", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeWithoutRuleTrampoline, &FRAME_PLAN_12}, + &PEGTransformerFactory::FinalizeWithoutRuleTrampoline, &FRAME_PLAN_Leaf}, {"ConnectStatement", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeConnectStatementTrampoline, &FRAME_PLAN_69}, + &PEGTransformerFactory::FinalizeConnectStatementTrampoline, &FRAME_PLAN_ConnectStatement}, {"DisconnectStatement", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeDisconnectStatementTrampoline, &FRAME_PLAN_12}, + &PEGTransformerFactory::FinalizeDisconnectStatementTrampoline, &FRAME_PLAN_Leaf}, {"SessionTarget", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, - &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, + &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_ChoiceThrow}, {"LocalSessionTarget", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeLocalSessionTargetTrampoline, &FRAME_PLAN_12}, + &PEGTransformerFactory::FinalizeLocalSessionTargetTrampoline, &FRAME_PLAN_Leaf}, {"StringSessionTarget", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeStringSessionTargetTrampoline, &FRAME_PLAN_70}, + &PEGTransformerFactory::FinalizeStringSessionTargetTrampoline, &FRAME_PLAN_StringSessionTarget}, {"CatalogSessionTarget", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeCatalogSessionTargetTrampoline, &FRAME_PLAN_12}, + &PEGTransformerFactory::FinalizeCatalogSessionTargetTrampoline, &FRAME_PLAN_Leaf}, {"CopyStatement", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeCopyStatementTrampoline, &FRAME_PLAN_71}, + &PEGTransformerFactory::FinalizeCopyStatementTrampoline, &FRAME_PLAN_CopyStatement}, {"CopyVariations", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, - &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, + &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_ChoiceThrow}, {"CopyTable", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeCopyTableTrampoline, &FRAME_PLAN_72}, + &PEGTransformerFactory::FinalizeCopyTableTrampoline, &FRAME_PLAN_CopyTable}, {"FromOrTo", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, - &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, + &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_ChoiceThrow}, {"CopyFrom", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeCopyFromTrampoline, &FRAME_PLAN_12}, + &PEGTransformerFactory::FinalizeCopyFromTrampoline, &FRAME_PLAN_Leaf}, {"CopyTo", &PEGTransformerFactory::InitializePlannedTrampoline, &PEGTransformerFactory::FinalizeCopyToTrampoline, - &FRAME_PLAN_12}, + &FRAME_PLAN_Leaf}, {"CopySelect", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeCopySelectTrampoline, &FRAME_PLAN_73}, + &PEGTransformerFactory::FinalizeCopySelectTrampoline, &FRAME_PLAN_CopySelect}, {"CopyFileName", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, - &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, + &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_ChoiceThrow}, {"CopyFileNameExpression", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, - &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, + &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_ChoiceThrow}, {"CopyFileNameStringLiteral", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeCopyFileNameStringLiteralTrampoline, &FRAME_PLAN_12}, + &PEGTransformerFactory::FinalizeCopyFileNameStringLiteralTrampoline, &FRAME_PLAN_Leaf}, {"CopyFileNameIdentifier", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeCopyFileNameIdentifierTrampoline, &FRAME_PLAN_12}, + &PEGTransformerFactory::FinalizeCopyFileNameIdentifierTrampoline, &FRAME_PLAN_Leaf}, {"CopyFileNameIdentifierColId", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeCopyFileNameIdentifierColIdTrampoline, &FRAME_PLAN_74}, + &PEGTransformerFactory::FinalizeCopyFileNameIdentifierColIdTrampoline, &FRAME_PLAN_CopyFileNameIdentifierColId}, {"IdentifierColId", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeIdentifierColIdTrampoline, &FRAME_PLAN_75}, + &PEGTransformerFactory::FinalizeIdentifierColIdTrampoline, &FRAME_PLAN_IdentifierColId}, {"CopyFileNameSuffix", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_32}, + &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_AttachAlias}, {"CopyLegacyOption", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeCopyLegacyOptionTrampoline, &FRAME_PLAN_12}, + &PEGTransformerFactory::FinalizeCopyLegacyOptionTrampoline, &FRAME_PLAN_Leaf}, {"CopyOptions", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeCopyOptionsTrampoline, &FRAME_PLAN_76}, + &PEGTransformerFactory::FinalizeCopyOptionsTrampoline, &FRAME_PLAN_CopyOptions}, {"CopyOptionList", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, - &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, + &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_ChoiceThrow}, {"SpecializedOptionList", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeSpecializedOptionListTrampoline, &FRAME_PLAN_77}, + &PEGTransformerFactory::FinalizeSpecializedOptionListTrampoline, &FRAME_PLAN_SpecializedOptionList}, {"SpecializedOptionTail", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeSpecializedOptionTailTrampoline, &FRAME_PLAN_78}, + &PEGTransformerFactory::FinalizeSpecializedOptionTailTrampoline, &FRAME_PLAN_SpecializedOptionTail}, {"SpecializedOption", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, - &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, + &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_ChoiceThrow}, {"SingleOption", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, - &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, + &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_ChoiceThrow}, {"BinaryOption", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeBinaryOptionTrampoline, &FRAME_PLAN_12}, + &PEGTransformerFactory::FinalizeBinaryOptionTrampoline, &FRAME_PLAN_Leaf}, {"FreezeOption", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeFreezeOptionTrampoline, &FRAME_PLAN_12}, + &PEGTransformerFactory::FinalizeFreezeOptionTrampoline, &FRAME_PLAN_Leaf}, {"OidsOption", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeOidsOptionTrampoline, &FRAME_PLAN_12}, + &PEGTransformerFactory::FinalizeOidsOptionTrampoline, &FRAME_PLAN_Leaf}, {"CsvOption", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeCsvOptionTrampoline, &FRAME_PLAN_12}, + &PEGTransformerFactory::FinalizeCsvOptionTrampoline, &FRAME_PLAN_Leaf}, {"HeaderOption", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeHeaderOptionTrampoline, &FRAME_PLAN_12}, + &PEGTransformerFactory::FinalizeHeaderOptionTrampoline, &FRAME_PLAN_Leaf}, {"NullAsOption", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeNullAsOptionTrampoline, &FRAME_PLAN_12}, + &PEGTransformerFactory::FinalizeNullAsOptionTrampoline, &FRAME_PLAN_Leaf}, {"DelimiterAsOption", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeDelimiterAsOptionTrampoline, &FRAME_PLAN_12}, + &PEGTransformerFactory::FinalizeDelimiterAsOptionTrampoline, &FRAME_PLAN_Leaf}, {"QuoteAsOption", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeQuoteAsOptionTrampoline, &FRAME_PLAN_12}, + &PEGTransformerFactory::FinalizeQuoteAsOptionTrampoline, &FRAME_PLAN_Leaf}, {"EscapeAsOption", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeEscapeAsOptionTrampoline, &FRAME_PLAN_12}, + &PEGTransformerFactory::FinalizeEscapeAsOptionTrampoline, &FRAME_PLAN_Leaf}, {"EncodingOption", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeEncodingOptionTrampoline, &FRAME_PLAN_12}, + &PEGTransformerFactory::FinalizeEncodingOptionTrampoline, &FRAME_PLAN_Leaf}, {"ForceQuoteOption", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeForceQuoteOptionTrampoline, &FRAME_PLAN_79}, + &PEGTransformerFactory::FinalizeForceQuoteOptionTrampoline, &FRAME_PLAN_ForceQuoteOption}, {"StarSymbolColumnList", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, - &PEGTransformerFactory::FinalizeStarSymbolColumnListTrampoline, &FRAME_PLAN_80}, + &PEGTransformerFactory::FinalizeStarSymbolColumnListTrampoline, &FRAME_PLAN_StarSymbolColumnList}, {"ForceQuote", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeForceQuoteTrampoline, &FRAME_PLAN_12}, + &PEGTransformerFactory::FinalizeForceQuoteTrampoline, &FRAME_PLAN_Leaf}, {"PartitionByOption", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizePartitionByOptionTrampoline, &FRAME_PLAN_81}, + &PEGTransformerFactory::FinalizePartitionByOptionTrampoline, &FRAME_PLAN_PartitionByOption}, {"PartitionByColumnList", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, - &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, + &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_ChoiceThrow}, {"StarPartitionByColumnList", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeStarPartitionByColumnListTrampoline, &FRAME_PLAN_12}, + &PEGTransformerFactory::FinalizeStarPartitionByColumnListTrampoline, &FRAME_PLAN_Leaf}, {"ParenthesizedPartitionByColumnList", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeParenthesizedPartitionByColumnListTrampoline, &FRAME_PLAN_82}, + &PEGTransformerFactory::FinalizeParenthesizedPartitionByColumnListTrampoline, &FRAME_PLAN_InsertColumnList}, {"SinglePartitionByColumnList", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeSinglePartitionByColumnListTrampoline, &FRAME_PLAN_83}, + &PEGTransformerFactory::FinalizeSinglePartitionByColumnListTrampoline, &FRAME_PLAN_ColIdDot}, {"ForceNullOption", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeForceNullOptionTrampoline, &FRAME_PLAN_84}, + &PEGTransformerFactory::FinalizeForceNullOptionTrampoline, &FRAME_PLAN_ForceNullOption}, {"ForceNotNull", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeForceNotNullTrampoline, &FRAME_PLAN_12}, + &PEGTransformerFactory::FinalizeForceNotNullTrampoline, &FRAME_PLAN_Leaf}, {"CopyGenericOptionList", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeCopyGenericOptionListTrampoline, &FRAME_PLAN_85}, + &PEGTransformerFactory::FinalizeCopyGenericOptionListTrampoline, &FRAME_PLAN_CopyGenericOptionList}, {"CopyGenericOption", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, - &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, + &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_ChoiceThrow}, {"OrderByCopyOption", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeOrderByCopyOptionTrampoline, &FRAME_PLAN_86}, + &PEGTransformerFactory::FinalizeOrderByCopyOptionTrampoline, &FRAME_PLAN_OrderByCopyOption}, {"PartitionedByCopyOption", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizePartitionedByCopyOptionTrampoline, &FRAME_PLAN_86}, + &PEGTransformerFactory::FinalizePartitionedByCopyOptionTrampoline, &FRAME_PLAN_OrderByCopyOption}, {"GenericCopyOptionList", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeGenericCopyOptionListTrampoline, &FRAME_PLAN_87}, + &PEGTransformerFactory::FinalizeGenericCopyOptionListTrampoline, &FRAME_PLAN_GenericCopyOptionList}, {"GenericCopyOption", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeGenericCopyOptionTrampoline, &FRAME_PLAN_88}, + &PEGTransformerFactory::FinalizeGenericCopyOptionTrampoline, &FRAME_PLAN_GenericCopyOption}, {"GenericCopyOptionValue", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, - &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, + &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_ChoiceThrow}, {"GenericCopyOptionOrderList", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeGenericCopyOptionOrderListTrampoline, &FRAME_PLAN_89}, + &PEGTransformerFactory::FinalizeGenericCopyOptionOrderListTrampoline, &FRAME_PLAN_GenericCopyOptionOrderList}, {"GenericCopyOptionExpression", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeGenericCopyOptionExpressionTrampoline, &FRAME_PLAN_31}, + &PEGTransformerFactory::FinalizeGenericCopyOptionExpressionTrampoline, &FRAME_PLAN_DatabasePath}, {"GenericCopyOptionParenthesizedExpressionList", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeGenericCopyOptionParenthesizedExpressionListTrampoline, &FRAME_PLAN_90}, + &PEGTransformerFactory::FinalizeGenericCopyOptionParenthesizedExpressionListTrampoline, + &FRAME_PLAN_GenericCopyOptionParenthesizedExpressionList}, {"CopyFromDatabase", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, - &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, + &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_ChoiceThrow}, {"CopyFromDatabaseWithFlag", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeCopyFromDatabaseWithFlagTrampoline, &FRAME_PLAN_91}, + &PEGTransformerFactory::FinalizeCopyFromDatabaseWithFlagTrampoline, &FRAME_PLAN_CopyFromDatabaseWithFlag}, {"CopyFromDatabaseWithoutFlag", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeCopyFromDatabaseWithoutFlagTrampoline, &FRAME_PLAN_92}, + &PEGTransformerFactory::FinalizeCopyFromDatabaseWithoutFlagTrampoline, &FRAME_PLAN_CopyFromDatabaseWithoutFlag}, {"CopyDatabaseFlag", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeCopyDatabaseFlagTrampoline, &FRAME_PLAN_93}, + &PEGTransformerFactory::FinalizeCopyDatabaseFlagTrampoline, &FRAME_PLAN_CopyDatabaseFlag}, {"SchemaOrData", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, - &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, + &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_ChoiceThrow}, {"CopySchema", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeCopySchemaTrampoline, &FRAME_PLAN_12}, + &PEGTransformerFactory::FinalizeCopySchemaTrampoline, &FRAME_PLAN_Leaf}, {"CopyData", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeCopyDataTrampoline, &FRAME_PLAN_12}, + &PEGTransformerFactory::FinalizeCopyDataTrampoline, &FRAME_PLAN_Leaf}, {"CreateIndexStmt", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeCreateIndexStmtTrampoline, &FRAME_PLAN_94}, + &PEGTransformerFactory::FinalizeCreateIndexStmtTrampoline, &FRAME_PLAN_CreateIndexStmt}, {"WithList", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeWithListTrampoline, &FRAME_PLAN_95}, + &PEGTransformerFactory::FinalizeWithListTrampoline, &FRAME_PLAN_WithList}, {"RelOptionOrOids", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, - &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, + &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_ChoiceThrow}, {"RelOptionList", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeRelOptionListTrampoline, &FRAME_PLAN_96}, + &PEGTransformerFactory::FinalizeRelOptionListTrampoline, &FRAME_PLAN_RelOptionList}, {"Oids", &PEGTransformerFactory::InitializePlannedTrampoline, &PEGTransformerFactory::FinalizeOidsTrampoline, - &FRAME_PLAN_97}, + &FRAME_PLAN_Oids}, {"WithOrWithoutOids", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, - &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, + &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_ChoiceThrow}, {"WithOids", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeWithOidsTrampoline, &FRAME_PLAN_12}, + &PEGTransformerFactory::FinalizeWithOidsTrampoline, &FRAME_PLAN_Leaf}, {"WithoutOids", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeWithoutOidsTrampoline, &FRAME_PLAN_12}, + &PEGTransformerFactory::FinalizeWithoutOidsTrampoline, &FRAME_PLAN_Leaf}, {"IndexElement", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeIndexElementTrampoline, &FRAME_PLAN_98}, + &PEGTransformerFactory::FinalizeIndexElementTrampoline, &FRAME_PLAN_IndexElement}, {"UniqueIndex", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeUniqueIndexTrampoline, &FRAME_PLAN_12}, + &PEGTransformerFactory::FinalizeUniqueIndexTrampoline, &FRAME_PLAN_Leaf}, {"IndexType", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeIndexTypeTrampoline, &FRAME_PLAN_12}, + &PEGTransformerFactory::FinalizeIndexTypeTrampoline, &FRAME_PLAN_Leaf}, {"RelOption", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeRelOptionTrampoline, &FRAME_PLAN_99}, + &PEGTransformerFactory::FinalizeRelOptionTrampoline, &FRAME_PLAN_RelOption}, {"RelOptionName", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, - &PEGTransformerFactory::FinalizeRelOptionNameTrampoline, &FRAME_PLAN_100}, + &PEGTransformerFactory::FinalizeRelOptionNameTrampoline, &FRAME_PLAN_RelOptionName}, {"DottedColLabel", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeDottedColLabelTrampoline, &FRAME_PLAN_101}, + &PEGTransformerFactory::FinalizeDottedColLabelTrampoline, &FRAME_PLAN_DottedColLabel}, {"RelOptionArgumentOpt", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeRelOptionArgumentOptTrampoline, &FRAME_PLAN_102}, + &PEGTransformerFactory::FinalizeRelOptionArgumentOptTrampoline, &FRAME_PLAN_RelOptionArgumentOpt}, {"DefArg", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, - &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, + &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_ChoiceThrow}, {"DefArgNull", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeDefArgNullTrampoline, &FRAME_PLAN_103}, + &PEGTransformerFactory::FinalizeDefArgNullTrampoline, &FRAME_PLAN_DefArgNull}, {"DefArgKeyword", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeDefArgKeywordTrampoline, &FRAME_PLAN_12}, + &PEGTransformerFactory::FinalizeDefArgKeywordTrampoline, &FRAME_PLAN_Leaf}, {"DefArgStringLiteral", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeDefArgStringLiteralTrampoline, &FRAME_PLAN_12}, + &PEGTransformerFactory::FinalizeDefArgStringLiteralTrampoline, &FRAME_PLAN_Leaf}, {"NoneLiteral", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeNoneLiteralTrampoline, &FRAME_PLAN_12}, + &PEGTransformerFactory::FinalizeNoneLiteralTrampoline, &FRAME_PLAN_Leaf}, {"CreateMacroStmt", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeCreateMacroStmtTrampoline, &FRAME_PLAN_104}, + &PEGTransformerFactory::FinalizeCreateMacroStmtTrampoline, &FRAME_PLAN_CreateMacroStmt}, {"ReturnsType", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_105}, + &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_CastOperator}, {"MacroOrFunction", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, - &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, + &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_ChoiceThrow}, {"MacroKeyword", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeMacroKeywordTrampoline, &FRAME_PLAN_12}, + &PEGTransformerFactory::FinalizeMacroKeywordTrampoline, &FRAME_PLAN_Leaf}, {"FunctionKeyword", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeFunctionKeywordTrampoline, &FRAME_PLAN_12}, + &PEGTransformerFactory::FinalizeFunctionKeywordTrampoline, &FRAME_PLAN_Leaf}, {"MacroDefinition", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeMacroDefinitionTrampoline, &FRAME_PLAN_106}, + &PEGTransformerFactory::FinalizeMacroDefinitionTrampoline, &FRAME_PLAN_MacroDefinition}, {"MacroDefinitionBody", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, - &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, + &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_ChoiceThrow}, {"MacroParameters", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeMacroParametersTrampoline, &FRAME_PLAN_107}, + &PEGTransformerFactory::FinalizeMacroParametersTrampoline, &FRAME_PLAN_MacroParameters}, {"MacroParameter", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, - &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, + &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_ChoiceThrow}, {"SimpleParameter", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeSimpleParameterTrampoline, &FRAME_PLAN_108}, + &PEGTransformerFactory::FinalizeSimpleParameterTrampoline, &FRAME_PLAN_SimpleParameter}, {"ScalarMacroDefinition", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeScalarMacroDefinitionTrampoline, &FRAME_PLAN_31}, + &PEGTransformerFactory::FinalizeScalarMacroDefinitionTrampoline, &FRAME_PLAN_DatabasePath}, {"TableMacroDefinition", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeTableMacroDefinitionTrampoline, &FRAME_PLAN_109}, + &PEGTransformerFactory::FinalizeTableMacroDefinitionTrampoline, &FRAME_PLAN_TableMacroDefinition}, {"CreateSchemaStmt", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeCreateSchemaStmtTrampoline, &FRAME_PLAN_110}, + &PEGTransformerFactory::FinalizeCreateSchemaStmtTrampoline, &FRAME_PLAN_CreateSchemaStmt}, {"WithOptionList", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeWithOptionListTrampoline, &FRAME_PLAN_16}, + &PEGTransformerFactory::FinalizeWithOptionListTrampoline, &FRAME_PLAN_ResetOptions}, {"CreateSecretStmt", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeCreateSecretStmtTrampoline, &FRAME_PLAN_111}, + &PEGTransformerFactory::FinalizeCreateSecretStmtTrampoline, &FRAME_PLAN_CreateSecretStmt}, {"SecretStorageSpecifier", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeSecretStorageSpecifierTrampoline, &FRAME_PLAN_12}, + &PEGTransformerFactory::FinalizeSecretStorageSpecifierTrampoline, &FRAME_PLAN_Leaf}, {"SecretName", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeSecretNameTrampoline, &FRAME_PLAN_83}, + &PEGTransformerFactory::FinalizeSecretNameTrampoline, &FRAME_PLAN_ColIdDot}, {"CreateSequenceStmt", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeCreateSequenceStmtTrampoline, &FRAME_PLAN_112}, + &PEGTransformerFactory::FinalizeCreateSequenceStmtTrampoline, &FRAME_PLAN_CreateSequenceStmt}, {"SequenceOption", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, - &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, + &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_ChoiceThrow}, {"SeqSetCycle", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, - &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, + &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_ChoiceThrow}, {"SeqCycle", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeSeqCycleTrampoline, &FRAME_PLAN_12}, + &PEGTransformerFactory::FinalizeSeqCycleTrampoline, &FRAME_PLAN_Leaf}, {"SeqNoCycle", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeSeqNoCycleTrampoline, &FRAME_PLAN_12}, + &PEGTransformerFactory::FinalizeSeqNoCycleTrampoline, &FRAME_PLAN_Leaf}, {"SeqSetIncrement", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeSeqSetIncrementTrampoline, &FRAME_PLAN_17}, + &PEGTransformerFactory::FinalizeSeqSetIncrementTrampoline, &FRAME_PLAN_AddDefault}, {"SeqSetMinMax", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeSeqSetMinMaxTrampoline, &FRAME_PLAN_113}, + &PEGTransformerFactory::FinalizeSeqSetMinMaxTrampoline, &FRAME_PLAN_SeqSetMinMax}, {"SeqNoMinMax", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeSeqNoMinMaxTrampoline, &FRAME_PLAN_114}, + &PEGTransformerFactory::FinalizeSeqNoMinMaxTrampoline, &FRAME_PLAN_SeqNoMinMax}, {"SeqStartWith", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeSeqStartWithTrampoline, &FRAME_PLAN_17}, + &PEGTransformerFactory::FinalizeSeqStartWithTrampoline, &FRAME_PLAN_AddDefault}, {"SeqOwnedBy", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeSeqOwnedByTrampoline, &FRAME_PLAN_115}, + &PEGTransformerFactory::FinalizeSeqOwnedByTrampoline, &FRAME_PLAN_SeqOwnedBy}, {"SeqMinOrMax", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, - &PEGTransformerFactory::FinalizeSeqMinOrMaxTrampoline, &FRAME_PLAN_19}, + &PEGTransformerFactory::FinalizeSeqMinOrMaxTrampoline, + &FRAME_PLAN_ChoiceEarlyIdentifierKeywordStringOperatorThrow}, {"MinValue", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeMinValueTrampoline, &FRAME_PLAN_12}, + &PEGTransformerFactory::FinalizeMinValueTrampoline, &FRAME_PLAN_Leaf}, {"MaxValue", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeMaxValueTrampoline, &FRAME_PLAN_12}, + &PEGTransformerFactory::FinalizeMaxValueTrampoline, &FRAME_PLAN_Leaf}, {"CreateStatement", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeCreateStatementTrampoline, &FRAME_PLAN_116}, + &PEGTransformerFactory::FinalizeCreateStatementTrampoline, &FRAME_PLAN_CreateStatement}, {"CreateStatementVariation", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, - &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, + &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_ChoiceThrow}, {"OrReplace", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeOrReplaceTrampoline, &FRAME_PLAN_12}, + &PEGTransformerFactory::FinalizeOrReplaceTrampoline, &FRAME_PLAN_Leaf}, {"Temporary", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, - &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, + &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_ChoiceThrow}, {"Persistent", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizePersistentTrampoline, &FRAME_PLAN_12}, + &PEGTransformerFactory::FinalizePersistentTrampoline, &FRAME_PLAN_Leaf}, {"TempPersistent", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeTempPersistentTrampoline, &FRAME_PLAN_12}, + &PEGTransformerFactory::FinalizeTempPersistentTrampoline, &FRAME_PLAN_Leaf}, {"TemporaryPersistent", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeTemporaryPersistentTrampoline, &FRAME_PLAN_12}, + &PEGTransformerFactory::FinalizeTemporaryPersistentTrampoline, &FRAME_PLAN_Leaf}, {"CreateTableStmt", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeCreateTableStmtTrampoline, &FRAME_PLAN_117}, + &PEGTransformerFactory::FinalizeCreateTableStmtTrampoline, &FRAME_PLAN_CreateTableStmt}, {"CreateTableDefinition", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, - &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, + &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_ChoiceThrow}, {"CreateTableAs", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeCreateTableAsTrampoline, &FRAME_PLAN_118}, + &PEGTransformerFactory::FinalizeCreateTableAsTrampoline, &FRAME_PLAN_CreateTableAs}, {"PartitionSortedOptions", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, - &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, + &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_ChoiceThrow}, {"PartitionOptSortedOptions", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizePartitionOptSortedOptionsTrampoline, &FRAME_PLAN_119}, + &PEGTransformerFactory::FinalizePartitionOptSortedOptionsTrampoline, &FRAME_PLAN_PartitionOptSortedOptions}, {"SortedOptPartitionOptions", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeSortedOptPartitionOptionsTrampoline, &FRAME_PLAN_120}, + &PEGTransformerFactory::FinalizeSortedOptPartitionOptionsTrampoline, &FRAME_PLAN_SortedOptPartitionOptions}, {"PartitionOptions", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizePartitionOptionsTrampoline, &FRAME_PLAN_121}, + &PEGTransformerFactory::FinalizePartitionOptionsTrampoline, &FRAME_PLAN_PartitionOptions}, {"SortedOptions", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeSortedOptionsTrampoline, &FRAME_PLAN_121}, + &PEGTransformerFactory::FinalizeSortedOptionsTrampoline, &FRAME_PLAN_PartitionOptions}, {"WithData", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, - &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, + &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_ChoiceThrow}, {"WithDataOnly", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeWithDataOnlyTrampoline, &FRAME_PLAN_12}, + &PEGTransformerFactory::FinalizeWithDataOnlyTrampoline, &FRAME_PLAN_Leaf}, {"WithNoData", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeWithNoDataTrampoline, &FRAME_PLAN_12}, + &PEGTransformerFactory::FinalizeWithNoDataTrampoline, &FRAME_PLAN_Leaf}, {"IdentifierList", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeIdentifierListTrampoline, &FRAME_PLAN_12}, + &PEGTransformerFactory::FinalizeIdentifierListTrampoline, &FRAME_PLAN_Leaf}, {"CreateColumnList", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeCreateColumnListTrampoline, &FRAME_PLAN_122}, + &PEGTransformerFactory::FinalizeCreateColumnListTrampoline, &FRAME_PLAN_CreateColumnList}, {"IfNotExists", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeIfNotExistsTrampoline, &FRAME_PLAN_12}, + &PEGTransformerFactory::FinalizeIfNotExistsTrampoline, &FRAME_PLAN_Leaf}, {"QualifiedName", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, - &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, + &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_ChoiceThrow}, {"SchemaReservedIdentifierOrStringLiteral", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeSchemaReservedIdentifierOrStringLiteralTrampoline, &FRAME_PLAN_123}, + &PEGTransformerFactory::FinalizeSchemaReservedIdentifierOrStringLiteralTrampoline, + &FRAME_PLAN_SchemaReservedIdentifierOrStringLiteral}, {"CatalogReservedSchemaIdentifier", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeCatalogReservedSchemaIdentifierTrampoline, &FRAME_PLAN_124}, + &PEGTransformerFactory::FinalizeCatalogReservedSchemaIdentifierTrampoline, + &FRAME_PLAN_CatalogReservedSchemaIdentifier}, {"IdentifierOrStringLiteral", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, - &PEGTransformerFactory::FinalizeIdentifierOrStringLiteralTrampoline, &FRAME_PLAN_54}, + &PEGTransformerFactory::FinalizeIdentifierOrStringLiteralTrampoline, + &FRAME_PLAN_ChoiceFallbackIdentifierKeywordStringOperatorChoiceListThrow}, {"ReservedIdentifierOrStringLiteral", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, - &PEGTransformerFactory::FinalizeReservedIdentifierOrStringLiteralTrampoline, &FRAME_PLAN_125}, + &PEGTransformerFactory::FinalizeReservedIdentifierOrStringLiteralTrampoline, + &FRAME_PLAN_ReservedIdentifierOrStringLiteral}, {"CatalogQualification", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeCatalogQualificationTrampoline, &FRAME_PLAN_12}, + &PEGTransformerFactory::FinalizeCatalogQualificationTrampoline, &FRAME_PLAN_Leaf}, {"SchemaQualification", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeSchemaQualificationTrampoline, &FRAME_PLAN_12}, + &PEGTransformerFactory::FinalizeSchemaQualificationTrampoline, &FRAME_PLAN_Leaf}, {"ReservedSchemaQualification", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeReservedSchemaQualificationTrampoline, &FRAME_PLAN_12}, + &PEGTransformerFactory::FinalizeReservedSchemaQualificationTrampoline, &FRAME_PLAN_Leaf}, {"TableQualification", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeTableQualificationTrampoline, &FRAME_PLAN_12}, + &PEGTransformerFactory::FinalizeTableQualificationTrampoline, &FRAME_PLAN_Leaf}, {"ReservedTableQualification", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeReservedTableQualificationTrampoline, &FRAME_PLAN_12}, + &PEGTransformerFactory::FinalizeReservedTableQualificationTrampoline, &FRAME_PLAN_Leaf}, {"CreateTableColumnList", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeCreateTableColumnListTrampoline, &FRAME_PLAN_126}, + &PEGTransformerFactory::FinalizeCreateTableColumnListTrampoline, &FRAME_PLAN_CreateTableColumnList}, {"CreateTableColumnElement", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, - &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, + &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_ChoiceThrow}, {"CreateTableColumnDefinition", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeCreateTableColumnDefinitionTrampoline, &FRAME_PLAN_127}, + &PEGTransformerFactory::FinalizeCreateTableColumnDefinitionTrampoline, &FRAME_PLAN_CreateTableColumnDefinition}, {"CreateTableConstraint", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeCreateTableConstraintTrampoline, &FRAME_PLAN_128}, + &PEGTransformerFactory::FinalizeCreateTableConstraintTrampoline, &FRAME_PLAN_CreateTableConstraint}, {"ColumnDefinition", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeColumnDefinitionTrampoline, &FRAME_PLAN_129}, + &PEGTransformerFactory::FinalizeColumnDefinitionTrampoline, &FRAME_PLAN_ColumnDefinition}, {"ColumnConstraint", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, - &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, + &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_ChoiceThrow}, {"NameableColumnConstraint", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeNameableColumnConstraintTrampoline, &FRAME_PLAN_130}, + &PEGTransformerFactory::FinalizeNameableColumnConstraintTrampoline, &FRAME_PLAN_NameableColumnConstraint}, {"ColumnConstraintElement", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, - &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, + &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_ChoiceThrow}, {"NotNullConstraint", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, - &PEGTransformerFactory::FinalizeNotNullConstraintTrampoline, &FRAME_PLAN_1}, + &PEGTransformerFactory::FinalizeNotNullConstraintTrampoline, &FRAME_PLAN_ChoiceThrow}, {"NullConstraint", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeNullConstraintTrampoline, &FRAME_PLAN_12}, + &PEGTransformerFactory::FinalizeNullConstraintTrampoline, &FRAME_PLAN_Leaf}, {"NotNullColumnConstraint", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeNotNullColumnConstraintTrampoline, &FRAME_PLAN_12}, + &PEGTransformerFactory::FinalizeNotNullColumnConstraintTrampoline, &FRAME_PLAN_Leaf}, {"UniqueConstraint", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeUniqueConstraintTrampoline, &FRAME_PLAN_131}, + &PEGTransformerFactory::FinalizeUniqueConstraintTrampoline, &FRAME_PLAN_UniqueConstraint}, {"PrimaryKeyConstraint", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizePrimaryKeyConstraintTrampoline, &FRAME_PLAN_132}, + &PEGTransformerFactory::FinalizePrimaryKeyConstraintTrampoline, &FRAME_PLAN_PrimaryKeyConstraint}, {"ConstraintTiming", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, - &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, + &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_ChoiceThrow}, {"ImmediateConstraint", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeImmediateConstraintTrampoline, &FRAME_PLAN_12}, + &PEGTransformerFactory::FinalizeImmediateConstraintTrampoline, &FRAME_PLAN_Leaf}, {"DeferredConstraint", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeDeferredConstraintTrampoline, &FRAME_PLAN_12}, + &PEGTransformerFactory::FinalizeDeferredConstraintTrampoline, &FRAME_PLAN_Leaf}, {"DefaultValue", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeDefaultValueTrampoline, &FRAME_PLAN_133}, + &PEGTransformerFactory::FinalizeDefaultValueTrampoline, &FRAME_PLAN_DefaultValue}, {"CheckConstraint", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeCheckConstraintTrampoline, &FRAME_PLAN_134}, + &PEGTransformerFactory::FinalizeCheckConstraintTrampoline, &FRAME_PLAN_CheckConstraint}, {"ForeignKeyConstraint", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeForeignKeyConstraintTrampoline, &FRAME_PLAN_135}, + &PEGTransformerFactory::FinalizeForeignKeyConstraintTrampoline, &FRAME_PLAN_ForeignKeyConstraint}, {"ColumnCollation", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeColumnCollationTrampoline, &FRAME_PLAN_136}, + &PEGTransformerFactory::FinalizeColumnCollationTrampoline, &FRAME_PLAN_ColumnCollation}, {"ColumnCompression", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeColumnCompressionTrampoline, &FRAME_PLAN_13}, + &PEGTransformerFactory::FinalizeColumnCompressionTrampoline, &FRAME_PLAN_ColumnCompression}, {"KeyActions", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, - &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, + &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_ChoiceThrow}, {"UpdateFirstKeyActions", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeUpdateFirstKeyActionsTrampoline, &FRAME_PLAN_137}, + &PEGTransformerFactory::FinalizeUpdateFirstKeyActionsTrampoline, &FRAME_PLAN_UpdateFirstKeyActions}, {"DeleteFirstKeyActions", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeDeleteFirstKeyActionsTrampoline, &FRAME_PLAN_138}, + &PEGTransformerFactory::FinalizeDeleteFirstKeyActionsTrampoline, &FRAME_PLAN_DeleteFirstKeyActions}, {"UpdateAction", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeUpdateActionTrampoline, &FRAME_PLAN_139}, + &PEGTransformerFactory::FinalizeUpdateActionTrampoline, &FRAME_PLAN_DeleteAction}, {"DeleteAction", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeDeleteActionTrampoline, &FRAME_PLAN_139}, + &PEGTransformerFactory::FinalizeDeleteActionTrampoline, &FRAME_PLAN_DeleteAction}, {"KeyAction", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, - &PEGTransformerFactory::FinalizeKeyActionTrampoline, &FRAME_PLAN_19}, + &PEGTransformerFactory::FinalizeKeyActionTrampoline, &FRAME_PLAN_ChoiceEarlyIdentifierKeywordStringOperatorThrow}, {"NoKeyAction", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeNoKeyActionTrampoline, &FRAME_PLAN_12}, + &PEGTransformerFactory::FinalizeNoKeyActionTrampoline, &FRAME_PLAN_Leaf}, {"RestrictKeyAction", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeRestrictKeyActionTrampoline, &FRAME_PLAN_12}, + &PEGTransformerFactory::FinalizeRestrictKeyActionTrampoline, &FRAME_PLAN_Leaf}, {"CascadeKeyAction", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeCascadeKeyActionTrampoline, &FRAME_PLAN_12}, + &PEGTransformerFactory::FinalizeCascadeKeyActionTrampoline, &FRAME_PLAN_Leaf}, {"SetNullKeyAction", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeSetNullKeyActionTrampoline, &FRAME_PLAN_12}, + &PEGTransformerFactory::FinalizeSetNullKeyActionTrampoline, &FRAME_PLAN_Leaf}, {"SetDefaultKeyAction", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeSetDefaultKeyActionTrampoline, &FRAME_PLAN_12}, + &PEGTransformerFactory::FinalizeSetDefaultKeyActionTrampoline, &FRAME_PLAN_Leaf}, {"TopLevelConstraint", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeTopLevelConstraintTrampoline, &FRAME_PLAN_140}, + &PEGTransformerFactory::FinalizeTopLevelConstraintTrampoline, &FRAME_PLAN_TopLevelConstraint}, {"TopLevelConstraintList", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, - &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, + &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_ChoiceThrow}, {"TopCheckConstraint", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeTopCheckConstraintTrampoline, &FRAME_PLAN_141}, + &PEGTransformerFactory::FinalizeTopCheckConstraintTrampoline, &FRAME_PLAN_TopCheckConstraint}, {"TopPrimaryKeyConstraint", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeTopPrimaryKeyConstraintTrampoline, &FRAME_PLAN_142}, + &PEGTransformerFactory::FinalizeTopPrimaryKeyConstraintTrampoline, &FRAME_PLAN_TopPrimaryKeyConstraint}, {"TopUniqueConstraint", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeTopUniqueConstraintTrampoline, &FRAME_PLAN_143}, + &PEGTransformerFactory::FinalizeTopUniqueConstraintTrampoline, &FRAME_PLAN_TopUniqueConstraint}, {"TopForeignKeyConstraint", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeTopForeignKeyConstraintTrampoline, &FRAME_PLAN_144}, + &PEGTransformerFactory::FinalizeTopForeignKeyConstraintTrampoline, &FRAME_PLAN_TopForeignKeyConstraint}, {"ColumnIdList", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeColumnIdListTrampoline, &FRAME_PLAN_145}, + &PEGTransformerFactory::FinalizeColumnIdListTrampoline, &FRAME_PLAN_ColumnIdList}, {"DottedIdentifier", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeDottedIdentifierTrampoline, &FRAME_PLAN_146}, + &PEGTransformerFactory::FinalizeDottedIdentifierTrampoline, &FRAME_PLAN_DottedIdentifier}, {"DotColLabel", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeDotColLabelTrampoline, &FRAME_PLAN_147}, + &PEGTransformerFactory::FinalizeDotColLabelTrampoline, &FRAME_PLAN_ColLabelParameter}, {"Identifier", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeIdentifierTrampoline, &FRAME_PLAN_12}, + &PEGTransformerFactory::FinalizeIdentifierTrampoline, &FRAME_PLAN_Leaf}, {"ColId", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, - &PEGTransformerFactory::FinalizeColIdTrampoline, &FRAME_PLAN_148}, + &PEGTransformerFactory::FinalizeColIdTrampoline, &FRAME_PLAN_ColId}, {"ColIdOrString", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, - &PEGTransformerFactory::FinalizeColIdOrStringTrampoline, &FRAME_PLAN_149}, + &PEGTransformerFactory::FinalizeColIdOrStringTrampoline, + &FRAME_PLAN_ChoiceEarlyIdentifierKeywordStringEmptyNameThrow}, {"TypeFuncName", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, - &PEGTransformerFactory::FinalizeTypeFuncNameTrampoline, &FRAME_PLAN_150}, + &PEGTransformerFactory::FinalizeTypeFuncNameTrampoline, &FRAME_PLAN_TypeFuncName}, {"TypeFuncKeyword", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, - &PEGTransformerFactory::FinalizeTypeFuncKeywordTrampoline, &FRAME_PLAN_151}, + &PEGTransformerFactory::FinalizeTypeFuncKeywordTrampoline, &FRAME_PLAN_TypeFuncKeyword}, {"ColLabel", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, - &PEGTransformerFactory::FinalizeColLabelTrampoline, &FRAME_PLAN_152}, + &PEGTransformerFactory::FinalizeColLabelTrampoline, &FRAME_PLAN_ColLabel}, {"ColLabelOrString", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, - &PEGTransformerFactory::FinalizeColLabelOrStringTrampoline, &FRAME_PLAN_149}, + &PEGTransformerFactory::FinalizeColLabelOrStringTrampoline, + &FRAME_PLAN_ChoiceEarlyIdentifierKeywordStringEmptyNameThrow}, {"ColLabelIdentifier", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeColLabelIdentifierTrampoline, &FRAME_PLAN_153}, + &PEGTransformerFactory::FinalizeColLabelIdentifierTrampoline, &FRAME_PLAN_ColLabelIdentifier}, {"StringLiteralIdentifier", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeStringLiteralIdentifierTrampoline, &FRAME_PLAN_12}, + &PEGTransformerFactory::FinalizeStringLiteralIdentifierTrampoline, &FRAME_PLAN_Leaf}, {"GeneratedColumn", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeGeneratedColumnTrampoline, &FRAME_PLAN_154}, + &PEGTransformerFactory::FinalizeGeneratedColumnTrampoline, &FRAME_PLAN_GeneratedColumn}, {"Generated", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, - &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, + &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_ChoiceThrow}, {"GeneratedAlways", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeGeneratedAlwaysTrampoline, &FRAME_PLAN_12}, + &PEGTransformerFactory::FinalizeGeneratedAlwaysTrampoline, &FRAME_PLAN_Leaf}, {"GeneratedByDefault", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeGeneratedByDefaultTrampoline, &FRAME_PLAN_12}, + &PEGTransformerFactory::FinalizeGeneratedByDefaultTrampoline, &FRAME_PLAN_Leaf}, {"GeneratedColumnType", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, - &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, + &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_ChoiceThrow}, {"CommitAction", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeCommitActionTrampoline, &FRAME_PLAN_155}, + &PEGTransformerFactory::FinalizeCommitActionTrampoline, &FRAME_PLAN_CommitAction}, {"PreserveOrDelete", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, - &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, + &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_ChoiceThrow}, {"PreserveRows", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizePreserveRowsTrampoline, &FRAME_PLAN_12}, + &PEGTransformerFactory::FinalizePreserveRowsTrampoline, &FRAME_PLAN_Leaf}, {"DeleteRows", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeDeleteRowsTrampoline, &FRAME_PLAN_12}, + &PEGTransformerFactory::FinalizeDeleteRowsTrampoline, &FRAME_PLAN_Leaf}, {"VirtualGeneratedColumn", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeVirtualGeneratedColumnTrampoline, &FRAME_PLAN_12}, + &PEGTransformerFactory::FinalizeVirtualGeneratedColumnTrampoline, &FRAME_PLAN_Leaf}, {"StoredGeneratedColumn", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeStoredGeneratedColumnTrampoline, &FRAME_PLAN_12}, + &PEGTransformerFactory::FinalizeStoredGeneratedColumnTrampoline, &FRAME_PLAN_Leaf}, {"CreateTriggerStmt", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeCreateTriggerStmtTrampoline, &FRAME_PLAN_156}, + &PEGTransformerFactory::FinalizeCreateTriggerStmtTrampoline, &FRAME_PLAN_CreateTriggerStmt}, {"TriggerBody", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, - &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, + &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_ChoiceThrow}, {"TriggerName", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeTriggerNameTrampoline, &FRAME_PLAN_12}, + &PEGTransformerFactory::FinalizeTriggerNameTrampoline, &FRAME_PLAN_Leaf}, {"ReferencingClause", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeReferencingClauseTrampoline, &FRAME_PLAN_157}, + &PEGTransformerFactory::FinalizeReferencingClauseTrampoline, &FRAME_PLAN_ReferencingClause}, {"ReferencingItem", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, - &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, + &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_ChoiceThrow}, {"ReferencingNewTableAs", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeReferencingNewTableAsTrampoline, &FRAME_PLAN_158}, + &PEGTransformerFactory::FinalizeReferencingNewTableAsTrampoline, &FRAME_PLAN_ReferencingNewTableAs}, {"ReferencingOldTableAs", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeReferencingOldTableAsTrampoline, &FRAME_PLAN_158}, + &PEGTransformerFactory::FinalizeReferencingOldTableAsTrampoline, &FRAME_PLAN_ReferencingNewTableAs}, {"TriggerTiming", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, - &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, + &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_ChoiceThrow}, {"TriggerBefore", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeTriggerBeforeTrampoline, &FRAME_PLAN_12}, + &PEGTransformerFactory::FinalizeTriggerBeforeTrampoline, &FRAME_PLAN_Leaf}, {"TriggerAfter", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeTriggerAfterTrampoline, &FRAME_PLAN_12}, + &PEGTransformerFactory::FinalizeTriggerAfterTrampoline, &FRAME_PLAN_Leaf}, {"TriggerInsteadOf", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeTriggerInsteadOfTrampoline, &FRAME_PLAN_12}, + &PEGTransformerFactory::FinalizeTriggerInsteadOfTrampoline, &FRAME_PLAN_Leaf}, {"TriggerEvent", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, - &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, + &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_ChoiceThrow}, {"TriggerEventInsert", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeTriggerEventInsertTrampoline, &FRAME_PLAN_12}, + &PEGTransformerFactory::FinalizeTriggerEventInsertTrampoline, &FRAME_PLAN_Leaf}, {"TriggerEventDelete", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeTriggerEventDeleteTrampoline, &FRAME_PLAN_12}, + &PEGTransformerFactory::FinalizeTriggerEventDeleteTrampoline, &FRAME_PLAN_Leaf}, {"TriggerEventUpdate", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeTriggerEventUpdateTrampoline, &FRAME_PLAN_12}, + &PEGTransformerFactory::FinalizeTriggerEventUpdateTrampoline, &FRAME_PLAN_Leaf}, {"TriggerEventUpdateOf", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeTriggerEventUpdateOfTrampoline, &FRAME_PLAN_159}, + &PEGTransformerFactory::FinalizeTriggerEventUpdateOfTrampoline, &FRAME_PLAN_TriggerEventUpdateOf}, {"TriggerColumnList", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeTriggerColumnListTrampoline, &FRAME_PLAN_160}, + &PEGTransformerFactory::FinalizeTriggerColumnListTrampoline, &FRAME_PLAN_ColumnList}, {"ForEachClause", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, - &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, + &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_ChoiceThrow}, {"ForEachRow", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeForEachRowTrampoline, &FRAME_PLAN_12}, + &PEGTransformerFactory::FinalizeForEachRowTrampoline, &FRAME_PLAN_Leaf}, {"ForEachStatement", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeForEachStatementTrampoline, &FRAME_PLAN_12}, + &PEGTransformerFactory::FinalizeForEachStatementTrampoline, &FRAME_PLAN_Leaf}, {"CreateTypeStmt", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeCreateTypeStmtTrampoline, &FRAME_PLAN_161}, + &PEGTransformerFactory::FinalizeCreateTypeStmtTrampoline, &FRAME_PLAN_CreateTypeStmt}, {"CreateType", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, - &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, + &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_ChoiceThrow}, {"CreateTypeFromType", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeCreateTypeFromTypeTrampoline, &FRAME_PLAN_162}, + &PEGTransformerFactory::FinalizeCreateTypeFromTypeTrampoline, &FRAME_PLAN_CreateTypeFromType}, {"EnumSelectType", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeEnumSelectTypeTrampoline, &FRAME_PLAN_163}, + &PEGTransformerFactory::FinalizeEnumSelectTypeTrampoline, &FRAME_PLAN_ArrayParensSelect}, {"EnumStringLiteralList", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeEnumStringLiteralListTrampoline, &FRAME_PLAN_164}, + &PEGTransformerFactory::FinalizeEnumStringLiteralListTrampoline, &FRAME_PLAN_EnumStringLiteralList}, {"CreateViewStmt", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeCreateViewStmtTrampoline, &FRAME_PLAN_165}, + &PEGTransformerFactory::FinalizeCreateViewStmtTrampoline, &FRAME_PLAN_CreateViewStmt}, {"CreateRecursive", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeCreateRecursiveTrampoline, &FRAME_PLAN_12}, + &PEGTransformerFactory::FinalizeCreateRecursiveTrampoline, &FRAME_PLAN_Leaf}, {"CreateSecure", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeCreateSecureTrampoline, &FRAME_PLAN_12}, + &PEGTransformerFactory::FinalizeCreateSecureTrampoline, &FRAME_PLAN_Leaf}, {"DeallocateStatement", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeDeallocateStatementTrampoline, &FRAME_PLAN_166}, + &PEGTransformerFactory::FinalizeDeallocateStatementTrampoline, &FRAME_PLAN_DeallocateStatement}, {"DeallocatePrepare", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeDeallocatePrepareTrampoline, &FRAME_PLAN_12}, + &PEGTransformerFactory::FinalizeDeallocatePrepareTrampoline, &FRAME_PLAN_Leaf}, {"DeleteStatement", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeDeleteStatementTrampoline, &FRAME_PLAN_167}, + &PEGTransformerFactory::FinalizeDeleteStatementTrampoline, &FRAME_PLAN_DeleteStatement}, {"TruncateStatement", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeTruncateStatementTrampoline, &FRAME_PLAN_168}, + &PEGTransformerFactory::FinalizeTruncateStatementTrampoline, &FRAME_PLAN_TruncateStatement}, {"TruncateOptions", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, - &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, + &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_ChoiceThrow}, {"TruncateAliasOptions", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeTruncateAliasOptionsTrampoline, &FRAME_PLAN_169}, + &PEGTransformerFactory::FinalizeTruncateAliasOptionsTrampoline, &FRAME_PLAN_TruncateAliasOptions}, {"TruncateDropBehavior", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeTruncateDropBehaviorTrampoline, &FRAME_PLAN_170}, + &PEGTransformerFactory::FinalizeTruncateDropBehaviorTrampoline, &FRAME_PLAN_TruncateDropBehavior}, {"TargetOptAlias", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeTargetOptAliasTrampoline, &FRAME_PLAN_171}, + &PEGTransformerFactory::FinalizeTargetOptAliasTrampoline, &FRAME_PLAN_TargetOptAlias}, {"TargetAlias", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeTargetAliasTrampoline, &FRAME_PLAN_32}, + &PEGTransformerFactory::FinalizeTargetAliasTrampoline, &FRAME_PLAN_AttachAlias}, {"DeleteUsingClause", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeDeleteUsingClauseTrampoline, &FRAME_PLAN_172}, + &PEGTransformerFactory::FinalizeDeleteUsingClauseTrampoline, &FRAME_PLAN_DeleteUsingClause}, {"DescribeStatement", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, - &PEGTransformerFactory::FinalizeDescribeStatementTrampoline, &FRAME_PLAN_1}, + &PEGTransformerFactory::FinalizeDescribeStatementTrampoline, &FRAME_PLAN_ChoiceThrow}, {"ShowExternalResources", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeShowExternalResourcesTrampoline, &FRAME_PLAN_173}, + &PEGTransformerFactory::FinalizeShowExternalResourcesTrampoline, &FRAME_PLAN_ShowExternalResources}, {"ShowExternalResourcesType", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_174}, + &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_ShowExternalResourcesType}, {"ShowExternalResourceTypes", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeShowExternalResourceTypesTrampoline, &FRAME_PLAN_175}, + &PEGTransformerFactory::FinalizeShowExternalResourceTypesTrampoline, &FRAME_PLAN_ShowExternalResourceTypes}, {"ShowDeprecatedSelect", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeShowDeprecatedSelectTrampoline, &FRAME_PLAN_176}, + &PEGTransformerFactory::FinalizeShowDeprecatedSelectTrampoline, &FRAME_PLAN_ShowDeprecatedSelect}, {"DescribeSelect", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeDescribeSelectTrampoline, &FRAME_PLAN_177}, + &PEGTransformerFactory::FinalizeDescribeSelectTrampoline, &FRAME_PLAN_DescribeSelect}, {"ShowAllTables", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeShowAllTablesTrampoline, &FRAME_PLAN_178}, + &PEGTransformerFactory::FinalizeShowAllTablesTrampoline, &FRAME_PLAN_ShowAllTables}, {"ShowTables", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeShowTablesTrampoline, &FRAME_PLAN_179}, + &PEGTransformerFactory::FinalizeShowTablesTrampoline, &FRAME_PLAN_ShowTables}, {"ShowByName", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeShowByNameTrampoline, &FRAME_PLAN_180}, + &PEGTransformerFactory::FinalizeShowByNameTrampoline, &FRAME_PLAN_ShowByName}, {"DescribeByName", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeDescribeByNameTrampoline, &FRAME_PLAN_181}, + &PEGTransformerFactory::FinalizeDescribeByNameTrampoline, &FRAME_PLAN_DescribeByName}, {"DescribeOrSummarize", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, - &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, + &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_ChoiceThrow}, {"ShowTarget", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, - &PEGTransformerFactory::FinalizeShowTargetTrampoline, &FRAME_PLAN_182}, + &PEGTransformerFactory::FinalizeShowTargetTrampoline, &FRAME_PLAN_ShowTarget}, {"ShowDeprecatedQualifiedTableName", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeShowDeprecatedQualifiedTableNameTrampoline, &FRAME_PLAN_183}, + &PEGTransformerFactory::FinalizeShowDeprecatedQualifiedTableNameTrampoline, + &FRAME_PLAN_ShowDeprecatedQualifiedTableName}, {"ShowSettingName", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeShowSettingNameTrampoline, &FRAME_PLAN_12}, + &PEGTransformerFactory::FinalizeShowSettingNameTrampoline, &FRAME_PLAN_Leaf}, {"DescribeTarget", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, - &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, + &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_ChoiceThrow}, {"DescribeBaseTableName", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeDescribeBaseTableNameTrampoline, &FRAME_PLAN_184}, + &PEGTransformerFactory::FinalizeDescribeBaseTableNameTrampoline, &FRAME_PLAN_BaseTableSet}, {"DescribeStringLiteral", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeDescribeStringLiteralTrampoline, &FRAME_PLAN_12}, + &PEGTransformerFactory::FinalizeDescribeStringLiteralTrampoline, &FRAME_PLAN_Leaf}, {"Summarize", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeSummarizeTrampoline, &FRAME_PLAN_185}, + &PEGTransformerFactory::FinalizeSummarizeTrampoline, &FRAME_PLAN_Summarize}, {"SummarizeRule", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeSummarizeRuleTrampoline, &FRAME_PLAN_12}, + &PEGTransformerFactory::FinalizeSummarizeRuleTrampoline, &FRAME_PLAN_Leaf}, {"ShowOrDescribe", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, - &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, + &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_ChoiceThrow}, {"ShowRule", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeShowRuleTrampoline, &FRAME_PLAN_12}, + &PEGTransformerFactory::FinalizeShowRuleTrampoline, &FRAME_PLAN_Leaf}, {"DescribeRule", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, - &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, + &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_ChoiceThrow}, {"DescribeLongRule", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeDescribeLongRuleTrampoline, &FRAME_PLAN_12}, + &PEGTransformerFactory::FinalizeDescribeLongRuleTrampoline, &FRAME_PLAN_Leaf}, {"DescRule", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeDescRuleTrampoline, &FRAME_PLAN_12}, + &PEGTransformerFactory::FinalizeDescRuleTrampoline, &FRAME_PLAN_Leaf}, {"DetachStatement", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeDetachStatementTrampoline, &FRAME_PLAN_186}, + &PEGTransformerFactory::FinalizeDetachStatementTrampoline, &FRAME_PLAN_DetachStatement}, {"DropStatement", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeDropStatementTrampoline, &FRAME_PLAN_187}, + &PEGTransformerFactory::FinalizeDropStatementTrampoline, &FRAME_PLAN_DropStatement}, {"DropMemberStatement", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeDropMemberStatementTrampoline, &FRAME_PLAN_188}, + &PEGTransformerFactory::FinalizeDropMemberStatementTrampoline, &FRAME_PLAN_DropMemberStatement}, {"DropMember", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, - &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, + &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_ChoiceThrow}, {"DropTableFunctionMember", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeDropTableFunctionMemberTrampoline, &FRAME_PLAN_189}, + &PEGTransformerFactory::FinalizeDropTableFunctionMemberTrampoline, &FRAME_PLAN_DropTableFunctionMember}, {"DropFunctionMember", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeDropFunctionMemberTrampoline, &FRAME_PLAN_190}, + &PEGTransformerFactory::FinalizeDropFunctionMemberTrampoline, &FRAME_PLAN_DropFunctionMember}, {"DropEntries", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, - &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, + &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_ChoiceThrow}, {"DropTrigger", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeDropTriggerTrampoline, &FRAME_PLAN_191}, + &PEGTransformerFactory::FinalizeDropTriggerTrampoline, &FRAME_PLAN_DropTrigger}, {"DropTable", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeDropTableTrampoline, &FRAME_PLAN_192}, + &PEGTransformerFactory::FinalizeDropTableTrampoline, &FRAME_PLAN_DropTable}, {"DropTableFunction", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeDropTableFunctionTrampoline, &FRAME_PLAN_193}, + &PEGTransformerFactory::FinalizeDropTableFunctionTrampoline, &FRAME_PLAN_DropTableFunction}, {"DropFunction", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeDropFunctionTrampoline, &FRAME_PLAN_194}, + &PEGTransformerFactory::FinalizeDropFunctionTrampoline, &FRAME_PLAN_DropFunction}, {"DropFunctionSignature", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeDropFunctionSignatureTrampoline, &FRAME_PLAN_195}, + &PEGTransformerFactory::FinalizeDropFunctionSignatureTrampoline, &FRAME_PLAN_DropFunctionSignature}, {"DropSignatureType", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, - &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, + &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_ChoiceThrow}, {"DropSignatureAnyType", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeDropSignatureAnyTypeTrampoline, &FRAME_PLAN_12}, + &PEGTransformerFactory::FinalizeDropSignatureAnyTypeTrampoline, &FRAME_PLAN_Leaf}, {"DropSchema", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeDropSchemaTrampoline, &FRAME_PLAN_196}, + &PEGTransformerFactory::FinalizeDropSchemaTrampoline, &FRAME_PLAN_DropSchema}, {"DropIndex", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeDropIndexTrampoline, &FRAME_PLAN_197}, + &PEGTransformerFactory::FinalizeDropIndexTrampoline, &FRAME_PLAN_DropIndex}, {"QualifiedIndexName", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, - &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, + &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_ChoiceThrow}, {"QualifiedIndexNameString", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeQualifiedIndexNameStringTrampoline, &FRAME_PLAN_12}, + &PEGTransformerFactory::FinalizeQualifiedIndexNameStringTrampoline, &FRAME_PLAN_Leaf}, {"SchemaReservedIndex", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeSchemaReservedIndexTrampoline, &FRAME_PLAN_56}, + &PEGTransformerFactory::FinalizeSchemaReservedIndexTrampoline, &FRAME_PLAN_SchemaReservedFunctionName}, {"CatalogReservedSchemaIndex", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeCatalogReservedSchemaIndexTrampoline, &FRAME_PLAN_55}, + &PEGTransformerFactory::FinalizeCatalogReservedSchemaIndexTrampoline, &FRAME_PLAN_CatalogReservedSchemaIndex}, {"DropSequence", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeDropSequenceTrampoline, &FRAME_PLAN_198}, + &PEGTransformerFactory::FinalizeDropSequenceTrampoline, &FRAME_PLAN_DropSequence}, {"DropCollation", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeDropCollationTrampoline, &FRAME_PLAN_199}, + &PEGTransformerFactory::FinalizeDropCollationTrampoline, &FRAME_PLAN_DropCollation}, {"DropType", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeDropTypeTrampoline, &FRAME_PLAN_200}, + &PEGTransformerFactory::FinalizeDropTypeTrampoline, &FRAME_PLAN_DropType}, {"DropSecret", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeDropSecretTrampoline, &FRAME_PLAN_201}, + &PEGTransformerFactory::FinalizeDropSecretTrampoline, &FRAME_PLAN_DropSecret}, {"TableOrView", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, - &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, + &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_ChoiceThrow}, {"MaterializedViewEntry", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeMaterializedViewEntryTrampoline, &FRAME_PLAN_12}, + &PEGTransformerFactory::FinalizeMaterializedViewEntryTrampoline, &FRAME_PLAN_Leaf}, {"FunctionTypeMacro", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, - &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, + &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_ChoiceThrow}, {"FunctionTypeMacroKeyword", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeFunctionTypeMacroKeywordTrampoline, &FRAME_PLAN_12}, + &PEGTransformerFactory::FinalizeFunctionTypeMacroKeywordTrampoline, &FRAME_PLAN_Leaf}, {"FunctionTypeFunction", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeFunctionTypeFunctionTrampoline, &FRAME_PLAN_12}, + &PEGTransformerFactory::FinalizeFunctionTypeFunctionTrampoline, &FRAME_PLAN_Leaf}, {"DropBehavior", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, - &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, + &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_ChoiceThrow}, {"CascadeDropBehavior", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeCascadeDropBehaviorTrampoline, &FRAME_PLAN_12}, + &PEGTransformerFactory::FinalizeCascadeDropBehaviorTrampoline, &FRAME_PLAN_Leaf}, {"RestrictDropBehavior", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeRestrictDropBehaviorTrampoline, &FRAME_PLAN_12}, + &PEGTransformerFactory::FinalizeRestrictDropBehaviorTrampoline, &FRAME_PLAN_Leaf}, {"IfExists", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeIfExistsTrampoline, &FRAME_PLAN_12}, + &PEGTransformerFactory::FinalizeIfExistsTrampoline, &FRAME_PLAN_Leaf}, {"DropSecretStorage", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeDropSecretStorageTrampoline, &FRAME_PLAN_12}, + &PEGTransformerFactory::FinalizeDropSecretStorageTrampoline, &FRAME_PLAN_Leaf}, {"ExecuteStatement", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeExecuteStatementTrampoline, &FRAME_PLAN_202}, + &PEGTransformerFactory::FinalizeExecuteStatementTrampoline, &FRAME_PLAN_ExecuteStatement}, {"ExplainStatement", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeExplainStatementTrampoline, &FRAME_PLAN_203}, + &PEGTransformerFactory::FinalizeExplainStatementTrampoline, &FRAME_PLAN_ExplainStatement}, {"ExplainOptionList", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeExplainOptionListTrampoline, &FRAME_PLAN_204}, + &PEGTransformerFactory::FinalizeExplainOptionListTrampoline, &FRAME_PLAN_ExplainOptionList}, {"ExplainOption", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeExplainOptionTrampoline, &FRAME_PLAN_205}, + &PEGTransformerFactory::FinalizeExplainOptionTrampoline, &FRAME_PLAN_ExplainOption}, {"ExplainOptionName", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, - &PEGTransformerFactory::FinalizeExplainOptionNameTrampoline, &FRAME_PLAN_206}, + &PEGTransformerFactory::FinalizeExplainOptionNameTrampoline, &FRAME_PLAN_ExplainOptionName}, {"ExplainSelectStatement", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeExplainSelectStatementTrampoline, &FRAME_PLAN_207}, + &PEGTransformerFactory::FinalizeExplainSelectStatementTrampoline, &FRAME_PLAN_ExplainSelectStatement}, {"ExplainableStatements", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, - &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, + &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_ChoiceThrow}, {"ExportStatement", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeExportStatementTrampoline, &FRAME_PLAN_208}, + &PEGTransformerFactory::FinalizeExportStatementTrampoline, &FRAME_PLAN_ExportStatement}, {"ExportSource", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeExportSourceTrampoline, &FRAME_PLAN_12}, + &PEGTransformerFactory::FinalizeExportSourceTrampoline, &FRAME_PLAN_Leaf}, {"ExportOptions", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, - &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, + &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_ChoiceThrow}, {"ImportStatement", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeImportStatementTrampoline, &FRAME_PLAN_12}, + &PEGTransformerFactory::FinalizeImportStatementTrampoline, &FRAME_PLAN_Leaf}, {"ColumnReference", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, - &PEGTransformerFactory::FinalizeColumnReferenceTrampoline, &FRAME_PLAN_1}, + &PEGTransformerFactory::FinalizeColumnReferenceTrampoline, &FRAME_PLAN_ChoiceThrow}, {"NestedSchemaTableColumnName", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeNestedSchemaTableColumnNameTrampoline, &FRAME_PLAN_209}, + &PEGTransformerFactory::FinalizeNestedSchemaTableColumnNameTrampoline, &FRAME_PLAN_NestedSchemaTableColumnName}, {"CatalogReservedSchemaTableColumnName", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeCatalogReservedSchemaTableColumnNameTrampoline, &FRAME_PLAN_210}, + &PEGTransformerFactory::FinalizeCatalogReservedSchemaTableColumnNameTrampoline, + &FRAME_PLAN_CatalogReservedSchemaTableColumnName}, {"SchemaReservedTableColumnName", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeSchemaReservedTableColumnNameTrampoline, &FRAME_PLAN_211}, + &PEGTransformerFactory::FinalizeSchemaReservedTableColumnNameTrampoline, + &FRAME_PLAN_SchemaReservedTableColumnName}, {"TableReservedColumnName", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeTableReservedColumnNameTrampoline, &FRAME_PLAN_212}, + &PEGTransformerFactory::FinalizeTableReservedColumnNameTrampoline, &FRAME_PLAN_TableReservedColumnName}, {"FunctionExpression", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeFunctionExpressionTrampoline, &FRAME_PLAN_213}, + &PEGTransformerFactory::FinalizeFunctionExpressionTrampoline, &FRAME_PLAN_FunctionExpression}, {"FunctionExpressionArguments", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeFunctionExpressionArgumentsTrampoline, &FRAME_PLAN_214}, + &PEGTransformerFactory::FinalizeFunctionExpressionArgumentsTrampoline, &FRAME_PLAN_FunctionExpressionArguments}, {"FunctionExpressionArgumentList", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeFunctionExpressionArgumentListTrampoline, &FRAME_PLAN_215}, + &PEGTransformerFactory::FinalizeFunctionExpressionArgumentListTrampoline, + &FRAME_PLAN_FunctionExpressionArgumentList}, {"FunctionArgumentList", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeFunctionArgumentListTrampoline, &FRAME_PLAN_216}, + &PEGTransformerFactory::FinalizeFunctionArgumentListTrampoline, &FRAME_PLAN_FunctionArgumentList}, {"FunctionIdentifier", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, - &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, + &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_ChoiceThrow}, {"FunctionNameAsQualifiedName", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeFunctionNameAsQualifiedNameTrampoline, &FRAME_PLAN_12}, + &PEGTransformerFactory::FinalizeFunctionNameAsQualifiedNameTrampoline, &FRAME_PLAN_Leaf}, {"CatalogReservedSchemaFunctionName", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeCatalogReservedSchemaFunctionNameTrampoline, &FRAME_PLAN_217}, + &PEGTransformerFactory::FinalizeCatalogReservedSchemaFunctionNameTrampoline, + &FRAME_PLAN_CatalogReservedSchemaFunctionName}, {"SchemaReservedFunctionName", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeSchemaReservedFunctionNameTrampoline, &FRAME_PLAN_56}, + &PEGTransformerFactory::FinalizeSchemaReservedFunctionNameTrampoline, &FRAME_PLAN_SchemaReservedFunctionName}, {"DistinctOrAll", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, - &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, + &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_ChoiceThrow}, {"DistinctKeyword", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeDistinctKeywordTrampoline, &FRAME_PLAN_12}, + &PEGTransformerFactory::FinalizeDistinctKeywordTrampoline, &FRAME_PLAN_Leaf}, {"AllKeyword", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeAllKeywordTrampoline, &FRAME_PLAN_12}, + &PEGTransformerFactory::FinalizeAllKeywordTrampoline, &FRAME_PLAN_Leaf}, {"WithinGroupClause", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeWithinGroupClauseTrampoline, &FRAME_PLAN_218}, + &PEGTransformerFactory::FinalizeWithinGroupClauseTrampoline, &FRAME_PLAN_WithinGroupClause}, {"FilterClause", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeFilterClauseTrampoline, &FRAME_PLAN_219}, + &PEGTransformerFactory::FinalizeFilterClauseTrampoline, &FRAME_PLAN_FilterClause}, {"FilterClauseExpression", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeFilterClauseExpressionTrampoline, &FRAME_PLAN_220}, + &PEGTransformerFactory::FinalizeFilterClauseExpressionTrampoline, &FRAME_PLAN_FilterClauseExpression}, {"FilterClauseContents", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeFilterClauseContentsTrampoline, &FRAME_PLAN_21}, + &PEGTransformerFactory::FinalizeFilterClauseContentsTrampoline, &FRAME_PLAN_AndExpression}, {"IgnoreOrRespectNulls", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, - &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, + &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_ChoiceThrow}, {"IgnoreNulls", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeIgnoreNullsTrampoline, &FRAME_PLAN_12}, + &PEGTransformerFactory::FinalizeIgnoreNullsTrampoline, &FRAME_PLAN_Leaf}, {"RespectNulls", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeRespectNullsTrampoline, &FRAME_PLAN_12}, + &PEGTransformerFactory::FinalizeRespectNullsTrampoline, &FRAME_PLAN_Leaf}, {"ParenthesisExpression", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeParenthesisExpressionTrampoline, &FRAME_PLAN_57}, + &PEGTransformerFactory::FinalizeParenthesisExpressionTrampoline, &FRAME_PLAN_ParenthesisExpression}, {"LiteralExpression", &PEGTransformerFactory::InitializeLiteralExpressionTrampoline, &PEGTransformerFactory::FinalizeLiteralExpressionTrampoline, nullptr}, {"ConstantLiteral", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, - &PEGTransformerFactory::FinalizeConstantLiteralTrampoline, &FRAME_PLAN_1}, + &PEGTransformerFactory::FinalizeConstantLiteralTrampoline, &FRAME_PLAN_ChoiceThrow}, {"NullLiteral", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeNullLiteralTrampoline, &FRAME_PLAN_12}, + &PEGTransformerFactory::FinalizeNullLiteralTrampoline, &FRAME_PLAN_Leaf}, {"TrueLiteral", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeTrueLiteralTrampoline, &FRAME_PLAN_12}, + &PEGTransformerFactory::FinalizeTrueLiteralTrampoline, &FRAME_PLAN_Leaf}, {"FalseLiteral", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeFalseLiteralTrampoline, &FRAME_PLAN_12}, + &PEGTransformerFactory::FinalizeFalseLiteralTrampoline, &FRAME_PLAN_Leaf}, {"CastExpression", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeCastExpressionTrampoline, &FRAME_PLAN_221}, + &PEGTransformerFactory::FinalizeCastExpressionTrampoline, &FRAME_PLAN_CastExpression}, {"CastArguments", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeCastArgumentsTrampoline, &FRAME_PLAN_222}, + &PEGTransformerFactory::FinalizeCastArgumentsTrampoline, &FRAME_PLAN_CastArguments}, {"CastOrTryCast", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, - &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, + &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_ChoiceThrow}, {"CastKeyword", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeCastKeywordTrampoline, &FRAME_PLAN_12}, + &PEGTransformerFactory::FinalizeCastKeywordTrampoline, &FRAME_PLAN_Leaf}, {"TryCastKeyword", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeTryCastKeywordTrampoline, &FRAME_PLAN_12}, + &PEGTransformerFactory::FinalizeTryCastKeywordTrampoline, &FRAME_PLAN_Leaf}, {"ColIdDot", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeColIdDotTrampoline, &FRAME_PLAN_83}, + &PEGTransformerFactory::FinalizeColIdDotTrampoline, &FRAME_PLAN_ColIdDot}, {"StarExpression", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeStarExpressionTrampoline, &FRAME_PLAN_223}, + &PEGTransformerFactory::FinalizeStarExpressionTrampoline, &FRAME_PLAN_StarExpression}, {"StarQualifierList", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeStarQualifierListTrampoline, &FRAME_PLAN_224}, + &PEGTransformerFactory::FinalizeStarQualifierListTrampoline, &FRAME_PLAN_StarQualifierList}, {"ExcludeList", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeExcludeListTrampoline, &FRAME_PLAN_225}, + &PEGTransformerFactory::FinalizeExcludeListTrampoline, &FRAME_PLAN_ExcludeList}, {"ExcludeNames", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, - &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, + &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_ChoiceThrow}, {"ExcludeNameList", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeExcludeNameListTrampoline, &FRAME_PLAN_226}, + &PEGTransformerFactory::FinalizeExcludeNameListTrampoline, &FRAME_PLAN_ExcludeNameList}, {"ExcludeNameSingle", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeExcludeNameSingleTrampoline, &FRAME_PLAN_227}, + &PEGTransformerFactory::FinalizeExcludeNameSingleTrampoline, &FRAME_PLAN_ExcludeNameSingle}, {"ExcludeName", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, - &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, + &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_ChoiceThrow}, {"ExcludeDottedName", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeExcludeDottedNameTrampoline, &FRAME_PLAN_228}, + &PEGTransformerFactory::FinalizeExcludeDottedNameTrampoline, &FRAME_PLAN_ExcludeDottedName}, {"ExcludeColumnName", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeExcludeColumnNameTrampoline, &FRAME_PLAN_38}, + &PEGTransformerFactory::FinalizeExcludeColumnNameTrampoline, &FRAME_PLAN_ConstraintName}, {"ReplaceList", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeReplaceListTrampoline, &FRAME_PLAN_229}, + &PEGTransformerFactory::FinalizeReplaceListTrampoline, &FRAME_PLAN_ReplaceList}, {"ReplaceEntries", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, - &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, + &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_ChoiceThrow}, {"ReplaceEntrySingle", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeReplaceEntrySingleTrampoline, &FRAME_PLAN_230}, + &PEGTransformerFactory::FinalizeReplaceEntrySingleTrampoline, &FRAME_PLAN_ReplaceEntrySingle}, {"ReplaceEntryList", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeReplaceEntryListTrampoline, &FRAME_PLAN_231}, + &PEGTransformerFactory::FinalizeReplaceEntryListTrampoline, &FRAME_PLAN_ReplaceEntryList}, {"ReplaceEntry", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeReplaceEntryTrampoline, &FRAME_PLAN_232}, + &PEGTransformerFactory::FinalizeReplaceEntryTrampoline, &FRAME_PLAN_ReplaceEntry}, {"RenameList", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeRenameListTrampoline, &FRAME_PLAN_233}, + &PEGTransformerFactory::FinalizeRenameListTrampoline, &FRAME_PLAN_RenameList}, {"RenameEntries", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, - &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, + &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_ChoiceThrow}, {"RenameEntryList", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeRenameEntryListTrampoline, &FRAME_PLAN_234}, + &PEGTransformerFactory::FinalizeRenameEntryListTrampoline, &FRAME_PLAN_RenameEntryList}, {"SingleRenameEntry", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeSingleRenameEntryTrampoline, &FRAME_PLAN_235}, + &PEGTransformerFactory::FinalizeSingleRenameEntryTrampoline, &FRAME_PLAN_SingleRenameEntry}, {"RenameEntry", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeRenameEntryTrampoline, &FRAME_PLAN_227}, + &PEGTransformerFactory::FinalizeRenameEntryTrampoline, &FRAME_PLAN_ExcludeNameSingle}, {"SubqueryExpression", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeSubqueryExpressionTrampoline, &FRAME_PLAN_236}, + &PEGTransformerFactory::FinalizeSubqueryExpressionTrampoline, &FRAME_PLAN_SubqueryExpression}, {"SubqueryNot", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeSubqueryNotTrampoline, &FRAME_PLAN_12}, + &PEGTransformerFactory::FinalizeSubqueryNotTrampoline, &FRAME_PLAN_Leaf}, {"SubqueryExists", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeSubqueryExistsTrampoline, &FRAME_PLAN_12}, + &PEGTransformerFactory::FinalizeSubqueryExistsTrampoline, &FRAME_PLAN_Leaf}, {"CaseExpression", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, - &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, + &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_ChoiceThrow}, {"SimpleCaseExpression", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeSimpleCaseExpressionTrampoline, &FRAME_PLAN_237}, + &PEGTransformerFactory::FinalizeSimpleCaseExpressionTrampoline, &FRAME_PLAN_SimpleCaseExpression}, {"SearchedCaseExpression", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeSearchedCaseExpressionTrampoline, &FRAME_PLAN_238}, + &PEGTransformerFactory::FinalizeSearchedCaseExpressionTrampoline, &FRAME_PLAN_SearchedCaseExpression}, {"SimpleCaseWhenThen", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeSimpleCaseWhenThenTrampoline, &FRAME_PLAN_239}, + &PEGTransformerFactory::FinalizeSimpleCaseWhenThenTrampoline, &FRAME_PLAN_SimpleCaseWhenThen}, {"SimpleCaseWhenOperand", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, - &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, + &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_ChoiceThrow}, {"SimpleCaseWhenEquals", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeSimpleCaseWhenEqualsTrampoline, &FRAME_PLAN_31}, + &PEGTransformerFactory::FinalizeSimpleCaseWhenEqualsTrampoline, &FRAME_PLAN_DatabasePath}, {"CaseWhenThen", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeCaseWhenThenTrampoline, &FRAME_PLAN_240}, + &PEGTransformerFactory::FinalizeCaseWhenThenTrampoline, &FRAME_PLAN_CaseWhenThen}, {"CaseElse", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeCaseElseTrampoline, &FRAME_PLAN_21}, + &PEGTransformerFactory::FinalizeCaseElseTrampoline, &FRAME_PLAN_AndExpression}, {"TypeLiteral", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeTypeLiteralTrampoline, &FRAME_PLAN_162}, + &PEGTransformerFactory::FinalizeTypeLiteralTrampoline, &FRAME_PLAN_CreateTypeFromType}, {"IntervalLiteral", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeIntervalLiteralTrampoline, &FRAME_PLAN_241}, + &PEGTransformerFactory::FinalizeIntervalLiteralTrampoline, &FRAME_PLAN_IntervalLiteral}, {"IntervalParameter", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, - &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, + &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_ChoiceThrow}, {"IntervalStringParameter", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeIntervalStringParameterTrampoline, &FRAME_PLAN_12}, + &PEGTransformerFactory::FinalizeIntervalStringParameterTrampoline, &FRAME_PLAN_Leaf}, {"FrameClause", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeFrameClauseTrampoline, &FRAME_PLAN_242}, + &PEGTransformerFactory::FinalizeFrameClauseTrampoline, &FRAME_PLAN_FrameClause}, {"Framing", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, - &PEGTransformerFactory::FinalizeFramingTrampoline, &FRAME_PLAN_19}, + &PEGTransformerFactory::FinalizeFramingTrampoline, &FRAME_PLAN_ChoiceEarlyIdentifierKeywordStringOperatorThrow}, {"RowsFraming", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeRowsFramingTrampoline, &FRAME_PLAN_12}, + &PEGTransformerFactory::FinalizeRowsFramingTrampoline, &FRAME_PLAN_Leaf}, {"RangeFraming", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeRangeFramingTrampoline, &FRAME_PLAN_12}, + &PEGTransformerFactory::FinalizeRangeFramingTrampoline, &FRAME_PLAN_Leaf}, {"GroupsFraming", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeGroupsFramingTrampoline, &FRAME_PLAN_12}, + &PEGTransformerFactory::FinalizeGroupsFramingTrampoline, &FRAME_PLAN_Leaf}, {"FrameExtent", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, - &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, + &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_ChoiceThrow}, {"SingleFrameExtent", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeSingleFrameExtentTrampoline, &FRAME_PLAN_243}, + &PEGTransformerFactory::FinalizeSingleFrameExtentTrampoline, &FRAME_PLAN_SingleFrameExtent}, {"BetweenFrameExtent", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeBetweenFrameExtentTrampoline, &FRAME_PLAN_244}, + &PEGTransformerFactory::FinalizeBetweenFrameExtentTrampoline, &FRAME_PLAN_BetweenFrameExtent}, {"FrameBound", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, - &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, + &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_ChoiceThrow}, {"FrameUnbounded", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeFrameUnboundedTrampoline, &FRAME_PLAN_245}, + &PEGTransformerFactory::FinalizeFrameUnboundedTrampoline, &FRAME_PLAN_FrameUnbounded}, {"FrameExpression", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeFrameExpressionTrampoline, &FRAME_PLAN_246}, + &PEGTransformerFactory::FinalizeFrameExpressionTrampoline, &FRAME_PLAN_FrameExpression}, {"FrameCurrentRow", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeFrameCurrentRowTrampoline, &FRAME_PLAN_12}, + &PEGTransformerFactory::FinalizeFrameCurrentRowTrampoline, &FRAME_PLAN_Leaf}, {"PrecedingOrFollowing", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, - &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, + &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_ChoiceThrow}, {"PrecedingFrame", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizePrecedingFrameTrampoline, &FRAME_PLAN_12}, + &PEGTransformerFactory::FinalizePrecedingFrameTrampoline, &FRAME_PLAN_Leaf}, {"FollowingFrame", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeFollowingFrameTrampoline, &FRAME_PLAN_12}, + &PEGTransformerFactory::FinalizeFollowingFrameTrampoline, &FRAME_PLAN_Leaf}, {"WindowExcludeClause", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeWindowExcludeClauseTrampoline, &FRAME_PLAN_247}, + &PEGTransformerFactory::FinalizeWindowExcludeClauseTrampoline, &FRAME_PLAN_WindowExcludeClause}, {"WindowExcludeElement", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, - &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, + &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_ChoiceThrow}, {"ExcludeCurrentRow", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeExcludeCurrentRowTrampoline, &FRAME_PLAN_12}, + &PEGTransformerFactory::FinalizeExcludeCurrentRowTrampoline, &FRAME_PLAN_Leaf}, {"ExcludeGroup", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeExcludeGroupTrampoline, &FRAME_PLAN_12}, + &PEGTransformerFactory::FinalizeExcludeGroupTrampoline, &FRAME_PLAN_Leaf}, {"ExcludeTies", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeExcludeTiesTrampoline, &FRAME_PLAN_12}, + &PEGTransformerFactory::FinalizeExcludeTiesTrampoline, &FRAME_PLAN_Leaf}, {"ExcludeNoOthers", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeExcludeNoOthersTrampoline, &FRAME_PLAN_12}, + &PEGTransformerFactory::FinalizeExcludeNoOthersTrampoline, &FRAME_PLAN_Leaf}, {"OverClause", &PEGTransformerFactory::InitializeOverClauseTrampoline, &PEGTransformerFactory::FinalizeOverClauseTrampoline, nullptr}, {"WindowFrame", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, - &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, + &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_ChoiceThrow}, {"IdentifierWindowFrame", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeIdentifierWindowFrameTrampoline, &FRAME_PLAN_12}, + &PEGTransformerFactory::FinalizeIdentifierWindowFrameTrampoline, &FRAME_PLAN_Leaf}, {"ParensIdentifier", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeParensIdentifierTrampoline, &FRAME_PLAN_12}, + &PEGTransformerFactory::FinalizeParensIdentifierTrampoline, &FRAME_PLAN_Leaf}, {"WindowFrameDefinition", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, - &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, + &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_ChoiceThrow}, {"WindowFrameNameContentsParens", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeWindowFrameNameContentsParensTrampoline, &FRAME_PLAN_248}, + &PEGTransformerFactory::FinalizeWindowFrameNameContentsParensTrampoline, + &FRAME_PLAN_WindowFrameNameContentsParens}, {"WindowFrameNameContents", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeWindowFrameNameContentsTrampoline, &FRAME_PLAN_249}, + &PEGTransformerFactory::FinalizeWindowFrameNameContentsTrampoline, &FRAME_PLAN_WindowFrameNameContents}, {"WindowFrameContentsParens", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeWindowFrameContentsParensTrampoline, &FRAME_PLAN_250}, + &PEGTransformerFactory::FinalizeWindowFrameContentsParensTrampoline, &FRAME_PLAN_WindowFrameContentsParens}, {"WindowFrameContents", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeWindowFrameContentsTrampoline, &FRAME_PLAN_251}, + &PEGTransformerFactory::FinalizeWindowFrameContentsTrampoline, &FRAME_PLAN_WindowFrameContents}, {"BaseWindowName", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeBaseWindowNameTrampoline, &FRAME_PLAN_12}, + &PEGTransformerFactory::FinalizeBaseWindowNameTrampoline, &FRAME_PLAN_Leaf}, {"WindowPartition", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeWindowPartitionTrampoline, &FRAME_PLAN_252}, + &PEGTransformerFactory::FinalizeWindowPartitionTrampoline, &FRAME_PLAN_WindowPartition}, {"ListExpression", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, - &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, + &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_ChoiceThrow}, {"ArrayBoundedListExpression", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeArrayBoundedListExpressionTrampoline, &FRAME_PLAN_253}, + &PEGTransformerFactory::FinalizeArrayBoundedListExpressionTrampoline, &FRAME_PLAN_ArrayBoundedListExpression}, {"ArrayParensSelect", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeArrayParensSelectTrampoline, &FRAME_PLAN_163}, + &PEGTransformerFactory::FinalizeArrayParensSelectTrampoline, &FRAME_PLAN_ArrayParensSelect}, {"BoundedListExpression", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeBoundedListExpressionTrampoline, &FRAME_PLAN_254}, + &PEGTransformerFactory::FinalizeBoundedListExpressionTrampoline, &FRAME_PLAN_BoundedListExpression}, {"StructExpression", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeStructExpressionTrampoline, &FRAME_PLAN_255}, + &PEGTransformerFactory::FinalizeStructExpressionTrampoline, &FRAME_PLAN_StructExpression}, {"StructField", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeStructFieldTrampoline, &FRAME_PLAN_256}, + &PEGTransformerFactory::FinalizeStructFieldTrampoline, &FRAME_PLAN_StructField}, {"MapExpression", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeMapExpressionTrampoline, &FRAME_PLAN_257}, + &PEGTransformerFactory::FinalizeMapExpressionTrampoline, &FRAME_PLAN_MapExpression}, {"MapStructExpression", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeMapStructExpressionTrampoline, &FRAME_PLAN_258}, + &PEGTransformerFactory::FinalizeMapStructExpressionTrampoline, &FRAME_PLAN_MapStructExpression}, {"MapStructField", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeMapStructFieldTrampoline, &FRAME_PLAN_259}, + &PEGTransformerFactory::FinalizeMapStructFieldTrampoline, &FRAME_PLAN_MapStructField}, {"GroupingExpression", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeGroupingExpressionTrampoline, &FRAME_PLAN_260}, + &PEGTransformerFactory::FinalizeGroupingExpressionTrampoline, &FRAME_PLAN_GroupingExpression}, {"GroupingOrGroupingId", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, - &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, + &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_ChoiceThrow}, {"GroupingKeyword", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeGroupingKeywordTrampoline, &FRAME_PLAN_12}, + &PEGTransformerFactory::FinalizeGroupingKeywordTrampoline, &FRAME_PLAN_Leaf}, {"GroupingIdKeyword", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeGroupingIdKeywordTrampoline, &FRAME_PLAN_12}, + &PEGTransformerFactory::FinalizeGroupingIdKeywordTrampoline, &FRAME_PLAN_Leaf}, {"Parameter", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, - &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, + &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_ChoiceThrow}, {"QuestionMarkNumberedParameter", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeQuestionMarkNumberedParameterTrampoline, &FRAME_PLAN_12}, + &PEGTransformerFactory::FinalizeQuestionMarkNumberedParameterTrampoline, &FRAME_PLAN_Leaf}, {"AnonymousParameter", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeAnonymousParameterTrampoline, &FRAME_PLAN_12}, + &PEGTransformerFactory::FinalizeAnonymousParameterTrampoline, &FRAME_PLAN_Leaf}, {"NumberedParameter", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeNumberedParameterTrampoline, &FRAME_PLAN_12}, + &PEGTransformerFactory::FinalizeNumberedParameterTrampoline, &FRAME_PLAN_Leaf}, {"ColLabelParameter", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeColLabelParameterTrampoline, &FRAME_PLAN_147}, + &PEGTransformerFactory::FinalizeColLabelParameterTrampoline, &FRAME_PLAN_ColLabelParameter}, {"PositionalExpression", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizePositionalExpressionTrampoline, &FRAME_PLAN_12}, + &PEGTransformerFactory::FinalizePositionalExpressionTrampoline, &FRAME_PLAN_Leaf}, {"DefaultExpression", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeDefaultExpressionTrampoline, &FRAME_PLAN_12}, + &PEGTransformerFactory::FinalizeDefaultExpressionTrampoline, &FRAME_PLAN_Leaf}, {"ListComprehensionExpression", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeListComprehensionExpressionTrampoline, &FRAME_PLAN_261}, + &PEGTransformerFactory::FinalizeListComprehensionExpressionTrampoline, &FRAME_PLAN_ListComprehensionExpression}, {"ListComprehensionFilter", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeListComprehensionFilterTrampoline, &FRAME_PLAN_21}, + &PEGTransformerFactory::FinalizeListComprehensionFilterTrampoline, &FRAME_PLAN_AndExpression}, {"ParensExpression", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeParensExpressionTrampoline, &FRAME_PLAN_262}, + &PEGTransformerFactory::FinalizeParensExpressionTrampoline, &FRAME_PLAN_ParensExpression}, {"MeasureSemanticsExpression", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeMeasureSemanticsExpressionTrampoline, &FRAME_PLAN_263}, + &PEGTransformerFactory::FinalizeMeasureSemanticsExpressionTrampoline, &FRAME_PLAN_MeasureSemanticsExpression}, {"SingleExpression", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, - &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, + &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_ChoiceThrow}, {"Expression", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_264}, + &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_ArrowFullBody}, {"ColumnDefaultExpr", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeColumnDefaultExprTrampoline, &FRAME_PLAN_265}, + &PEGTransformerFactory::FinalizeColumnDefaultExprTrampoline, &FRAME_PLAN_ColumnDefaultExpr}, {"LogicalOrExpression", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeLogicalOrExpressionTrampoline, &FRAME_PLAN_266}, + &PEGTransformerFactory::FinalizeLogicalOrExpressionTrampoline, &FRAME_PLAN_LogicalOrExpression}, {"LogicalOrExpressionTail", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeLogicalOrExpressionTailTrampoline, &FRAME_PLAN_267}, + &PEGTransformerFactory::FinalizeLogicalOrExpressionTailTrampoline, &FRAME_PLAN_LogicalOrExpressionTail}, {"ColDefOrExpr", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeColDefOrExprTrampoline, &FRAME_PLAN_268}, + &PEGTransformerFactory::FinalizeColDefOrExprTrampoline, &FRAME_PLAN_ColDefOrExpr}, {"ColDefOrExpressionTail", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeColDefOrExpressionTailTrampoline, &FRAME_PLAN_269}, + &PEGTransformerFactory::FinalizeColDefOrExpressionTailTrampoline, &FRAME_PLAN_ColDefOrExpressionTail}, {"LogicalAndExpression", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeLogicalAndExpressionTrampoline, &FRAME_PLAN_270}, + &PEGTransformerFactory::FinalizeLogicalAndExpressionTrampoline, &FRAME_PLAN_LogicalAndExpression}, {"LogicalAndExpressionTail", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeLogicalAndExpressionTailTrampoline, &FRAME_PLAN_271}, + &PEGTransformerFactory::FinalizeLogicalAndExpressionTailTrampoline, &FRAME_PLAN_LogicalAndExpressionTail}, {"ColDefAndExpr", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeColDefAndExprTrampoline, &FRAME_PLAN_272}, + &PEGTransformerFactory::FinalizeColDefAndExprTrampoline, &FRAME_PLAN_ColDefAndExpr}, {"ColDefAndExpressionTail", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeColDefAndExpressionTailTrampoline, &FRAME_PLAN_273}, + &PEGTransformerFactory::FinalizeColDefAndExpressionTailTrampoline, &FRAME_PLAN_ColDefAndExpressionTail}, {"LogicalNotExpression", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeLogicalNotExpressionTrampoline, &FRAME_PLAN_274}, + &PEGTransformerFactory::FinalizeLogicalNotExpressionTrampoline, &FRAME_PLAN_LogicalNotExpression}, {"NotExpression", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeNotExpressionTrampoline, &FRAME_PLAN_275}, + &PEGTransformerFactory::FinalizeNotExpressionTrampoline, &FRAME_PLAN_NotExpression}, {"NotKeyword", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeNotKeywordTrampoline, &FRAME_PLAN_12}, + &PEGTransformerFactory::FinalizeNotKeywordTrampoline, &FRAME_PLAN_Leaf}, {"IsExpression", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeIsExpressionTrampoline, &FRAME_PLAN_276}, + &PEGTransformerFactory::FinalizeIsExpressionTrampoline, &FRAME_PLAN_IsExpression}, {"IsExpressionContinuation", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeIsExpressionContinuationTrampoline, &FRAME_PLAN_277}, + &PEGTransformerFactory::FinalizeIsExpressionContinuationTrampoline, &FRAME_PLAN_IsExpressionContinuation}, {"IsExpressionTail", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, - &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, + &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_ChoiceThrow}, {"IsTestTail", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeIsTestTailTrampoline, &FRAME_PLAN_278}, + &PEGTransformerFactory::FinalizeIsTestTailTrampoline, &FRAME_PLAN_IsTestTail}, {"IsDistinctTail", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeIsDistinctTailTrampoline, &FRAME_PLAN_279}, + &PEGTransformerFactory::FinalizeIsDistinctTailTrampoline, &FRAME_PLAN_IsDistinctTail}, {"IsComparisonTail", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeIsComparisonTailTrampoline, &FRAME_PLAN_280}, + &PEGTransformerFactory::FinalizeIsComparisonTailTrampoline, &FRAME_PLAN_IsComparisonTail}, {"IsOtherOperatorTail", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeIsOtherOperatorTailTrampoline, &FRAME_PLAN_281}, + &PEGTransformerFactory::FinalizeIsOtherOperatorTailTrampoline, &FRAME_PLAN_IsOtherOperatorTail}, {"IsCastTail", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeIsCastTailTrampoline, &FRAME_PLAN_282}, + &PEGTransformerFactory::FinalizeIsCastTailTrampoline, &FRAME_PLAN_IsCastTail}, {"IsTest", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, - &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, + &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_ChoiceThrow}, {"IsLiteral", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeIsLiteralTrampoline, &FRAME_PLAN_283}, + &PEGTransformerFactory::FinalizeIsLiteralTrampoline, &FRAME_PLAN_IsLiteral}, {"IsLiteralValue", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, - &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, + &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_ChoiceThrow}, {"UnknownLiteral", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeUnknownLiteralTrampoline, &FRAME_PLAN_12}, + &PEGTransformerFactory::FinalizeUnknownLiteralTrampoline, &FRAME_PLAN_Leaf}, {"NotNull", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, - &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, + &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_ChoiceThrow}, {"NotNullKeyword", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeNotNullKeywordTrampoline, &FRAME_PLAN_12}, + &PEGTransformerFactory::FinalizeNotNullKeywordTrampoline, &FRAME_PLAN_Leaf}, {"NotNullOperator", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeNotNullOperatorTrampoline, &FRAME_PLAN_12}, + &PEGTransformerFactory::FinalizeNotNullOperatorTrampoline, &FRAME_PLAN_Leaf}, {"IsNull", &PEGTransformerFactory::InitializePlannedTrampoline, &PEGTransformerFactory::FinalizeIsNullTrampoline, - &FRAME_PLAN_284}, + &FRAME_PLAN_IsNull}, {"IsNullOperator", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeIsNullOperatorTrampoline, &FRAME_PLAN_12}, + &PEGTransformerFactory::FinalizeIsNullOperatorTrampoline, &FRAME_PLAN_Leaf}, {"IsDistinctFromExpression", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeIsDistinctFromExpressionTrampoline, &FRAME_PLAN_285}, + &PEGTransformerFactory::FinalizeIsDistinctFromExpressionTrampoline, &FRAME_PLAN_IsDistinctFromExpression}, {"IsDistinctFromTail", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeIsDistinctFromTailTrampoline, &FRAME_PLAN_286}, + &PEGTransformerFactory::FinalizeIsDistinctFromTailTrampoline, &FRAME_PLAN_IsDistinctFromTail}, {"IsDistinctFromOp", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeIsDistinctFromOpTrampoline, &FRAME_PLAN_12}, + &PEGTransformerFactory::FinalizeIsDistinctFromOpTrampoline, &FRAME_PLAN_Leaf}, {"ComparisonExpression", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeComparisonExpressionTrampoline, &FRAME_PLAN_287}, + &PEGTransformerFactory::FinalizeComparisonExpressionTrampoline, &FRAME_PLAN_ComparisonExpression}, {"ComparisonExpressionTail", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeComparisonExpressionTailTrampoline, &FRAME_PLAN_288}, + &PEGTransformerFactory::FinalizeComparisonExpressionTailTrampoline, &FRAME_PLAN_ComparisonExpressionTail}, {"ComparisonOperand", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, - &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, + &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_ChoiceThrow}, {"NotComparisonOperand", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeNotComparisonOperandTrampoline, &FRAME_PLAN_289}, + &PEGTransformerFactory::FinalizeNotComparisonOperandTrampoline, &FRAME_PLAN_NotComparisonOperand}, {"ComparisonOperator", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, - &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, + &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_ChoiceThrow}, {"OperatorEqual", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeOperatorEqualTrampoline, &FRAME_PLAN_12}, + &PEGTransformerFactory::FinalizeOperatorEqualTrampoline, &FRAME_PLAN_Leaf}, {"OperatorNotEqual", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeOperatorNotEqualTrampoline, &FRAME_PLAN_12}, + &PEGTransformerFactory::FinalizeOperatorNotEqualTrampoline, &FRAME_PLAN_Leaf}, {"OperatorLessThan", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeOperatorLessThanTrampoline, &FRAME_PLAN_12}, + &PEGTransformerFactory::FinalizeOperatorLessThanTrampoline, &FRAME_PLAN_Leaf}, {"OperatorGreaterThan", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeOperatorGreaterThanTrampoline, &FRAME_PLAN_12}, + &PEGTransformerFactory::FinalizeOperatorGreaterThanTrampoline, &FRAME_PLAN_Leaf}, {"OperatorLessThanEquals", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeOperatorLessThanEqualsTrampoline, &FRAME_PLAN_12}, + &PEGTransformerFactory::FinalizeOperatorLessThanEqualsTrampoline, &FRAME_PLAN_Leaf}, {"OperatorGreaterThanEquals", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeOperatorGreaterThanEqualsTrampoline, &FRAME_PLAN_12}, + &PEGTransformerFactory::FinalizeOperatorGreaterThanEqualsTrampoline, &FRAME_PLAN_Leaf}, {"BetweenInLikeExpression", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeBetweenInLikeExpressionTrampoline, &FRAME_PLAN_290}, + &PEGTransformerFactory::FinalizeBetweenInLikeExpressionTrampoline, &FRAME_PLAN_BetweenInLikeExpression}, {"InPredicate", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeInPredicateTrampoline, &FRAME_PLAN_291}, + &PEGTransformerFactory::FinalizeInPredicateTrampoline, &FRAME_PLAN_InPredicate}, {"BetweenLikeOp", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeBetweenLikeOpTrampoline, &FRAME_PLAN_292}, + &PEGTransformerFactory::FinalizeBetweenLikeOpTrampoline, &FRAME_PLAN_BetweenLikeOp}, {"BetweenLikeOpExpression", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, - &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, + &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_ChoiceThrow}, {"LikeClause", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeLikeClauseTrampoline, &FRAME_PLAN_293}, + &PEGTransformerFactory::FinalizeLikeClauseTrampoline, &FRAME_PLAN_LikeClause}, {"EscapeClause", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeEscapeClauseTrampoline, &FRAME_PLAN_294}, + &PEGTransformerFactory::FinalizeEscapeClauseTrampoline, &FRAME_PLAN_EscapeClause}, {"LikeVariations", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, - &PEGTransformerFactory::FinalizeLikeVariationsTrampoline, &FRAME_PLAN_19}, + &PEGTransformerFactory::FinalizeLikeVariationsTrampoline, + &FRAME_PLAN_ChoiceEarlyIdentifierKeywordStringOperatorThrow}, {"LikeToken", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeLikeTokenTrampoline, &FRAME_PLAN_12}, + &PEGTransformerFactory::FinalizeLikeTokenTrampoline, &FRAME_PLAN_Leaf}, {"ILikeToken", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeILikeTokenTrampoline, &FRAME_PLAN_12}, + &PEGTransformerFactory::FinalizeILikeTokenTrampoline, &FRAME_PLAN_Leaf}, {"GlobToken", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeGlobTokenTrampoline, &FRAME_PLAN_12}, + &PEGTransformerFactory::FinalizeGlobTokenTrampoline, &FRAME_PLAN_Leaf}, {"SimilarToToken", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeSimilarToTokenTrampoline, &FRAME_PLAN_12}, + &PEGTransformerFactory::FinalizeSimilarToTokenTrampoline, &FRAME_PLAN_Leaf}, {"RegexMatchToken", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeRegexMatchTokenTrampoline, &FRAME_PLAN_12}, + &PEGTransformerFactory::FinalizeRegexMatchTokenTrampoline, &FRAME_PLAN_Leaf}, {"RegexInsensitiveMatchToken", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeRegexInsensitiveMatchTokenTrampoline, &FRAME_PLAN_12}, + &PEGTransformerFactory::FinalizeRegexInsensitiveMatchTokenTrampoline, &FRAME_PLAN_Leaf}, {"NotILikeOp", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeNotILikeOpTrampoline, &FRAME_PLAN_12}, + &PEGTransformerFactory::FinalizeNotILikeOpTrampoline, &FRAME_PLAN_Leaf}, {"NotLikeOp", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeNotLikeOpTrampoline, &FRAME_PLAN_12}, + &PEGTransformerFactory::FinalizeNotLikeOpTrampoline, &FRAME_PLAN_Leaf}, {"NotRegexInsensitiveMatchOp", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeNotRegexInsensitiveMatchOpTrampoline, &FRAME_PLAN_12}, + &PEGTransformerFactory::FinalizeNotRegexInsensitiveMatchOpTrampoline, &FRAME_PLAN_Leaf}, {"NotSimilarToOp", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeNotSimilarToOpTrampoline, &FRAME_PLAN_12}, + &PEGTransformerFactory::FinalizeNotSimilarToOpTrampoline, &FRAME_PLAN_Leaf}, {"InClause", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeInClauseTrampoline, &FRAME_PLAN_295}, + &PEGTransformerFactory::FinalizeInClauseTrampoline, &FRAME_PLAN_InClause}, {"InExpression", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, - &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, + &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_ChoiceThrow}, {"InContainsExpression", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeInContainsExpressionTrampoline, &FRAME_PLAN_296}, + &PEGTransformerFactory::FinalizeInContainsExpressionTrampoline, &FRAME_PLAN_InContainsExpression}, {"InExpressionList", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeInExpressionListTrampoline, &FRAME_PLAN_297}, + &PEGTransformerFactory::FinalizeInExpressionListTrampoline, &FRAME_PLAN_InExpressionList}, {"InSelectStatement", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeInSelectStatementTrampoline, &FRAME_PLAN_298}, + &PEGTransformerFactory::FinalizeInSelectStatementTrampoline, &FRAME_PLAN_CTESelectBody}, {"BetweenClause", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeBetweenClauseTrampoline, &FRAME_PLAN_299}, + &PEGTransformerFactory::FinalizeBetweenClauseTrampoline, &FRAME_PLAN_BetweenClause}, {"OtherOperatorExpression", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_300}, + &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_OtherOperatorExpression}, {"InfixOtherOperatorExpression", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeInfixOtherOperatorExpressionTrampoline, &FRAME_PLAN_301}, + &PEGTransformerFactory::FinalizeInfixOtherOperatorExpressionTrampoline, &FRAME_PLAN_InfixOtherOperatorExpression}, {"OtherOperatorTail", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, - &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, + &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_ChoiceThrow}, {"AnyAllSubqueryTail", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeAnyAllSubqueryTailTrampoline, &FRAME_PLAN_302}, + &PEGTransformerFactory::FinalizeAnyAllSubqueryTailTrampoline, &FRAME_PLAN_AnyAllSubqueryTail}, {"OtherOperatorExpressionTail", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeOtherOperatorExpressionTailTrampoline, &FRAME_PLAN_303}, + &PEGTransformerFactory::FinalizeOtherOperatorExpressionTailTrampoline, &FRAME_PLAN_OtherOperatorExpressionTail}, {"SingleArrowTail", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeSingleArrowTailTrampoline, &FRAME_PLAN_304}, + &PEGTransformerFactory::FinalizeSingleArrowTailTrampoline, &FRAME_PLAN_SingleArrowTail}, {"SingleArrowBody", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, - &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, + &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_ChoiceThrow}, {"ArrowChainBody", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeArrowChainBodyTrampoline, &FRAME_PLAN_305}, + &PEGTransformerFactory::FinalizeArrowChainBodyTrampoline, &FRAME_PLAN_ArrowChainBody}, {"ArrowChainTail", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, - &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, + &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_ChoiceThrow}, {"DoubleArrowTail", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeDoubleArrowTailTrampoline, &FRAME_PLAN_306}, + &PEGTransformerFactory::FinalizeDoubleArrowTailTrampoline, &FRAME_PLAN_DoubleArrowTail}, {"ArrowFullBody", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeArrowFullBodyTrampoline, &FRAME_PLAN_264}, + &PEGTransformerFactory::FinalizeArrowFullBodyTrampoline, &FRAME_PLAN_ArrowFullBody}, {"OtherOperator", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, - &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, + &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_ChoiceThrow}, {"AnyAllParsedOperator", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeAnyAllParsedOperatorTrampoline, &FRAME_PLAN_307}, + &PEGTransformerFactory::FinalizeAnyAllParsedOperatorTrampoline, &FRAME_PLAN_AnyAllParsedOperator}, {"NamedOtherOperator", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, - &PEGTransformerFactory::FinalizeNamedOtherOperatorTrampoline, &FRAME_PLAN_54}, + &PEGTransformerFactory::FinalizeNamedOtherOperatorTrampoline, + &FRAME_PLAN_ChoiceFallbackIdentifierKeywordStringOperatorChoiceListThrow}, {"OperatorLiteral", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeOperatorLiteralTrampoline, &FRAME_PLAN_12}, + &PEGTransformerFactory::FinalizeOperatorLiteralTrampoline, &FRAME_PLAN_Leaf}, {"AnyOperatorLiteral", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeAnyOperatorLiteralTrampoline, &FRAME_PLAN_12}, + &PEGTransformerFactory::FinalizeAnyOperatorLiteralTrampoline, &FRAME_PLAN_Leaf}, {"AnyAllOperator", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeAnyAllOperatorTrampoline, &FRAME_PLAN_308}, + &PEGTransformerFactory::FinalizeAnyAllOperatorTrampoline, &FRAME_PLAN_AnyAllOperator}, {"AnyOrAll", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, - &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, + &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_ChoiceThrow}, {"SubqueryAny", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeSubqueryAnyTrampoline, &FRAME_PLAN_12}, + &PEGTransformerFactory::FinalizeSubqueryAnyTrampoline, &FRAME_PLAN_Leaf}, {"SubqueryAll", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeSubqueryAllTrampoline, &FRAME_PLAN_12}, + &PEGTransformerFactory::FinalizeSubqueryAllTrampoline, &FRAME_PLAN_Leaf}, {"QualifiedOperator", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeQualifiedOperatorTrampoline, &FRAME_PLAN_309}, + &PEGTransformerFactory::FinalizeQualifiedOperatorTrampoline, &FRAME_PLAN_QualifiedOperator}, {"QualifiedOperatorContents", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeQualifiedOperatorContentsTrampoline, &FRAME_PLAN_310}, + &PEGTransformerFactory::FinalizeQualifiedOperatorContentsTrampoline, &FRAME_PLAN_QualifiedOperatorContents}, {"BitwiseExpression", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeBitwiseExpressionTrampoline, &FRAME_PLAN_311}, + &PEGTransformerFactory::FinalizeBitwiseExpressionTrampoline, &FRAME_PLAN_BitwiseExpression}, {"BitwiseExpressionTail", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeBitwiseExpressionTailTrampoline, &FRAME_PLAN_312}, + &PEGTransformerFactory::FinalizeBitwiseExpressionTailTrampoline, &FRAME_PLAN_BitwiseExpressionTail}, {"BitOperator", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeBitOperatorTrampoline, &FRAME_PLAN_12}, + &PEGTransformerFactory::FinalizeBitOperatorTrampoline, &FRAME_PLAN_Leaf}, {"TildeExpression", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeTildeExpressionTrampoline, &FRAME_PLAN_313}, + &PEGTransformerFactory::FinalizeTildeExpressionTrampoline, &FRAME_PLAN_TildeExpression}, {"AdditiveExpression", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeAdditiveExpressionTrampoline, &FRAME_PLAN_314}, + &PEGTransformerFactory::FinalizeAdditiveExpressionTrampoline, &FRAME_PLAN_AdditiveExpression}, {"AdditiveExpressionTail", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeAdditiveExpressionTailTrampoline, &FRAME_PLAN_315}, + &PEGTransformerFactory::FinalizeAdditiveExpressionTailTrampoline, &FRAME_PLAN_AdditiveExpressionTail}, {"Term", &PEGTransformerFactory::InitializePlannedTrampoline, &PEGTransformerFactory::FinalizeTermTrampoline, - &FRAME_PLAN_12}, + &FRAME_PLAN_Leaf}, {"MultiplicativeExpression", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeMultiplicativeExpressionTrampoline, &FRAME_PLAN_316}, + &PEGTransformerFactory::FinalizeMultiplicativeExpressionTrampoline, &FRAME_PLAN_MultiplicativeExpression}, {"MultiplicativeExpressionTail", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeMultiplicativeExpressionTailTrampoline, &FRAME_PLAN_317}, + &PEGTransformerFactory::FinalizeMultiplicativeExpressionTailTrampoline, &FRAME_PLAN_MultiplicativeExpressionTail}, {"Factor", &PEGTransformerFactory::InitializePlannedTrampoline, &PEGTransformerFactory::FinalizeFactorTrampoline, - &FRAME_PLAN_12}, + &FRAME_PLAN_Leaf}, {"ExponentiationExpression", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeExponentiationExpressionTrampoline, &FRAME_PLAN_318}, + &PEGTransformerFactory::FinalizeExponentiationExpressionTrampoline, &FRAME_PLAN_ExponentiationExpression}, {"ExponentiationExpressionTail", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeExponentiationExpressionTailTrampoline, &FRAME_PLAN_319}, + &PEGTransformerFactory::FinalizeExponentiationExpressionTailTrampoline, &FRAME_PLAN_ExponentiationExpressionTail}, {"ExponentOperator", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeExponentOperatorTrampoline, &FRAME_PLAN_12}, + &PEGTransformerFactory::FinalizeExponentOperatorTrampoline, &FRAME_PLAN_Leaf}, {"CollateExpression", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeCollateExpressionTrampoline, &FRAME_PLAN_320}, + &PEGTransformerFactory::FinalizeCollateExpressionTrampoline, &FRAME_PLAN_CollateExpression}, {"CollateExpressionTail", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeCollateExpressionTailTrampoline, &FRAME_PLAN_321}, + &PEGTransformerFactory::FinalizeCollateExpressionTailTrampoline, &FRAME_PLAN_CollateExpressionTail}, {"AtTimeZoneExpression", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeAtTimeZoneExpressionTrampoline, &FRAME_PLAN_322}, + &PEGTransformerFactory::FinalizeAtTimeZoneExpressionTrampoline, &FRAME_PLAN_AtTimeZoneExpression}, {"AtTimeZoneExpressionTail", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeAtTimeZoneExpressionTailTrampoline, &FRAME_PLAN_323}, + &PEGTransformerFactory::FinalizeAtTimeZoneExpressionTailTrampoline, &FRAME_PLAN_AtTimeZoneExpressionTail}, {"UnaryExpression", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, - &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, + &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_ChoiceThrow}, {"PrefixExpression", &PEGTransformerFactory::InitializePrefixExpressionTrampoline, &PEGTransformerFactory::FinalizePrefixExpressionTrampoline, nullptr}, {"CustomPrefixExpression", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeCustomPrefixExpressionTrampoline, &FRAME_PLAN_324}, + &PEGTransformerFactory::FinalizeCustomPrefixExpressionTrampoline, &FRAME_PLAN_CustomPrefixExpression}, {"PrefixOperator", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, - &PEGTransformerFactory::FinalizePrefixOperatorTrampoline, &FRAME_PLAN_19}, + &PEGTransformerFactory::FinalizePrefixOperatorTrampoline, + &FRAME_PLAN_ChoiceEarlyIdentifierKeywordStringOperatorThrow}, {"MinusPrefixOperator", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeMinusPrefixOperatorTrampoline, &FRAME_PLAN_12}, + &PEGTransformerFactory::FinalizeMinusPrefixOperatorTrampoline, &FRAME_PLAN_Leaf}, {"PlusPrefixOperator", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizePlusPrefixOperatorTrampoline, &FRAME_PLAN_12}, + &PEGTransformerFactory::FinalizePlusPrefixOperatorTrampoline, &FRAME_PLAN_Leaf}, {"TildePrefixOperator", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeTildePrefixOperatorTrampoline, &FRAME_PLAN_12}, + &PEGTransformerFactory::FinalizeTildePrefixOperatorTrampoline, &FRAME_PLAN_Leaf}, {"BaseExpression", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeBaseExpressionTrampoline, &FRAME_PLAN_325}, + &PEGTransformerFactory::FinalizeBaseExpressionTrampoline, &FRAME_PLAN_BaseExpression}, {"IndirectionList", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeIndirectionListTrampoline, &FRAME_PLAN_326}, + &PEGTransformerFactory::FinalizeIndirectionListTrampoline, &FRAME_PLAN_IndirectionList}, {"Indirection", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, - &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, + &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_ChoiceThrow}, {"CastOperator", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeCastOperatorTrampoline, &FRAME_PLAN_105}, + &PEGTransformerFactory::FinalizeCastOperatorTrampoline, &FRAME_PLAN_CastOperator}, {"DotOperator", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, - &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, + &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_ChoiceThrow}, {"DotMethodOperator", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeDotMethodOperatorTrampoline, &FRAME_PLAN_327}, + &PEGTransformerFactory::FinalizeDotMethodOperatorTrampoline, &FRAME_PLAN_DotMethodOperator}, {"DotColumnOperator", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeDotColumnOperatorTrampoline, &FRAME_PLAN_147}, + &PEGTransformerFactory::FinalizeDotColumnOperatorTrampoline, &FRAME_PLAN_ColLabelParameter}, {"MethodExpression", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeMethodExpressionTrampoline, &FRAME_PLAN_328}, + &PEGTransformerFactory::FinalizeMethodExpressionTrampoline, &FRAME_PLAN_MethodExpression}, {"MethodExpressionArguments", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeMethodExpressionArgumentsTrampoline, &FRAME_PLAN_329}, + &PEGTransformerFactory::FinalizeMethodExpressionArgumentsTrampoline, &FRAME_PLAN_MethodExpressionArguments}, {"MethodExpressionArgumentList", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeMethodExpressionArgumentListTrampoline, &FRAME_PLAN_330}, + &PEGTransformerFactory::FinalizeMethodExpressionArgumentListTrampoline, &FRAME_PLAN_MethodExpressionArgumentList}, {"MethodFunctionArguments", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeMethodFunctionArgumentsTrampoline, &FRAME_PLAN_216}, + &PEGTransformerFactory::FinalizeMethodFunctionArgumentsTrampoline, &FRAME_PLAN_FunctionArgumentList}, {"SliceExpression", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeSliceExpressionTrampoline, &FRAME_PLAN_331}, + &PEGTransformerFactory::FinalizeSliceExpressionTrampoline, &FRAME_PLAN_SliceExpression}, {"SliceBound", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeSliceBoundTrampoline, &FRAME_PLAN_332}, + &PEGTransformerFactory::FinalizeSliceBoundTrampoline, &FRAME_PLAN_SliceBound}, {"SliceUpperBound", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, - &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, + &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_ChoiceThrow}, {"MinusStepSliceBound", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeMinusStepSliceBoundTrampoline, &FRAME_PLAN_333}, + &PEGTransformerFactory::FinalizeMinusStepSliceBoundTrampoline, &FRAME_PLAN_MinusStepSliceBound}, {"EndStepSliceBound", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeEndStepSliceBoundTrampoline, &FRAME_PLAN_334}, + &PEGTransformerFactory::FinalizeEndStepSliceBoundTrampoline, &FRAME_PLAN_EndStepSliceBound}, {"EndSliceBound", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeEndSliceBoundTrampoline, &FRAME_PLAN_66}, + &PEGTransformerFactory::FinalizeEndSliceBoundTrampoline, &FRAME_PLAN_EndSliceBound}, {"StepSliceBound", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeStepSliceBoundTrampoline, &FRAME_PLAN_66}, + &PEGTransformerFactory::FinalizeStepSliceBoundTrampoline, &FRAME_PLAN_EndSliceBound}, {"PostfixOperator", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizePostfixOperatorTrampoline, &FRAME_PLAN_12}, + &PEGTransformerFactory::FinalizePostfixOperatorTrampoline, &FRAME_PLAN_Leaf}, {"SpecialFunctionExpression", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, - &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, + &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_ChoiceThrow}, {"CoalesceExpression", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeCoalesceExpressionTrampoline, &FRAME_PLAN_335}, + &PEGTransformerFactory::FinalizeCoalesceExpressionTrampoline, &FRAME_PLAN_CoalesceExpression}, {"UnpackExpression", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeUnpackExpressionTrampoline, &FRAME_PLAN_134}, + &PEGTransformerFactory::FinalizeUnpackExpressionTrampoline, &FRAME_PLAN_CheckConstraint}, {"TryExpression", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeTryExpressionTrampoline, &FRAME_PLAN_134}, + &PEGTransformerFactory::FinalizeTryExpressionTrampoline, &FRAME_PLAN_CheckConstraint}, {"ColumnsExpression", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeColumnsExpressionTrampoline, &FRAME_PLAN_336}, + &PEGTransformerFactory::FinalizeColumnsExpressionTrampoline, &FRAME_PLAN_ColumnsExpression}, {"ExtractExpression", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeExtractExpressionTrampoline, &FRAME_PLAN_337}, + &PEGTransformerFactory::FinalizeExtractExpressionTrampoline, &FRAME_PLAN_ExtractExpression}, {"ExtractArguments", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeExtractArgumentsTrampoline, &FRAME_PLAN_338}, + &PEGTransformerFactory::FinalizeExtractArgumentsTrampoline, &FRAME_PLAN_ExtractArguments}, {"LambdaExpression", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeLambdaExpressionTrampoline, &FRAME_PLAN_339}, + &PEGTransformerFactory::FinalizeLambdaExpressionTrampoline, &FRAME_PLAN_LambdaExpression}, {"NullIfExpression", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeNullIfExpressionTrampoline, &FRAME_PLAN_340}, + &PEGTransformerFactory::FinalizeNullIfExpressionTrampoline, &FRAME_PLAN_NullIfExpression}, {"NullIfArguments", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeNullIfArgumentsTrampoline, &FRAME_PLAN_259}, + &PEGTransformerFactory::FinalizeNullIfArgumentsTrampoline, &FRAME_PLAN_MapStructField}, {"PositionExpression", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizePositionExpressionTrampoline, &FRAME_PLAN_341}, + &PEGTransformerFactory::FinalizePositionExpressionTrampoline, &FRAME_PLAN_PositionExpression}, {"PositionArguments", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizePositionArgumentsTrampoline, &FRAME_PLAN_342}, + &PEGTransformerFactory::FinalizePositionArgumentsTrampoline, &FRAME_PLAN_PositionArguments}, {"RowExpression", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeRowExpressionTrampoline, &FRAME_PLAN_343}, + &PEGTransformerFactory::FinalizeRowExpressionTrampoline, &FRAME_PLAN_RowExpression}, {"SubstringExpression", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeSubstringExpressionTrampoline, &FRAME_PLAN_344}, + &PEGTransformerFactory::FinalizeSubstringExpressionTrampoline, &FRAME_PLAN_SubstringExpression}, {"SubstringArguments", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, - &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, + &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_ChoiceThrow}, {"SubstringExpressionList", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeSubstringExpressionListTrampoline, &FRAME_PLAN_345}, + &PEGTransformerFactory::FinalizeSubstringExpressionListTrampoline, &FRAME_PLAN_OverlayExpressionList}, {"SubstringParameters", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeSubstringParametersTrampoline, &FRAME_PLAN_346}, + &PEGTransformerFactory::FinalizeSubstringParametersTrampoline, &FRAME_PLAN_SubstringParameters}, {"SubstringFromFor", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, - &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, + &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_ChoiceThrow}, {"SubstringFromOptionalFor", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeSubstringFromOptionalForTrampoline, &FRAME_PLAN_347}, + &PEGTransformerFactory::FinalizeSubstringFromOptionalForTrampoline, &FRAME_PLAN_SubstringFromOptionalFor}, {"SubstringFor", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeSubstringForTrampoline, &FRAME_PLAN_348}, + &PEGTransformerFactory::FinalizeSubstringForTrampoline, &FRAME_PLAN_SubstringFor}, {"TrimExpression", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeTrimExpressionTrampoline, &FRAME_PLAN_349}, + &PEGTransformerFactory::FinalizeTrimExpressionTrampoline, &FRAME_PLAN_TrimExpression}, {"TrimArguments", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeTrimArgumentsTrampoline, &FRAME_PLAN_350}, + &PEGTransformerFactory::FinalizeTrimArgumentsTrampoline, &FRAME_PLAN_TrimArguments}, {"TrimDirection", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, - &PEGTransformerFactory::FinalizeTrimDirectionTrampoline, &FRAME_PLAN_19}, + &PEGTransformerFactory::FinalizeTrimDirectionTrampoline, + &FRAME_PLAN_ChoiceEarlyIdentifierKeywordStringOperatorThrow}, {"TrimBoth", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeTrimBothTrampoline, &FRAME_PLAN_12}, + &PEGTransformerFactory::FinalizeTrimBothTrampoline, &FRAME_PLAN_Leaf}, {"TrimLeading", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeTrimLeadingTrampoline, &FRAME_PLAN_12}, + &PEGTransformerFactory::FinalizeTrimLeadingTrampoline, &FRAME_PLAN_Leaf}, {"TrimTrailing", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeTrimTrailingTrampoline, &FRAME_PLAN_12}, + &PEGTransformerFactory::FinalizeTrimTrailingTrampoline, &FRAME_PLAN_Leaf}, {"TrimSource", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeTrimSourceTrampoline, &FRAME_PLAN_351}, + &PEGTransformerFactory::FinalizeTrimSourceTrampoline, &FRAME_PLAN_TrimSource}, {"OverlayExpression", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeOverlayExpressionTrampoline, &FRAME_PLAN_352}, + &PEGTransformerFactory::FinalizeOverlayExpressionTrampoline, &FRAME_PLAN_OverlayExpression}, {"OverlayArguments", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, - &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, + &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_ChoiceThrow}, {"OverlayParameters", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeOverlayParametersTrampoline, &FRAME_PLAN_353}, + &PEGTransformerFactory::FinalizeOverlayParametersTrampoline, &FRAME_PLAN_OverlayParameters}, {"FromExpression", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeFromExpressionTrampoline, &FRAME_PLAN_21}, + &PEGTransformerFactory::FinalizeFromExpressionTrampoline, &FRAME_PLAN_AndExpression}, {"ForExpression", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeForExpressionTrampoline, &FRAME_PLAN_21}, + &PEGTransformerFactory::FinalizeForExpressionTrampoline, &FRAME_PLAN_AndExpression}, {"OverlayExpressionList", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeOverlayExpressionListTrampoline, &FRAME_PLAN_345}, + &PEGTransformerFactory::FinalizeOverlayExpressionListTrampoline, &FRAME_PLAN_OverlayExpressionList}, {"ExtractArgument", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, - &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, + &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_ChoiceThrow}, {"ExtractDatePartArgument", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeExtractDatePartArgumentTrampoline, &FRAME_PLAN_354}, + &PEGTransformerFactory::FinalizeExtractDatePartArgumentTrampoline, &FRAME_PLAN_ExtractDatePartArgument}, {"ExtractIdentifierArgument", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeExtractIdentifierArgumentTrampoline, &FRAME_PLAN_12}, + &PEGTransformerFactory::FinalizeExtractIdentifierArgumentTrampoline, &FRAME_PLAN_Leaf}, {"ExtractStringArgument", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeExtractStringArgumentTrampoline, &FRAME_PLAN_12}, + &PEGTransformerFactory::FinalizeExtractStringArgumentTrampoline, &FRAME_PLAN_Leaf}, {"ExtractDatePart", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, - &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, + &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_ChoiceThrow}, {"ExternalResourceStatement", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, - &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, + &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_ChoiceThrow}, {"CreateExternalResourceStmt", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeCreateExternalResourceStmtTrampoline, &FRAME_PLAN_355}, + &PEGTransformerFactory::FinalizeCreateExternalResourceStmtTrampoline, &FRAME_PLAN_CreateExternalResourceStmt}, {"RegisterExternalResourceStmt", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeRegisterExternalResourceStmtTrampoline, &FRAME_PLAN_356}, + &PEGTransformerFactory::FinalizeRegisterExternalResourceStmtTrampoline, &FRAME_PLAN_RegisterExternalResourceStmt}, {"DestroyExternalResourceStmt", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeDestroyExternalResourceStmtTrampoline, &FRAME_PLAN_357}, + &PEGTransformerFactory::FinalizeDestroyExternalResourceStmtTrampoline, &FRAME_PLAN_DestroyExternalResourceStmt}, {"ExternalResourceType", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, - &PEGTransformerFactory::FinalizeExternalResourceTypeTrampoline, &FRAME_PLAN_19}, + &PEGTransformerFactory::FinalizeExternalResourceTypeTrampoline, + &FRAME_PLAN_ChoiceEarlyIdentifierKeywordStringOperatorThrow}, {"ExternalResourceTypeName", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeExternalResourceTypeNameTrampoline, &FRAME_PLAN_358}, + &PEGTransformerFactory::FinalizeExternalResourceTypeNameTrampoline, &FRAME_PLAN_ExternalResourceTypeName}, {"BareName", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, - &PEGTransformerFactory::FinalizeBareNameTrampoline, &FRAME_PLAN_149}, + &PEGTransformerFactory::FinalizeBareNameTrampoline, &FRAME_PLAN_ChoiceEarlyIdentifierKeywordStringEmptyNameThrow}, {"ExternalResourceCreationOptions", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_33}, + &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_AttachOptions}, {"AttachToExternalResource", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeAttachToExternalResourceTrampoline, &FRAME_PLAN_359}, + &PEGTransformerFactory::FinalizeAttachToExternalResourceTrampoline, &FRAME_PLAN_AttachToExternalResource}, {"ConnectToExternalResource", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeConnectToExternalResourceTrampoline, &FRAME_PLAN_360}, + &PEGTransformerFactory::FinalizeConnectToExternalResourceTrampoline, &FRAME_PLAN_ConnectToExternalResource}, {"ExternalResourceSource", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, - &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, + &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_ChoiceThrow}, {"ExternalResourceCreateClause", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeExternalResourceCreateClauseTrampoline, &FRAME_PLAN_361}, + &PEGTransformerFactory::FinalizeExternalResourceCreateClauseTrampoline, &FRAME_PLAN_ExternalResourceCreateClause}, {"ExternalResourceReferenceClause", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeExternalResourceReferenceClauseTrampoline, &FRAME_PLAN_32}, + &PEGTransformerFactory::FinalizeExternalResourceReferenceClauseTrampoline, &FRAME_PLAN_AttachAlias}, {"InsertStatement", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeInsertStatementTrampoline, &FRAME_PLAN_362}, + &PEGTransformerFactory::FinalizeInsertStatementTrampoline, &FRAME_PLAN_InsertStatement}, {"OrAction", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, - &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, + &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_ChoiceThrow}, {"InsertOrReplace", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeInsertOrReplaceTrampoline, &FRAME_PLAN_12}, + &PEGTransformerFactory::FinalizeInsertOrReplaceTrampoline, &FRAME_PLAN_Leaf}, {"InsertOrIgnore", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeInsertOrIgnoreTrampoline, &FRAME_PLAN_12}, + &PEGTransformerFactory::FinalizeInsertOrIgnoreTrampoline, &FRAME_PLAN_Leaf}, {"ByNameOrPosition", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, - &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, + &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_ChoiceThrow}, {"InsertByNameOrder", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_363}, + &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_InsertByNameOrder}, {"InsertByPositionOrder", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_364}, + &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_InsertByPositionOrder}, {"InsertByName", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeInsertByNameTrampoline, &FRAME_PLAN_12}, + &PEGTransformerFactory::FinalizeInsertByNameTrampoline, &FRAME_PLAN_Leaf}, {"InsertByPosition", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeInsertByPositionTrampoline, &FRAME_PLAN_12}, + &PEGTransformerFactory::FinalizeInsertByPositionTrampoline, &FRAME_PLAN_Leaf}, {"InsertTarget", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeInsertTargetTrampoline, &FRAME_PLAN_365}, + &PEGTransformerFactory::FinalizeInsertTargetTrampoline, &FRAME_PLAN_InsertTarget}, {"InsertAlias", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeInsertAliasTrampoline, &FRAME_PLAN_12}, + &PEGTransformerFactory::FinalizeInsertAliasTrampoline, &FRAME_PLAN_Leaf}, {"ColumnList", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeColumnListTrampoline, &FRAME_PLAN_160}, + &PEGTransformerFactory::FinalizeColumnListTrampoline, &FRAME_PLAN_ColumnList}, {"InsertColumnList", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeInsertColumnListTrampoline, &FRAME_PLAN_82}, + &PEGTransformerFactory::FinalizeInsertColumnListTrampoline, &FRAME_PLAN_InsertColumnList}, {"InsertValues", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, - &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, + &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_ChoiceThrow}, {"SelectInsertValues", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeSelectInsertValuesTrampoline, &FRAME_PLAN_207}, + &PEGTransformerFactory::FinalizeSelectInsertValuesTrampoline, &FRAME_PLAN_ExplainSelectStatement}, {"DefaultValues", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeDefaultValuesTrampoline, &FRAME_PLAN_12}, + &PEGTransformerFactory::FinalizeDefaultValuesTrampoline, &FRAME_PLAN_Leaf}, {"OnConflictClause", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeOnConflictClauseTrampoline, &FRAME_PLAN_366}, + &PEGTransformerFactory::FinalizeOnConflictClauseTrampoline, &FRAME_PLAN_OnConflictClause}, {"OnConflictTarget", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, - &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, + &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_ChoiceThrow}, {"OnConflictExpressionTarget", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeOnConflictExpressionTargetTrampoline, &FRAME_PLAN_367}, + &PEGTransformerFactory::FinalizeOnConflictExpressionTargetTrampoline, &FRAME_PLAN_OnConflictExpressionTarget}, {"OnConflictIndexTarget", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeOnConflictIndexTargetTrampoline, &FRAME_PLAN_368}, + &PEGTransformerFactory::FinalizeOnConflictIndexTargetTrampoline, &FRAME_PLAN_OnConflictIndexTarget}, {"OnConflictAction", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, - &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, + &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_ChoiceThrow}, {"OnConflictUpdate", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeOnConflictUpdateTrampoline, &FRAME_PLAN_369}, + &PEGTransformerFactory::FinalizeOnConflictUpdateTrampoline, &FRAME_PLAN_OnConflictUpdate}, {"OnConflictNothing", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeOnConflictNothingTrampoline, &FRAME_PLAN_12}, + &PEGTransformerFactory::FinalizeOnConflictNothingTrampoline, &FRAME_PLAN_Leaf}, {"ReturningClause", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeReturningClauseTrampoline, &FRAME_PLAN_370}, + &PEGTransformerFactory::FinalizeReturningClauseTrampoline, &FRAME_PLAN_PivotUsing}, {"LoadStatement", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeLoadStatementTrampoline, &FRAME_PLAN_371}, + &PEGTransformerFactory::FinalizeLoadStatementTrampoline, &FRAME_PLAN_LoadStatement}, {"ExtensionAlias", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeExtensionAliasTrampoline, &FRAME_PLAN_12}, + &PEGTransformerFactory::FinalizeExtensionAliasTrampoline, &FRAME_PLAN_Leaf}, {"InstallStatement", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeInstallStatementTrampoline, &FRAME_PLAN_372}, + &PEGTransformerFactory::FinalizeInstallStatementTrampoline, &FRAME_PLAN_InstallStatement}, {"InstallAndLoad", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeInstallAndLoadTrampoline, &FRAME_PLAN_12}, + &PEGTransformerFactory::FinalizeInstallAndLoadTrampoline, &FRAME_PLAN_Leaf}, {"UpdateExtensionsStatement", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeUpdateExtensionsStatementTrampoline, &FRAME_PLAN_12}, + &PEGTransformerFactory::FinalizeUpdateExtensionsStatementTrampoline, &FRAME_PLAN_Leaf}, {"FromSource", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, - &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, + &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_ChoiceThrow}, {"FromSourceIdentifier", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeFromSourceIdentifierTrampoline, &FRAME_PLAN_373}, + &PEGTransformerFactory::FinalizeFromSourceIdentifierTrampoline, &FRAME_PLAN_FromSourceIdentifier}, {"FromSourceString", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeFromSourceStringTrampoline, &FRAME_PLAN_12}, + &PEGTransformerFactory::FinalizeFromSourceStringTrampoline, &FRAME_PLAN_Leaf}, {"FromSourceName", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, - &PEGTransformerFactory::FinalizeFromSourceNameTrampoline, &FRAME_PLAN_374}, + &PEGTransformerFactory::FinalizeFromSourceNameTrampoline, &FRAME_PLAN_FromSourceName}, {"VersionNumber", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeVersionNumberTrampoline, &FRAME_PLAN_375}, + &PEGTransformerFactory::FinalizeVersionNumberTrampoline, &FRAME_PLAN_VersionNumber}, {"ExtensionRepositoryStatement", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, - &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, + &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_ChoiceThrow}, {"CreateExtensionRepositoryStmt", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeCreateExtensionRepositoryStmtTrampoline, &FRAME_PLAN_376}, + &PEGTransformerFactory::FinalizeCreateExtensionRepositoryStmtTrampoline, + &FRAME_PLAN_CreateExtensionRepositoryStmt}, {"RepositoryPrefix", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeRepositoryPrefixTrampoline, &FRAME_PLAN_12}, + &PEGTransformerFactory::FinalizeRepositoryPrefixTrampoline, &FRAME_PLAN_Leaf}, {"RepositoryPublicKey", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeRepositoryPublicKeyTrampoline, &FRAME_PLAN_12}, + &PEGTransformerFactory::FinalizeRepositoryPublicKeyTrampoline, &FRAME_PLAN_Leaf}, {"CreateExtensionRepositoryFromHostStmt", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeCreateExtensionRepositoryFromHostStmtTrampoline, &FRAME_PLAN_377}, + &PEGTransformerFactory::FinalizeCreateExtensionRepositoryFromHostStmtTrampoline, + &FRAME_PLAN_CreateExtensionRepositoryFromHostStmt}, {"DropExtensionRepositoryStmt", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeDropExtensionRepositoryStmtTrampoline, &FRAME_PLAN_378}, + &PEGTransformerFactory::FinalizeDropExtensionRepositoryStmtTrampoline, &FRAME_PLAN_DropExtensionRepositoryStmt}, {"ExtensionRepositoryName", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, - &PEGTransformerFactory::FinalizeExtensionRepositoryNameTrampoline, &FRAME_PLAN_149}, + &PEGTransformerFactory::FinalizeExtensionRepositoryNameTrampoline, + &FRAME_PLAN_ChoiceEarlyIdentifierKeywordStringEmptyNameThrow}, {"TableMatchRecognizeClause", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeTableMatchRecognizeClauseTrampoline, &FRAME_PLAN_379}, + &PEGTransformerFactory::FinalizeTableMatchRecognizeClauseTrampoline, &FRAME_PLAN_TableMatchRecognizeClause}, {"MatchRecognizeBody", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeMatchRecognizeBodyTrampoline, &FRAME_PLAN_380}, + &PEGTransformerFactory::FinalizeMatchRecognizeBodyTrampoline, &FRAME_PLAN_MatchRecognizeBody}, {"MatchRecognizeClause", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, - &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, + &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_ChoiceThrow}, {"MRPartition", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeMRPartitionTrampoline, &FRAME_PLAN_381}, + &PEGTransformerFactory::FinalizeMRPartitionTrampoline, &FRAME_PLAN_MRPartition}, {"MROrderBy", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeMROrderByTrampoline, &FRAME_PLAN_382}, + &PEGTransformerFactory::FinalizeMROrderByTrampoline, &FRAME_PLAN_MROrderBy}, {"MRMeasures", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeMRMeasuresTrampoline, &FRAME_PLAN_383}, + &PEGTransformerFactory::FinalizeMRMeasuresTrampoline, &FRAME_PLAN_MRMeasures}, {"MRRows", &PEGTransformerFactory::InitializePlannedTrampoline, &PEGTransformerFactory::FinalizeMRRowsTrampoline, - &FRAME_PLAN_384}, + &FRAME_PLAN_MRRows}, {"MRSkip", &PEGTransformerFactory::InitializePlannedTrampoline, &PEGTransformerFactory::FinalizeMRSkipTrampoline, - &FRAME_PLAN_385}, + &FRAME_PLAN_MRSkip}, {"MRPattern", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeMRPatternTrampoline, &FRAME_PLAN_386}, + &PEGTransformerFactory::FinalizeMRPatternTrampoline, &FRAME_PLAN_MRPattern}, {"MRSubset", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeMRSubsetTrampoline, &FRAME_PLAN_387}, + &PEGTransformerFactory::FinalizeMRSubsetTrampoline, &FRAME_PLAN_MRSubset}, {"MRDefineAuto", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeMRDefineAutoTrampoline, &FRAME_PLAN_12}, + &PEGTransformerFactory::FinalizeMRDefineAutoTrampoline, &FRAME_PLAN_Leaf}, {"MRDefine", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeMRDefineTrampoline, &FRAME_PLAN_388}, + &PEGTransformerFactory::FinalizeMRDefineTrampoline, &FRAME_PLAN_MRDefine}, {"MeasuresClause", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeMeasuresClauseTrampoline, &FRAME_PLAN_389}, + &PEGTransformerFactory::FinalizeMeasuresClauseTrampoline, &FRAME_PLAN_MeasuresClause}, {"MeasuresElement", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeMeasuresElementTrampoline, &FRAME_PLAN_390}, + &PEGTransformerFactory::FinalizeMeasuresElementTrampoline, &FRAME_PLAN_ExpressionAsCollabel}, {"MeasureSemantics", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, - &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, + &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_ChoiceThrow}, {"RunningSemantics", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeRunningSemanticsTrampoline, &FRAME_PLAN_12}, + &PEGTransformerFactory::FinalizeRunningSemanticsTrampoline, &FRAME_PLAN_Leaf}, {"FinalSemantics", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeFinalSemanticsTrampoline, &FRAME_PLAN_12}, + &PEGTransformerFactory::FinalizeFinalSemanticsTrampoline, &FRAME_PLAN_Leaf}, {"RowsPerMatch", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, - &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, + &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_ChoiceThrow}, {"OneRowPerMatch", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeOneRowPerMatchTrampoline, &FRAME_PLAN_12}, + &PEGTransformerFactory::FinalizeOneRowPerMatchTrampoline, &FRAME_PLAN_Leaf}, {"AllRowsPerMatch", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeAllRowsPerMatchTrampoline, &FRAME_PLAN_391}, + &PEGTransformerFactory::FinalizeAllRowsPerMatchTrampoline, &FRAME_PLAN_AllRowsPerMatch}, {"AllRowsEmptyMatches", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, - &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, + &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_ChoiceThrow}, {"ShowEmptyMatches", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeShowEmptyMatchesTrampoline, &FRAME_PLAN_12}, + &PEGTransformerFactory::FinalizeShowEmptyMatchesTrampoline, &FRAME_PLAN_Leaf}, {"OmitEmptyMatches", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeOmitEmptyMatchesTrampoline, &FRAME_PLAN_12}, + &PEGTransformerFactory::FinalizeOmitEmptyMatchesTrampoline, &FRAME_PLAN_Leaf}, {"WithUnmatchedRows", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeWithUnmatchedRowsTrampoline, &FRAME_PLAN_12}, + &PEGTransformerFactory::FinalizeWithUnmatchedRowsTrampoline, &FRAME_PLAN_Leaf}, {"AfterMatchSkip", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_392}, + &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_AfterMatchSkip}, {"AfterMatchSkipTarget", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, - &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, + &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_ChoiceThrow}, {"SkipToNextRow", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeSkipToNextRowTrampoline, &FRAME_PLAN_12}, + &PEGTransformerFactory::FinalizeSkipToNextRowTrampoline, &FRAME_PLAN_Leaf}, {"SkipPastLastRow", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeSkipPastLastRowTrampoline, &FRAME_PLAN_12}, + &PEGTransformerFactory::FinalizeSkipPastLastRowTrampoline, &FRAME_PLAN_Leaf}, {"SkipToFirstVar", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeSkipToFirstVarTrampoline, &FRAME_PLAN_393}, + &PEGTransformerFactory::FinalizeSkipToFirstVarTrampoline, &FRAME_PLAN_SkipToFirstVar}, {"SkipToLastVar", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeSkipToLastVarTrampoline, &FRAME_PLAN_393}, + &PEGTransformerFactory::FinalizeSkipToLastVarTrampoline, &FRAME_PLAN_SkipToFirstVar}, {"SkipToVar", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeSkipToVarTrampoline, &FRAME_PLAN_394}, + &PEGTransformerFactory::FinalizeSkipToVarTrampoline, &FRAME_PLAN_SkipToVar}, {"PatternClause", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_395}, + &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_PatternClause}, {"RowPattern", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeRowPatternTrampoline, &FRAME_PLAN_396}, + &PEGTransformerFactory::FinalizeRowPatternTrampoline, &FRAME_PLAN_RowPattern}, {"RowPatternAlternative", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_397}, + &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_RowPatternAlternative}, {"RowPatternTerm", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeRowPatternTermTrampoline, &FRAME_PLAN_398}, + &PEGTransformerFactory::FinalizeRowPatternTermTrampoline, &FRAME_PLAN_RowPatternTerm}, {"RowPatternFactor", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeRowPatternFactorTrampoline, &FRAME_PLAN_399}, + &PEGTransformerFactory::FinalizeRowPatternFactorTrampoline, &FRAME_PLAN_RowPatternFactor}, {"RowPatternPrimary", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, - &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, + &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_ChoiceThrow}, {"RowPatternPermute", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeRowPatternPermuteTrampoline, &FRAME_PLAN_400}, + &PEGTransformerFactory::FinalizeRowPatternPermuteTrampoline, &FRAME_PLAN_RowPatternPermute}, {"RowPatternAnchor", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, - &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, + &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_ChoiceThrow}, {"PatternStart", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizePatternStartTrampoline, &FRAME_PLAN_12}, + &PEGTransformerFactory::FinalizePatternStartTrampoline, &FRAME_PLAN_Leaf}, {"PatternEnd", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizePatternEndTrampoline, &FRAME_PLAN_12}, + &PEGTransformerFactory::FinalizePatternEndTrampoline, &FRAME_PLAN_Leaf}, {"RowPatternGroup", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_401}, + &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_RowPatternGroup}, {"RowPatternEmpty", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeRowPatternEmptyTrampoline, &FRAME_PLAN_12}, + &PEGTransformerFactory::FinalizeRowPatternEmptyTrampoline, &FRAME_PLAN_Leaf}, {"RowPatternExclusion", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeRowPatternExclusionTrampoline, &FRAME_PLAN_402}, + &PEGTransformerFactory::FinalizeRowPatternExclusionTrampoline, &FRAME_PLAN_RowPatternExclusion}, {"RowPatternLabel", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeRowPatternLabelTrampoline, &FRAME_PLAN_403}, + &PEGTransformerFactory::FinalizeRowPatternLabelTrampoline, &FRAME_PLAN_RowPatternLabel}, {"RowPatternQuantifier", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeRowPatternQuantifierTrampoline, &FRAME_PLAN_404}, + &PEGTransformerFactory::FinalizeRowPatternQuantifierTrampoline, &FRAME_PLAN_RowPatternQuantifier}, {"RowPatternQuantifierKind", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, - &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, + &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_ChoiceThrow}, {"QuantifierReluctant", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeQuantifierReluctantTrampoline, &FRAME_PLAN_12}, + &PEGTransformerFactory::FinalizeQuantifierReluctantTrampoline, &FRAME_PLAN_Leaf}, {"QuantifierStar", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeQuantifierStarTrampoline, &FRAME_PLAN_12}, + &PEGTransformerFactory::FinalizeQuantifierStarTrampoline, &FRAME_PLAN_Leaf}, {"QuantifierPlus", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeQuantifierPlusTrampoline, &FRAME_PLAN_12}, + &PEGTransformerFactory::FinalizeQuantifierPlusTrampoline, &FRAME_PLAN_Leaf}, {"QuantifierOptional", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeQuantifierOptionalTrampoline, &FRAME_PLAN_12}, + &PEGTransformerFactory::FinalizeQuantifierOptionalTrampoline, &FRAME_PLAN_Leaf}, {"QuantifierRange", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_405}, + &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_QuantifierRange}, {"QuantifierBounds", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, - &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, + &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_ChoiceThrow}, {"QuantifierMinMax", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeQuantifierMinMaxTrampoline, &FRAME_PLAN_12}, + &PEGTransformerFactory::FinalizeQuantifierMinMaxTrampoline, &FRAME_PLAN_Leaf}, {"QuantifierMin", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeQuantifierMinTrampoline, &FRAME_PLAN_12}, + &PEGTransformerFactory::FinalizeQuantifierMinTrampoline, &FRAME_PLAN_Leaf}, {"QuantifierMax", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeQuantifierMaxTrampoline, &FRAME_PLAN_12}, + &PEGTransformerFactory::FinalizeQuantifierMaxTrampoline, &FRAME_PLAN_Leaf}, {"QuantifierExact", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeQuantifierExactTrampoline, &FRAME_PLAN_12}, + &PEGTransformerFactory::FinalizeQuantifierExactTrampoline, &FRAME_PLAN_Leaf}, {"SubsetClause", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeSubsetClauseTrampoline, &FRAME_PLAN_406}, + &PEGTransformerFactory::FinalizeSubsetClauseTrampoline, &FRAME_PLAN_SubsetClause}, {"SubsetElement", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeSubsetElementTrampoline, &FRAME_PLAN_407}, + &PEGTransformerFactory::FinalizeSubsetElementTrampoline, &FRAME_PLAN_SubsetElement}, {"DefineClause", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeDefineClauseTrampoline, &FRAME_PLAN_408}, + &PEGTransformerFactory::FinalizeDefineClauseTrampoline, &FRAME_PLAN_DefineClause}, {"DefineElement", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeDefineElementTrampoline, &FRAME_PLAN_409}, + &PEGTransformerFactory::FinalizeDefineElementTrampoline, &FRAME_PLAN_DefineElement}, {"MergeIntoStatement", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeMergeIntoStatementTrampoline, &FRAME_PLAN_410}, + &PEGTransformerFactory::FinalizeMergeIntoStatementTrampoline, &FRAME_PLAN_MergeIntoStatement}, {"MergeIntoUsingClause", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeMergeIntoUsingClauseTrampoline, &FRAME_PLAN_411}, + &PEGTransformerFactory::FinalizeMergeIntoUsingClauseTrampoline, &FRAME_PLAN_MergeIntoUsingClause}, {"MergeMatch", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, - &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, + &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_ChoiceThrow}, {"MatchedClause", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeMatchedClauseTrampoline, &FRAME_PLAN_412}, + &PEGTransformerFactory::FinalizeMatchedClauseTrampoline, &FRAME_PLAN_MatchedClause}, {"MatchedClauseAction", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, - &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, + &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_ChoiceThrow}, {"UpdateMatchClause", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeUpdateMatchClauseTrampoline, &FRAME_PLAN_413}, + &PEGTransformerFactory::FinalizeUpdateMatchClauseTrampoline, &FRAME_PLAN_UpdateMatchClause}, {"UpdateMatchInfo", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, - &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, + &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_ChoiceThrow}, {"UpdateMatchSetAction", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeUpdateMatchSetActionTrampoline, &FRAME_PLAN_414}, + &PEGTransformerFactory::FinalizeUpdateMatchSetActionTrampoline, &FRAME_PLAN_UpdateMatchSetAction}, {"UpdateByNameOrPosition", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeUpdateByNameOrPositionTrampoline, &FRAME_PLAN_415}, + &PEGTransformerFactory::FinalizeUpdateByNameOrPositionTrampoline, &FRAME_PLAN_UpdateByNameOrPosition}, {"DeleteMatchClause", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeDeleteMatchClauseTrampoline, &FRAME_PLAN_12}, + &PEGTransformerFactory::FinalizeDeleteMatchClauseTrampoline, &FRAME_PLAN_Leaf}, {"InsertMatchClause", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeInsertMatchClauseTrampoline, &FRAME_PLAN_416}, + &PEGTransformerFactory::FinalizeInsertMatchClauseTrampoline, &FRAME_PLAN_InsertMatchClause}, {"InsertMatchInfo", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, - &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, + &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_ChoiceThrow}, {"InsertDefaultValues", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeInsertDefaultValuesTrampoline, &FRAME_PLAN_12}, + &PEGTransformerFactory::FinalizeInsertDefaultValuesTrampoline, &FRAME_PLAN_Leaf}, {"InsertByNameOrPosition", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeInsertByNameOrPositionTrampoline, &FRAME_PLAN_417}, + &PEGTransformerFactory::FinalizeInsertByNameOrPositionTrampoline, &FRAME_PLAN_InsertByNameOrPosition}, {"InsertValuesList", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeInsertValuesListTrampoline, &FRAME_PLAN_418}, + &PEGTransformerFactory::FinalizeInsertValuesListTrampoline, &FRAME_PLAN_InsertValuesList}, {"DoNothingMatchClause", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeDoNothingMatchClauseTrampoline, &FRAME_PLAN_12}, + &PEGTransformerFactory::FinalizeDoNothingMatchClauseTrampoline, &FRAME_PLAN_Leaf}, {"ErrorMatchClause", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeErrorMatchClauseTrampoline, &FRAME_PLAN_66}, + &PEGTransformerFactory::FinalizeErrorMatchClauseTrampoline, &FRAME_PLAN_EndSliceBound}, {"UpdateMatchSetClause", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_419}, + &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_UpdateMatchSetClause}, {"UpdateMatchSetInfo", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, - &PEGTransformerFactory::FinalizeUpdateMatchSetInfoTrampoline, &FRAME_PLAN_80}, + &PEGTransformerFactory::FinalizeUpdateMatchSetInfoTrampoline, &FRAME_PLAN_StarSymbolColumnList}, {"AndExpression", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeAndExpressionTrampoline, &FRAME_PLAN_21}, + &PEGTransformerFactory::FinalizeAndExpressionTrampoline, &FRAME_PLAN_AndExpression}, {"NotMatchedClause", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeNotMatchedClauseTrampoline, &FRAME_PLAN_420}, + &PEGTransformerFactory::FinalizeNotMatchedClauseTrampoline, &FRAME_PLAN_NotMatchedClause}, {"BySourceOrTarget", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, - &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, + &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_ChoiceThrow}, {"BySource", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeBySourceTrampoline, &FRAME_PLAN_12}, + &PEGTransformerFactory::FinalizeBySourceTrampoline, &FRAME_PLAN_Leaf}, {"ByTarget", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeByTargetTrampoline, &FRAME_PLAN_12}, + &PEGTransformerFactory::FinalizeByTargetTrampoline, &FRAME_PLAN_Leaf}, {"PivotStatement", &PEGTransformerFactory::InitializePivotStatementTrampoline, &PEGTransformerFactory::FinalizePivotStatementTrampoline, nullptr}, {"PivotOn", &PEGTransformerFactory::InitializePlannedTrampoline, &PEGTransformerFactory::FinalizePivotOnTrampoline, - &FRAME_PLAN_421}, + &FRAME_PLAN_PivotOn}, {"PivotUsing", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizePivotUsingTrampoline, &FRAME_PLAN_370}, + &PEGTransformerFactory::FinalizePivotUsingTrampoline, &FRAME_PLAN_PivotUsing}, {"PivotColumnList", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizePivotColumnListTrampoline, &FRAME_PLAN_422}, + &PEGTransformerFactory::FinalizePivotColumnListTrampoline, &FRAME_PLAN_PivotColumnList}, {"PivotColumnEntry", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, - &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, + &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_ChoiceThrow}, {"PivotColumnExpression", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizePivotColumnExpressionTrampoline, &FRAME_PLAN_31}, + &PEGTransformerFactory::FinalizePivotColumnExpressionTrampoline, &FRAME_PLAN_DatabasePath}, {"PivotColumnSubquery", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizePivotColumnSubqueryTrampoline, &FRAME_PLAN_423}, + &PEGTransformerFactory::FinalizePivotColumnSubqueryTrampoline, &FRAME_PLAN_PivotColumnSubquery}, {"UnpivotStatement", &PEGTransformerFactory::InitializeUnpivotStatementTrampoline, &PEGTransformerFactory::FinalizeUnpivotStatementTrampoline, nullptr}, {"IntoNameValues", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeIntoNameValuesTrampoline, &FRAME_PLAN_424}, + &PEGTransformerFactory::FinalizeIntoNameValuesTrampoline, &FRAME_PLAN_IntoNameValues}, {"OptionalParensNameList", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, - &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, + &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_ChoiceThrow}, {"ParenthesizedNameList", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeParenthesizedNameListTrampoline, &FRAME_PLAN_425}, + &PEGTransformerFactory::FinalizeParenthesizedNameListTrampoline, &FRAME_PLAN_ColumnAliases}, {"BareNameList", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeBareNameListTrampoline, &FRAME_PLAN_426}, + &PEGTransformerFactory::FinalizeBareNameListTrampoline, &FRAME_PLAN_BareNameList}, {"IncludeOrExcludeNulls", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, - &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, + &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_ChoiceThrow}, {"IncludeNulls", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeIncludeNullsTrampoline, &FRAME_PLAN_12}, + &PEGTransformerFactory::FinalizeIncludeNullsTrampoline, &FRAME_PLAN_Leaf}, {"ExcludeNulls", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeExcludeNullsTrampoline, &FRAME_PLAN_12}, + &PEGTransformerFactory::FinalizeExcludeNullsTrampoline, &FRAME_PLAN_Leaf}, {"UnpivotHeader", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, - &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, + &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_ChoiceThrow}, {"UnpivotHeaderSingle", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeUnpivotHeaderSingleTrampoline, &FRAME_PLAN_38}, + &PEGTransformerFactory::FinalizeUnpivotHeaderSingleTrampoline, &FRAME_PLAN_ConstraintName}, {"UnpivotHeaderList", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeUnpivotHeaderListTrampoline, &FRAME_PLAN_425}, + &PEGTransformerFactory::FinalizeUnpivotHeaderListTrampoline, &FRAME_PLAN_ColumnAliases}, {"PragmaStatement", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizePragmaStatementTrampoline, &FRAME_PLAN_427}, + &PEGTransformerFactory::FinalizePragmaStatementTrampoline, &FRAME_PLAN_PragmaStatement}, {"PragmaAssignOrFunction", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, - &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, + &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_ChoiceThrow}, {"PragmaAssign", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizePragmaAssignTrampoline, &FRAME_PLAN_428}, + &PEGTransformerFactory::FinalizePragmaAssignTrampoline, &FRAME_PLAN_PragmaAssign}, {"PragmaFunction", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizePragmaFunctionTrampoline, &FRAME_PLAN_429}, + &PEGTransformerFactory::FinalizePragmaFunctionTrampoline, &FRAME_PLAN_PragmaFunction}, {"PragmaParameters", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizePragmaParametersTrampoline, &FRAME_PLAN_297}, + &PEGTransformerFactory::FinalizePragmaParametersTrampoline, &FRAME_PLAN_InExpressionList}, {"PrepareStatement", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizePrepareStatementTrampoline, &FRAME_PLAN_430}, + &PEGTransformerFactory::FinalizePrepareStatementTrampoline, &FRAME_PLAN_PrepareStatement}, {"TypeList", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeTypeListTrampoline, &FRAME_PLAN_431}, + &PEGTransformerFactory::FinalizeTypeListTrampoline, &FRAME_PLAN_TypeList}, {"SelectStatement", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeSelectStatementTrampoline, &FRAME_PLAN_207}, + &PEGTransformerFactory::FinalizeSelectStatementTrampoline, &FRAME_PLAN_ExplainSelectStatement}, {"SelectStatementInternal", &PEGTransformerFactory::InitializeSelectStatementInternalTrampoline, &PEGTransformerFactory::FinalizeSelectStatementInternalTrampoline, nullptr}, {"SelectSetOpChain", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeSelectSetOpChainTrampoline, &FRAME_PLAN_432}, + &PEGTransformerFactory::FinalizeSelectSetOpChainTrampoline, &FRAME_PLAN_SelectSetOpChain}, {"SelectSetOpChainTail", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeSelectSetOpChainTailTrampoline, &FRAME_PLAN_433}, + &PEGTransformerFactory::FinalizeSelectSetOpChainTailTrampoline, &FRAME_PLAN_SelectSetOpChainTail}, {"IntersectChain", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeIntersectChainTrampoline, &FRAME_PLAN_434}, + &PEGTransformerFactory::FinalizeIntersectChainTrampoline, &FRAME_PLAN_IntersectChain}, {"IntersectChainTail", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeIntersectChainTailTrampoline, &FRAME_PLAN_435}, + &PEGTransformerFactory::FinalizeIntersectChainTailTrampoline, &FRAME_PLAN_IntersectChainTail}, {"SetIntersectClause", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeSetIntersectClauseTrampoline, &FRAME_PLAN_436}, + &PEGTransformerFactory::FinalizeSetIntersectClauseTrampoline, &FRAME_PLAN_SetIntersectClause}, {"SelectAtom", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, - &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, + &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_ChoiceThrow}, {"SelectParens", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeSelectParensTrampoline, &FRAME_PLAN_298}, + &PEGTransformerFactory::FinalizeSelectParensTrampoline, &FRAME_PLAN_CTESelectBody}, {"SetopClause", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeSetopClauseTrampoline, &FRAME_PLAN_437}, + &PEGTransformerFactory::FinalizeSetopClauseTrampoline, &FRAME_PLAN_SetopClause}, {"SetopType", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, - &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, + &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_ChoiceThrow}, {"SetopUnion", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeSetopUnionTrampoline, &FRAME_PLAN_12}, + &PEGTransformerFactory::FinalizeSetopUnionTrampoline, &FRAME_PLAN_Leaf}, {"SetopExcept", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeSetopExceptTrampoline, &FRAME_PLAN_12}, + &PEGTransformerFactory::FinalizeSetopExceptTrampoline, &FRAME_PLAN_Leaf}, {"SelectStatementType", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, - &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, + &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_ChoiceThrow}, {"ResultModifiers", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeResultModifiersTrampoline, &FRAME_PLAN_438}, + &PEGTransformerFactory::FinalizeResultModifiersTrampoline, &FRAME_PLAN_ResultModifiers}, {"LimitOffset", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, - &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, + &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_ChoiceThrow}, {"LimitOffsetClause", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeLimitOffsetClauseTrampoline, &FRAME_PLAN_439}, + &PEGTransformerFactory::FinalizeLimitOffsetClauseTrampoline, &FRAME_PLAN_LimitOffsetClause}, {"OffsetLimitClause", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeOffsetLimitClauseTrampoline, &FRAME_PLAN_440}, + &PEGTransformerFactory::FinalizeOffsetLimitClauseTrampoline, &FRAME_PLAN_OffsetLimitClause}, {"OffsetFetchClause", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeOffsetFetchClauseTrampoline, &FRAME_PLAN_441}, + &PEGTransformerFactory::FinalizeOffsetFetchClauseTrampoline, &FRAME_PLAN_OffsetFetchClause}, {"FetchOffsetClause", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeFetchOffsetClauseTrampoline, &FRAME_PLAN_442}, + &PEGTransformerFactory::FinalizeFetchOffsetClauseTrampoline, &FRAME_PLAN_FetchOffsetClause}, {"FetchOnlyClause", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeFetchOnlyClauseTrampoline, &FRAME_PLAN_443}, + &PEGTransformerFactory::FinalizeFetchOnlyClauseTrampoline, &FRAME_PLAN_FetchOnlyClause}, {"TableStatement", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeTableStatementTrampoline, &FRAME_PLAN_444}, + &PEGTransformerFactory::FinalizeTableStatementTrampoline, &FRAME_PLAN_TableStatement}, {"OptionalParensSimpleSelect", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, - &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, + &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_ChoiceThrow}, {"SimpleSelectParens", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeSimpleSelectParensTrampoline, &FRAME_PLAN_445}, + &PEGTransformerFactory::FinalizeSimpleSelectParensTrampoline, &FRAME_PLAN_SimpleSelectParens}, {"SimpleSelect", &PEGTransformerFactory::InitializeSimpleSelectTrampoline, &PEGTransformerFactory::FinalizeSimpleSelectTrampoline, nullptr}, {"SelectFrom", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, - &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, + &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_ChoiceThrow}, {"SelectFromClause", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeSelectFromClauseTrampoline, &FRAME_PLAN_446}, + &PEGTransformerFactory::FinalizeSelectFromClauseTrampoline, &FRAME_PLAN_SelectFromClause}, {"FromSelectClause", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeFromSelectClauseTrampoline, &FRAME_PLAN_447}, + &PEGTransformerFactory::FinalizeFromSelectClauseTrampoline, &FRAME_PLAN_FromSelectClause}, {"WithStatement", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeWithStatementTrampoline, &FRAME_PLAN_448}, + &PEGTransformerFactory::FinalizeWithStatementTrampoline, &FRAME_PLAN_WithStatement}, {"CTEBody", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, - &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, + &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_ChoiceThrow}, {"CTESelectBody", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeCTESelectBodyTrampoline, &FRAME_PLAN_298}, + &PEGTransformerFactory::FinalizeCTESelectBodyTrampoline, &FRAME_PLAN_CTESelectBody}, {"CTEDMLBody", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeCTEDMLBodyTrampoline, &FRAME_PLAN_449}, + &PEGTransformerFactory::FinalizeCTEDMLBodyTrampoline, &FRAME_PLAN_CTEDMLBody}, {"UsingKey", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeUsingKeyTrampoline, &FRAME_PLAN_450}, + &PEGTransformerFactory::FinalizeUsingKeyTrampoline, &FRAME_PLAN_UsingKey}, {"Materialized", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeMaterializedTrampoline, &FRAME_PLAN_12}, + &PEGTransformerFactory::FinalizeMaterializedTrampoline, &FRAME_PLAN_Leaf}, {"WithClause", &PEGTransformerFactory::InitializeWithClauseTrampoline, &PEGTransformerFactory::FinalizeWithClauseTrampoline, nullptr}, {"SelectClause", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeSelectClauseTrampoline, &FRAME_PLAN_451}, + &PEGTransformerFactory::FinalizeSelectClauseTrampoline, &FRAME_PLAN_SelectClause}, {"TargetList", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeTargetListTrampoline, &FRAME_PLAN_452}, + &PEGTransformerFactory::FinalizeTargetListTrampoline, &FRAME_PLAN_TargetList}, {"ColumnAliases", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeColumnAliasesTrampoline, &FRAME_PLAN_425}, + &PEGTransformerFactory::FinalizeColumnAliasesTrampoline, &FRAME_PLAN_ColumnAliases}, {"DistinctClause", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, - &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, + &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_ChoiceThrow}, {"DistinctAll", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeDistinctAllTrampoline, &FRAME_PLAN_12}, + &PEGTransformerFactory::FinalizeDistinctAllTrampoline, &FRAME_PLAN_Leaf}, {"DistinctOn", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeDistinctOnTrampoline, &FRAME_PLAN_453}, + &PEGTransformerFactory::FinalizeDistinctOnTrampoline, &FRAME_PLAN_DistinctOn}, {"DistinctOnTargets", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeDistinctOnTargetsTrampoline, &FRAME_PLAN_335}, + &PEGTransformerFactory::FinalizeDistinctOnTargetsTrampoline, &FRAME_PLAN_CoalesceExpression}, {"InnerTableRef", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, - &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, + &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_ChoiceThrow}, {"TableRef", &PEGTransformerFactory::InitializeTableRefTrampoline, &PEGTransformerFactory::FinalizeTableRefTrampoline, nullptr}, {"TableSubquery", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeTableSubqueryTrampoline, &FRAME_PLAN_454}, + &PEGTransformerFactory::FinalizeTableSubqueryTrampoline, &FRAME_PLAN_TableSubquery}, {"BaseTableRef", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeBaseTableRefTrampoline, &FRAME_PLAN_455}, + &PEGTransformerFactory::FinalizeBaseTableRefTrampoline, &FRAME_PLAN_BaseTableRef}, {"TableAliasColon", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeTableAliasColonTrampoline, &FRAME_PLAN_38}, + &PEGTransformerFactory::FinalizeTableAliasColonTrampoline, &FRAME_PLAN_ConstraintName}, {"ValuesRef", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeValuesRefTrampoline, &FRAME_PLAN_456}, + &PEGTransformerFactory::FinalizeValuesRefTrampoline, &FRAME_PLAN_ValuesRef}, {"ParensTableRef", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeParensTableRefTrampoline, &FRAME_PLAN_457}, + &PEGTransformerFactory::FinalizeParensTableRefTrampoline, &FRAME_PLAN_ParensTableRef}, {"JoinedTableRef", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, - &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, + &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_ChoiceThrow}, {"JoinedTableRefChain", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeJoinedTableRefChainTrampoline, &FRAME_PLAN_458}, + &PEGTransformerFactory::FinalizeJoinedTableRefChainTrampoline, &FRAME_PLAN_JoinedTableRefChain}, {"JoinOrPivot", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, - &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, + &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_ChoiceThrow}, {"TablePivotClause", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeTablePivotClauseTrampoline, &FRAME_PLAN_459}, + &PEGTransformerFactory::FinalizeTablePivotClauseTrampoline, &FRAME_PLAN_TablePivotClause}, {"TablePivotClauseBody", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeTablePivotClauseBodyTrampoline, &FRAME_PLAN_460}, + &PEGTransformerFactory::FinalizeTablePivotClauseBodyTrampoline, &FRAME_PLAN_TablePivotClauseBody}, {"PivotGroupByList", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizePivotGroupByListTrampoline, &FRAME_PLAN_461}, + &PEGTransformerFactory::FinalizePivotGroupByListTrampoline, &FRAME_PLAN_PivotGroupByList}, {"TableUnpivotClause", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeTableUnpivotClauseTrampoline, &FRAME_PLAN_462}, + &PEGTransformerFactory::FinalizeTableUnpivotClauseTrampoline, &FRAME_PLAN_TableUnpivotClause}, {"TableUnpivotClauseBody", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeTableUnpivotClauseBodyTrampoline, &FRAME_PLAN_463}, + &PEGTransformerFactory::FinalizeTableUnpivotClauseBodyTrampoline, &FRAME_PLAN_TableUnpivotClauseBody}, {"PivotHeader", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizePivotHeaderTrampoline, &FRAME_PLAN_464}, + &PEGTransformerFactory::FinalizePivotHeaderTrampoline, &FRAME_PLAN_PivotHeader}, {"PivotValueList", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizePivotValueListTrampoline, &FRAME_PLAN_465}, + &PEGTransformerFactory::FinalizePivotValueListTrampoline, &FRAME_PLAN_PivotValueList}, {"PivotValueTarget", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, - &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, + &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_ChoiceThrow}, {"PivotEnumTarget", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizePivotEnumTargetTrampoline, &FRAME_PLAN_12}, + &PEGTransformerFactory::FinalizePivotEnumTargetTrampoline, &FRAME_PLAN_Leaf}, {"PivotListTarget", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizePivotListTargetTrampoline, &FRAME_PLAN_466}, + &PEGTransformerFactory::FinalizePivotListTargetTrampoline, &FRAME_PLAN_PivotListTarget}, {"UnpivotValueList", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeUnpivotValueListTrampoline, &FRAME_PLAN_467}, + &PEGTransformerFactory::FinalizeUnpivotValueListTrampoline, &FRAME_PLAN_UnpivotValueList}, {"PivotTargetList", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizePivotTargetListTrampoline, &FRAME_PLAN_468}, + &PEGTransformerFactory::FinalizePivotTargetListTrampoline, &FRAME_PLAN_PivotTargetList}, {"UnpivotTargetList", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeUnpivotTargetListTrampoline, &FRAME_PLAN_468}, + &PEGTransformerFactory::FinalizeUnpivotTargetListTrampoline, &FRAME_PLAN_PivotTargetList}, {"Lateral", &PEGTransformerFactory::InitializePlannedTrampoline, &PEGTransformerFactory::FinalizeLateralTrampoline, - &FRAME_PLAN_12}, + &FRAME_PLAN_Leaf}, {"BaseTableName", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, - &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, + &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_ChoiceThrow}, {"UnqualifiedBaseTableName", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeUnqualifiedBaseTableNameTrampoline, &FRAME_PLAN_12}, + &PEGTransformerFactory::FinalizeUnqualifiedBaseTableNameTrampoline, &FRAME_PLAN_Leaf}, {"QualifiedTableName", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, - &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, + &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_ChoiceThrow}, {"SchemaReservedTable", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeSchemaReservedTableTrampoline, &FRAME_PLAN_56}, + &PEGTransformerFactory::FinalizeSchemaReservedTableTrampoline, &FRAME_PLAN_SchemaReservedFunctionName}, {"CatalogReservedSchemaTable", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeCatalogReservedSchemaTableTrampoline, &FRAME_PLAN_55}, + &PEGTransformerFactory::FinalizeCatalogReservedSchemaTableTrampoline, &FRAME_PLAN_CatalogReservedSchemaIndex}, {"TableFunction", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, - &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, + &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_ChoiceThrow}, {"TableFunctionLateralOpt", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeTableFunctionLateralOptTrampoline, &FRAME_PLAN_469}, + &PEGTransformerFactory::FinalizeTableFunctionLateralOptTrampoline, &FRAME_PLAN_TableFunctionLateralOpt}, {"TableFunctionAliasColon", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeTableFunctionAliasColonTrampoline, &FRAME_PLAN_470}, + &PEGTransformerFactory::FinalizeTableFunctionAliasColonTrampoline, &FRAME_PLAN_TableFunctionAliasColon}, {"WithOrdinality", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeWithOrdinalityTrampoline, &FRAME_PLAN_12}, + &PEGTransformerFactory::FinalizeWithOrdinalityTrampoline, &FRAME_PLAN_Leaf}, {"QualifiedTableFunction", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, - &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, + &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_ChoiceThrow}, {"CatalogReservedSchemaTableFunctionName", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeCatalogReservedSchemaTableFunctionNameTrampoline, &FRAME_PLAN_471}, + &PEGTransformerFactory::FinalizeCatalogReservedSchemaTableFunctionNameTrampoline, + &FRAME_PLAN_CatalogReservedSchemaTableFunctionName}, {"TableFunctionNameAsQualifiedName", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeTableFunctionNameAsQualifiedNameTrampoline, &FRAME_PLAN_12}, + &PEGTransformerFactory::FinalizeTableFunctionNameAsQualifiedNameTrampoline, &FRAME_PLAN_Leaf}, {"TableFunctionArguments", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeTableFunctionArgumentsTrampoline, &FRAME_PLAN_472}, + &PEGTransformerFactory::FinalizeTableFunctionArgumentsTrampoline, &FRAME_PLAN_TableFunctionArguments}, {"FunctionArgument", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, - &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, + &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_ChoiceThrow}, {"NamedFunctionArgument", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeNamedFunctionArgumentTrampoline, &FRAME_PLAN_473}, + &PEGTransformerFactory::FinalizeNamedFunctionArgumentTrampoline, &FRAME_PLAN_NamedFunctionArgument}, {"PositionalFunctionArgument", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizePositionalFunctionArgumentTrampoline, &FRAME_PLAN_31}, + &PEGTransformerFactory::FinalizePositionalFunctionArgumentTrampoline, &FRAME_PLAN_DatabasePath}, {"NamedParameter", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeNamedParameterTrampoline, &FRAME_PLAN_474}, + &PEGTransformerFactory::FinalizeNamedParameterTrampoline, &FRAME_PLAN_NamedParameter}, {"TableAlias", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, - &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, + &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_ChoiceThrow}, {"TableAliasAs", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeTableAliasAsTrampoline, &FRAME_PLAN_475}, + &PEGTransformerFactory::FinalizeTableAliasAsTrampoline, &FRAME_PLAN_TableAliasAs}, {"TableAliasWithoutAs", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeTableAliasWithoutAsTrampoline, &FRAME_PLAN_476}, + &PEGTransformerFactory::FinalizeTableAliasWithoutAsTrampoline, &FRAME_PLAN_TableAliasWithoutAs}, {"AtClause", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeAtClauseTrampoline, &FRAME_PLAN_477}, + &PEGTransformerFactory::FinalizeAtClauseTrampoline, &FRAME_PLAN_AtClause}, {"AtSpecifier", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeAtSpecifierTrampoline, &FRAME_PLAN_478}, + &PEGTransformerFactory::FinalizeAtSpecifierTrampoline, &FRAME_PLAN_AtSpecifier}, {"AtUnit", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, - &PEGTransformerFactory::FinalizeAtUnitTrampoline, &FRAME_PLAN_19}, + &PEGTransformerFactory::FinalizeAtUnitTrampoline, &FRAME_PLAN_ChoiceEarlyIdentifierKeywordStringOperatorThrow}, {"VersionAtUnit", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeVersionAtUnitTrampoline, &FRAME_PLAN_12}, + &PEGTransformerFactory::FinalizeVersionAtUnitTrampoline, &FRAME_PLAN_Leaf}, {"TimestampAtUnit", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeTimestampAtUnitTrampoline, &FRAME_PLAN_12}, + &PEGTransformerFactory::FinalizeTimestampAtUnitTrampoline, &FRAME_PLAN_Leaf}, {"JoinClause", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, - &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, + &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_ChoiceThrow}, {"NearestJoinClause", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, - &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, + &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_ChoiceThrow}, {"NearestJoinAliased", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeNearestJoinAliasedTrampoline, &FRAME_PLAN_479}, + &PEGTransformerFactory::FinalizeNearestJoinAliasedTrampoline, &FRAME_PLAN_NearestJoinAliased}, {"NearestJoinBare", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeNearestJoinBareTrampoline, &FRAME_PLAN_480}, + &PEGTransformerFactory::FinalizeNearestJoinBareTrampoline, &FRAME_PLAN_NearestJoinBare}, {"NearestBareTableRef", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, - &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, + &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_ChoiceThrow}, {"NearestValuesRef", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeNearestValuesRefTrampoline, &FRAME_PLAN_481}, + &PEGTransformerFactory::FinalizeNearestValuesRefTrampoline, &FRAME_PLAN_NearestValuesRef}, {"NearestTableFunction", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeNearestTableFunctionTrampoline, &FRAME_PLAN_482}, + &PEGTransformerFactory::FinalizeNearestTableFunctionTrampoline, &FRAME_PLAN_NearestTableFunction}, {"NearestTableSubquery", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeNearestTableSubqueryTrampoline, &FRAME_PLAN_483}, + &PEGTransformerFactory::FinalizeNearestTableSubqueryTrampoline, &FRAME_PLAN_NearestTableSubquery}, {"NearestBaseTableRef", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeNearestBaseTableRefTrampoline, &FRAME_PLAN_484}, + &PEGTransformerFactory::FinalizeNearestBaseTableRefTrampoline, &FRAME_PLAN_NearestBaseTableRef}, {"NearestParensTableRef", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeNearestParensTableRefTrampoline, &FRAME_PLAN_485}, + &PEGTransformerFactory::FinalizeNearestParensTableRefTrampoline, &FRAME_PLAN_NearestParensTableRef}, {"ApproxOrExact", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, - &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, + &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_ChoiceThrow}, {"NearestApprox", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeNearestApproxTrampoline, &FRAME_PLAN_12}, + &PEGTransformerFactory::FinalizeNearestApproxTrampoline, &FRAME_PLAN_Leaf}, {"NearestExact", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeNearestExactTrampoline, &FRAME_PLAN_12}, + &PEGTransformerFactory::FinalizeNearestExactTrampoline, &FRAME_PLAN_Leaf}, {"DistanceOrSimilarity", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, - &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, + &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_ChoiceThrow}, {"NearestDistance", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeNearestDistanceTrampoline, &FRAME_PLAN_12}, + &PEGTransformerFactory::FinalizeNearestDistanceTrampoline, &FRAME_PLAN_Leaf}, {"NearestSimilarity", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeNearestSimilarityTrampoline, &FRAME_PLAN_12}, + &PEGTransformerFactory::FinalizeNearestSimilarityTrampoline, &FRAME_PLAN_Leaf}, {"RegularJoinClause", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeRegularJoinClauseTrampoline, &FRAME_PLAN_486}, + &PEGTransformerFactory::FinalizeRegularJoinClauseTrampoline, &FRAME_PLAN_RegularJoinClause}, {"JoinByClause", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeJoinByClauseTrampoline, &FRAME_PLAN_487}, + &PEGTransformerFactory::FinalizeJoinByClauseTrampoline, &FRAME_PLAN_JoinByClause}, {"Asof", &PEGTransformerFactory::InitializePlannedTrampoline, &PEGTransformerFactory::FinalizeAsofTrampoline, - &FRAME_PLAN_12}, + &FRAME_PLAN_Leaf}, {"JoinWithoutOnClause", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeJoinWithoutOnClauseTrampoline, &FRAME_PLAN_488}, + &PEGTransformerFactory::FinalizeJoinWithoutOnClauseTrampoline, &FRAME_PLAN_JoinWithoutOnClause}, {"JoinQualifier", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, - &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, + &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_ChoiceThrow}, {"OnClause", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeOnClauseTrampoline, &FRAME_PLAN_21}, + &PEGTransformerFactory::FinalizeOnClauseTrampoline, &FRAME_PLAN_AndExpression}, {"UsingClause", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeUsingClauseTrampoline, &FRAME_PLAN_489}, + &PEGTransformerFactory::FinalizeUsingClauseTrampoline, &FRAME_PLAN_UsingClause}, {"UsingColumnName", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, - &PEGTransformerFactory::FinalizeUsingColumnNameTrampoline, &FRAME_PLAN_149}, + &PEGTransformerFactory::FinalizeUsingColumnNameTrampoline, + &FRAME_PLAN_ChoiceEarlyIdentifierKeywordStringEmptyNameThrow}, {"JoinType", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, - &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, + &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_ChoiceThrow}, {"JoinPrefix", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, - &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, + &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_ChoiceThrow}, {"CrossJoinPrefix", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeCrossJoinPrefixTrampoline, &FRAME_PLAN_12}, + &PEGTransformerFactory::FinalizeCrossJoinPrefixTrampoline, &FRAME_PLAN_Leaf}, {"NaturalJoinPrefix", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeNaturalJoinPrefixTrampoline, &FRAME_PLAN_490}, + &PEGTransformerFactory::FinalizeNaturalJoinPrefixTrampoline, &FRAME_PLAN_NaturalJoinPrefix}, {"PositionalJoinPrefix", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizePositionalJoinPrefixTrampoline, &FRAME_PLAN_12}, + &PEGTransformerFactory::FinalizePositionalJoinPrefixTrampoline, &FRAME_PLAN_Leaf}, {"FullJoin", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeFullJoinTrampoline, &FRAME_PLAN_12}, + &PEGTransformerFactory::FinalizeFullJoinTrampoline, &FRAME_PLAN_Leaf}, {"LeftJoin", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeLeftJoinTrampoline, &FRAME_PLAN_12}, + &PEGTransformerFactory::FinalizeLeftJoinTrampoline, &FRAME_PLAN_Leaf}, {"RightJoin", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeRightJoinTrampoline, &FRAME_PLAN_12}, + &PEGTransformerFactory::FinalizeRightJoinTrampoline, &FRAME_PLAN_Leaf}, {"SemiJoin", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeSemiJoinTrampoline, &FRAME_PLAN_12}, + &PEGTransformerFactory::FinalizeSemiJoinTrampoline, &FRAME_PLAN_Leaf}, {"AntiJoin", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeAntiJoinTrampoline, &FRAME_PLAN_12}, + &PEGTransformerFactory::FinalizeAntiJoinTrampoline, &FRAME_PLAN_Leaf}, {"InnerJoin", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeInnerJoinTrampoline, &FRAME_PLAN_12}, + &PEGTransformerFactory::FinalizeInnerJoinTrampoline, &FRAME_PLAN_Leaf}, {"FromClause", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeFromClauseTrampoline, &FRAME_PLAN_172}, + &PEGTransformerFactory::FinalizeFromClauseTrampoline, &FRAME_PLAN_DeleteUsingClause}, {"WhereClause", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeWhereClauseTrampoline, &FRAME_PLAN_21}, + &PEGTransformerFactory::FinalizeWhereClauseTrampoline, &FRAME_PLAN_AndExpression}, {"GroupByClause", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeGroupByClauseTrampoline, &FRAME_PLAN_491}, + &PEGTransformerFactory::FinalizeGroupByClauseTrampoline, &FRAME_PLAN_GroupByClause}, {"HavingClause", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeHavingClauseTrampoline, &FRAME_PLAN_21}, + &PEGTransformerFactory::FinalizeHavingClauseTrampoline, &FRAME_PLAN_AndExpression}, {"QualifyClause", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeQualifyClauseTrampoline, &FRAME_PLAN_21}, + &PEGTransformerFactory::FinalizeQualifyClauseTrampoline, &FRAME_PLAN_AndExpression}, {"SampleClause", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeSampleClauseTrampoline, &FRAME_PLAN_492}, + &PEGTransformerFactory::FinalizeSampleClauseTrampoline, &FRAME_PLAN_SampleClause}, {"SelectSampleClause", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeSelectSampleClauseTrampoline, &FRAME_PLAN_492}, + &PEGTransformerFactory::FinalizeSelectSampleClauseTrampoline, &FRAME_PLAN_SampleClause}, {"WindowClause", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeWindowClauseTrampoline, &FRAME_PLAN_493}, + &PEGTransformerFactory::FinalizeWindowClauseTrampoline, &FRAME_PLAN_WindowClause}, {"WindowDefinition", &PEGTransformerFactory::InitializeWindowDefinitionTrampoline, &PEGTransformerFactory::FinalizeWindowDefinitionTrampoline, nullptr}, {"SampleEntry", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, - &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, + &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_ChoiceThrow}, {"SampleEntryCount", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeSampleEntryCountTrampoline, &FRAME_PLAN_494}, + &PEGTransformerFactory::FinalizeSampleEntryCountTrampoline, &FRAME_PLAN_SampleEntryCount}, {"SampleEntryFunction", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeSampleEntryFunctionTrampoline, &FRAME_PLAN_495}, + &PEGTransformerFactory::FinalizeSampleEntryFunctionTrampoline, &FRAME_PLAN_SampleEntryFunction}, {"SampleFunction", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeSampleFunctionTrampoline, &FRAME_PLAN_83}, + &PEGTransformerFactory::FinalizeSampleFunctionTrampoline, &FRAME_PLAN_ColIdDot}, {"SampleProperties", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeSamplePropertiesTrampoline, &FRAME_PLAN_496}, + &PEGTransformerFactory::FinalizeSamplePropertiesTrampoline, &FRAME_PLAN_SampleProperties}, {"RepeatableSample", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeRepeatableSampleTrampoline, &FRAME_PLAN_497}, + &PEGTransformerFactory::FinalizeRepeatableSampleTrampoline, &FRAME_PLAN_RepeatableSample}, {"SampleSeed", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeSampleSeedTrampoline, &FRAME_PLAN_12}, + &PEGTransformerFactory::FinalizeSampleSeedTrampoline, &FRAME_PLAN_Leaf}, {"SampleCount", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeSampleCountTrampoline, &FRAME_PLAN_498}, + &PEGTransformerFactory::FinalizeSampleCountTrampoline, &FRAME_PLAN_SampleCount}, {"SampleValue", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, - &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, + &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_ChoiceThrow}, {"SampleUnit", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, - &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, + &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_ChoiceThrow}, {"SamplePercentage", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeSamplePercentageTrampoline, &FRAME_PLAN_12}, + &PEGTransformerFactory::FinalizeSamplePercentageTrampoline, &FRAME_PLAN_Leaf}, {"SampleRows", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeSampleRowsTrampoline, &FRAME_PLAN_12}, + &PEGTransformerFactory::FinalizeSampleRowsTrampoline, &FRAME_PLAN_Leaf}, {"GroupByExpressions", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, - &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, + &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_ChoiceThrow}, {"GroupByAll", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeGroupByAllTrampoline, &FRAME_PLAN_12}, + &PEGTransformerFactory::FinalizeGroupByAllTrampoline, &FRAME_PLAN_Leaf}, {"GroupByList", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeGroupByListTrampoline, &FRAME_PLAN_499}, + &PEGTransformerFactory::FinalizeGroupByListTrampoline, &FRAME_PLAN_GroupByList}, {"GroupByExpression", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, - &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, + &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_ChoiceThrow}, {"GroupByBaseExpression", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeGroupByBaseExpressionTrampoline, &FRAME_PLAN_31}, + &PEGTransformerFactory::FinalizeGroupByBaseExpressionTrampoline, &FRAME_PLAN_DatabasePath}, {"EmptyGroupingItem", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeEmptyGroupingItemTrampoline, &FRAME_PLAN_12}, + &PEGTransformerFactory::FinalizeEmptyGroupingItemTrampoline, &FRAME_PLAN_Leaf}, {"CubeOrRollupClause", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeCubeOrRollupClauseTrampoline, &FRAME_PLAN_500}, + &PEGTransformerFactory::FinalizeCubeOrRollupClauseTrampoline, &FRAME_PLAN_CubeOrRollupClause}, {"CubeOrRollup", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, - &PEGTransformerFactory::FinalizeCubeOrRollupTrampoline, &FRAME_PLAN_19}, + &PEGTransformerFactory::FinalizeCubeOrRollupTrampoline, + &FRAME_PLAN_ChoiceEarlyIdentifierKeywordStringOperatorThrow}, {"CubeKeyword", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeCubeKeywordTrampoline, &FRAME_PLAN_12}, + &PEGTransformerFactory::FinalizeCubeKeywordTrampoline, &FRAME_PLAN_Leaf}, {"RollupKeyword", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeRollupKeywordTrampoline, &FRAME_PLAN_12}, + &PEGTransformerFactory::FinalizeRollupKeywordTrampoline, &FRAME_PLAN_Leaf}, {"GroupingSetsClause", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeGroupingSetsClauseTrampoline, &FRAME_PLAN_501}, + &PEGTransformerFactory::FinalizeGroupingSetsClauseTrampoline, &FRAME_PLAN_GroupingSetsClause}, {"SubqueryReference", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeSubqueryReferenceTrampoline, &FRAME_PLAN_298}, + &PEGTransformerFactory::FinalizeSubqueryReferenceTrampoline, &FRAME_PLAN_CTESelectBody}, {"OrderByExpression", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeOrderByExpressionTrampoline, &FRAME_PLAN_98}, + &PEGTransformerFactory::FinalizeOrderByExpressionTrampoline, &FRAME_PLAN_IndexElement}, {"DescOrAsc", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, - &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, + &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_ChoiceThrow}, {"DescendingOrder", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeDescendingOrderTrampoline, &FRAME_PLAN_12}, + &PEGTransformerFactory::FinalizeDescendingOrderTrampoline, &FRAME_PLAN_Leaf}, {"AscendingOrder", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeAscendingOrderTrampoline, &FRAME_PLAN_12}, + &PEGTransformerFactory::FinalizeAscendingOrderTrampoline, &FRAME_PLAN_Leaf}, {"NullsFirstOrLast", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, - &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, + &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_ChoiceThrow}, {"NullsFirst", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeNullsFirstTrampoline, &FRAME_PLAN_12}, + &PEGTransformerFactory::FinalizeNullsFirstTrampoline, &FRAME_PLAN_Leaf}, {"NullsLast", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeNullsLastTrampoline, &FRAME_PLAN_12}, + &PEGTransformerFactory::FinalizeNullsLastTrampoline, &FRAME_PLAN_Leaf}, {"OrderByClause", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeOrderByClauseTrampoline, &FRAME_PLAN_502}, + &PEGTransformerFactory::FinalizeOrderByClauseTrampoline, &FRAME_PLAN_OrderByClause}, {"OrderByExpressions", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, - &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, + &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_ChoiceThrow}, {"OrderByExpressionList", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeOrderByExpressionListTrampoline, &FRAME_PLAN_503}, + &PEGTransformerFactory::FinalizeOrderByExpressionListTrampoline, &FRAME_PLAN_OrderByExpressionList}, {"OrderByAll", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeOrderByAllTrampoline, &FRAME_PLAN_504}, + &PEGTransformerFactory::FinalizeOrderByAllTrampoline, &FRAME_PLAN_OrderByAll}, {"LimitClause", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeLimitClauseTrampoline, &FRAME_PLAN_505}, + &PEGTransformerFactory::FinalizeLimitClauseTrampoline, &FRAME_PLAN_LimitClause}, {"OffsetClause", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeOffsetClauseTrampoline, &FRAME_PLAN_506}, + &PEGTransformerFactory::FinalizeOffsetClauseTrampoline, &FRAME_PLAN_OffsetClause}, {"OffsetValue", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeOffsetValueTrampoline, &FRAME_PLAN_31}, + &PEGTransformerFactory::FinalizeOffsetValueTrampoline, &FRAME_PLAN_DatabasePath}, {"LimitValue", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, - &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, + &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_ChoiceThrow}, {"LimitAll", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeLimitAllTrampoline, &FRAME_PLAN_12}, + &PEGTransformerFactory::FinalizeLimitAllTrampoline, &FRAME_PLAN_Leaf}, {"LimitLiteralPercent", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeLimitLiteralPercentTrampoline, &FRAME_PLAN_12}, + &PEGTransformerFactory::FinalizeLimitLiteralPercentTrampoline, &FRAME_PLAN_Leaf}, {"LimitExpression", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeLimitExpressionTrampoline, &FRAME_PLAN_31}, + &PEGTransformerFactory::FinalizeLimitExpressionTrampoline, &FRAME_PLAN_DatabasePath}, {"FetchClause", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, - &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, + &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_ChoiceThrow}, {"FetchClauseWithoutValue", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeFetchClauseWithoutValueTrampoline, &FRAME_PLAN_12}, + &PEGTransformerFactory::FinalizeFetchClauseWithoutValueTrampoline, &FRAME_PLAN_Leaf}, {"FetchClauseWithValue", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_507}, + &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_FetchClauseWithValue}, {"FetchValue", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeFetchValueTrampoline, &FRAME_PLAN_31}, + &PEGTransformerFactory::FinalizeFetchValueTrampoline, &FRAME_PLAN_DatabasePath}, {"AliasedExpression", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, - &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, + &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_ChoiceThrow}, {"ColIdExpression", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeColIdExpressionTrampoline, &FRAME_PLAN_508}, + &PEGTransformerFactory::FinalizeColIdExpressionTrampoline, &FRAME_PLAN_ColIdExpression}, {"ExpressionAsCollabel", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeExpressionAsCollabelTrampoline, &FRAME_PLAN_390}, + &PEGTransformerFactory::FinalizeExpressionAsCollabelTrampoline, &FRAME_PLAN_ExpressionAsCollabel}, {"ExpressionOptIdentifier", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeExpressionOptIdentifierTrampoline, &FRAME_PLAN_31}, + &PEGTransformerFactory::FinalizeExpressionOptIdentifierTrampoline, &FRAME_PLAN_DatabasePath}, {"ValuesClause", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeValuesClauseTrampoline, &FRAME_PLAN_509}, + &PEGTransformerFactory::FinalizeValuesClauseTrampoline, &FRAME_PLAN_ValuesClause}, {"ValuesExpressions", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeValuesExpressionsTrampoline, &FRAME_PLAN_297}, + &PEGTransformerFactory::FinalizeValuesExpressionsTrampoline, &FRAME_PLAN_InExpressionList}, {"SetStatement", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, - &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, + &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_ChoiceThrow}, {"SetKeywordStatement", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeSetKeywordStatementTrampoline, &FRAME_PLAN_510}, + &PEGTransformerFactory::FinalizeSetKeywordStatementTrampoline, &FRAME_PLAN_SetKeywordStatement}, {"VariableAssignment", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeVariableAssignmentTrampoline, &FRAME_PLAN_511}, + &PEGTransformerFactory::FinalizeVariableAssignmentTrampoline, &FRAME_PLAN_VariableAssignment}, {"SetAssignmentOrTimeZone", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, - &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, + &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_ChoiceThrow}, {"ResetStatement", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeResetStatementTrampoline, &FRAME_PLAN_512}, + &PEGTransformerFactory::FinalizeResetStatementTrampoline, &FRAME_PLAN_ResetStatement}, {"ResetTarget", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, - &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, + &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_ChoiceThrow}, {"ResetTimeZone", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeResetTimeZoneTrampoline, &FRAME_PLAN_513}, + &PEGTransformerFactory::FinalizeResetTimeZoneTrampoline, &FRAME_PLAN_ResetTimeZone}, {"ResetVariableOrSetting", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeResetVariableOrSettingTrampoline, &FRAME_PLAN_514}, + &PEGTransformerFactory::FinalizeResetVariableOrSettingTrampoline, &FRAME_PLAN_ResetVariableOrSetting}, {"SetSchema", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeSetSchemaTrampoline, &FRAME_PLAN_513}, + &PEGTransformerFactory::FinalizeSetSchemaTrampoline, &FRAME_PLAN_ResetTimeZone}, {"StandardAssignment", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeStandardAssignmentTrampoline, &FRAME_PLAN_515}, + &PEGTransformerFactory::FinalizeStandardAssignmentTrampoline, &FRAME_PLAN_StandardAssignment}, {"SetVariableOrSetting", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, - &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, + &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_ChoiceThrow}, {"SetTimeZone", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeSetTimeZoneTrampoline, &FRAME_PLAN_516}, + &PEGTransformerFactory::FinalizeSetTimeZoneTrampoline, &FRAME_PLAN_SetTimeZone}, {"ZoneValue", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, - &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, + &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_ChoiceThrow}, {"ZoneLocal", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeZoneLocalTrampoline, &FRAME_PLAN_12}, + &PEGTransformerFactory::FinalizeZoneLocalTrampoline, &FRAME_PLAN_Leaf}, {"ZoneDefault", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeZoneDefaultTrampoline, &FRAME_PLAN_12}, + &PEGTransformerFactory::FinalizeZoneDefaultTrampoline, &FRAME_PLAN_Leaf}, {"ZoneStringLiteral", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeZoneStringLiteralTrampoline, &FRAME_PLAN_12}, + &PEGTransformerFactory::FinalizeZoneStringLiteralTrampoline, &FRAME_PLAN_Leaf}, {"ZoneIdentifier", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeZoneIdentifierTrampoline, &FRAME_PLAN_12}, + &PEGTransformerFactory::FinalizeZoneIdentifierTrampoline, &FRAME_PLAN_Leaf}, {"ZoneIntervalWithInterval", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeZoneIntervalWithIntervalTrampoline, &FRAME_PLAN_517}, + &PEGTransformerFactory::FinalizeZoneIntervalWithIntervalTrampoline, &FRAME_PLAN_ZoneIntervalWithInterval}, {"ZoneIntervalWithPrecision", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeZoneIntervalWithPrecisionTrampoline, &FRAME_PLAN_12}, + &PEGTransformerFactory::FinalizeZoneIntervalWithPrecisionTrampoline, &FRAME_PLAN_Leaf}, {"SetSetting", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeSetSettingTrampoline, &FRAME_PLAN_513}, + &PEGTransformerFactory::FinalizeSetSettingTrampoline, &FRAME_PLAN_ResetTimeZone}, {"SetVariable", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeSetVariableTrampoline, &FRAME_PLAN_518}, + &PEGTransformerFactory::FinalizeSetVariableTrampoline, &FRAME_PLAN_SetVariable}, {"VariableScope", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeVariableScopeTrampoline, &FRAME_PLAN_12}, + &PEGTransformerFactory::FinalizeVariableScopeTrampoline, &FRAME_PLAN_Leaf}, {"SettingScope", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, - &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, + &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_ChoiceThrow}, {"LocalScope", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeLocalScopeTrampoline, &FRAME_PLAN_12}, + &PEGTransformerFactory::FinalizeLocalScopeTrampoline, &FRAME_PLAN_Leaf}, {"SessionScope", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeSessionScopeTrampoline, &FRAME_PLAN_12}, + &PEGTransformerFactory::FinalizeSessionScopeTrampoline, &FRAME_PLAN_Leaf}, {"GlobalScope", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeGlobalScopeTrampoline, &FRAME_PLAN_12}, + &PEGTransformerFactory::FinalizeGlobalScopeTrampoline, &FRAME_PLAN_Leaf}, {"SetAssignment", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeSetAssignmentTrampoline, &FRAME_PLAN_519}, + &PEGTransformerFactory::FinalizeSetAssignmentTrampoline, &FRAME_PLAN_SetAssignment}, {"VariableList", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeVariableListTrampoline, &FRAME_PLAN_345}, + &PEGTransformerFactory::FinalizeVariableListTrampoline, &FRAME_PLAN_OverlayExpressionList}, {"TransactionStatement", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, - &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, + &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_ChoiceThrow}, {"BeginTransaction", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeBeginTransactionTrampoline, &FRAME_PLAN_520}, + &PEGTransformerFactory::FinalizeBeginTransactionTrampoline, &FRAME_PLAN_BeginTransaction}, {"RollbackTransaction", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeRollbackTransactionTrampoline, &FRAME_PLAN_12}, + &PEGTransformerFactory::FinalizeRollbackTransactionTrampoline, &FRAME_PLAN_Leaf}, {"CommitTransaction", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeCommitTransactionTrampoline, &FRAME_PLAN_12}, + &PEGTransformerFactory::FinalizeCommitTransactionTrampoline, &FRAME_PLAN_Leaf}, {"ReadOrWrite", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeReadOrWriteTrampoline, &FRAME_PLAN_521}, + &PEGTransformerFactory::FinalizeReadOrWriteTrampoline, &FRAME_PLAN_ReadOrWrite}, {"ReadOnlyOrReadWrite", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, - &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, + &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_ChoiceThrow}, {"ReadOnly", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeReadOnlyTrampoline, &FRAME_PLAN_12}, + &PEGTransformerFactory::FinalizeReadOnlyTrampoline, &FRAME_PLAN_Leaf}, {"ReadWrite", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeReadWriteTrampoline, &FRAME_PLAN_12}, + &PEGTransformerFactory::FinalizeReadWriteTrampoline, &FRAME_PLAN_Leaf}, {"UpdateStatement", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeUpdateStatementTrampoline, &FRAME_PLAN_522}, + &PEGTransformerFactory::FinalizeUpdateStatementTrampoline, &FRAME_PLAN_UpdateStatement}, {"UpdateTarget", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, - &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, + &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_ChoiceThrow}, {"BaseTableSet", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeBaseTableSetTrampoline, &FRAME_PLAN_184}, + &PEGTransformerFactory::FinalizeBaseTableSetTrampoline, &FRAME_PLAN_BaseTableSet}, {"BaseTableAliasSet", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeBaseTableAliasSetTrampoline, &FRAME_PLAN_523}, + &PEGTransformerFactory::FinalizeBaseTableAliasSetTrampoline, &FRAME_PLAN_BaseTableAliasSet}, {"UpdateAlias", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeUpdateAliasTrampoline, &FRAME_PLAN_32}, + &PEGTransformerFactory::FinalizeUpdateAliasTrampoline, &FRAME_PLAN_AttachAlias}, {"UpdateSetClauseList", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeUpdateSetClauseListTrampoline, &FRAME_PLAN_524}, + &PEGTransformerFactory::FinalizeUpdateSetClauseListTrampoline, &FRAME_PLAN_UpdateSetClauseList}, {"UpdateSetClause", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, - &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, + &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_ChoiceThrow}, {"UpdateSetTuple", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeUpdateSetTupleTrampoline, &FRAME_PLAN_17}, + &PEGTransformerFactory::FinalizeUpdateSetTupleTrampoline, &FRAME_PLAN_AddDefault}, {"UpdateSetElement", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeUpdateSetElementTrampoline, &FRAME_PLAN_525}, + &PEGTransformerFactory::FinalizeUpdateSetElementTrampoline, &FRAME_PLAN_UpdateSetElement}, {"UpdateSetColumnTarget", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeUpdateSetColumnTargetTrampoline, &FRAME_PLAN_526}, + &PEGTransformerFactory::FinalizeUpdateSetColumnTargetTrampoline, &FRAME_PLAN_UpdateSetColumnTarget}, {"UseStatement", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeUseStatementTrampoline, &FRAME_PLAN_527}, + &PEGTransformerFactory::FinalizeUseStatementTrampoline, &FRAME_PLAN_UseStatement}, {"UseTarget", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, - &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, + &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_ChoiceThrow}, {"SchemaNameAsUseTarget", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, - &PEGTransformerFactory::FinalizeSchemaNameAsUseTargetTrampoline, &FRAME_PLAN_54}, + &PEGTransformerFactory::FinalizeSchemaNameAsUseTargetTrampoline, + &FRAME_PLAN_ChoiceFallbackIdentifierKeywordStringOperatorChoiceListThrow}, {"CatalogNameAsUseTarget", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, - &PEGTransformerFactory::FinalizeCatalogNameAsUseTargetTrampoline, &FRAME_PLAN_54}, + &PEGTransformerFactory::FinalizeCatalogNameAsUseTargetTrampoline, + &FRAME_PLAN_ChoiceFallbackIdentifierKeywordStringOperatorChoiceListThrow}, {"UseTargetCatalogSchema", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeUseTargetCatalogSchemaTrampoline, &FRAME_PLAN_528}, + &PEGTransformerFactory::FinalizeUseTargetCatalogSchemaTrampoline, &FRAME_PLAN_UseTargetCatalogSchema}, {"DotIdentifier", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeDotIdentifierTrampoline, &FRAME_PLAN_12}, + &PEGTransformerFactory::FinalizeDotIdentifierTrampoline, &FRAME_PLAN_Leaf}, {"VacuumStatement", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeVacuumStatementTrampoline, &FRAME_PLAN_529}, + &PEGTransformerFactory::FinalizeVacuumStatementTrampoline, &FRAME_PLAN_VacuumStatement}, {"VacuumOptions", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, - &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_1}, + &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_ChoiceThrow}, {"VacuumParensOptions", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeVacuumParensOptionsTrampoline, &FRAME_PLAN_530}, + &PEGTransformerFactory::FinalizeVacuumParensOptionsTrampoline, &FRAME_PLAN_VacuumParensOptions}, {"VacuumLegacyOptions", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeVacuumLegacyOptionsTrampoline, &FRAME_PLAN_531}, + &PEGTransformerFactory::FinalizeVacuumLegacyOptionsTrampoline, &FRAME_PLAN_VacuumLegacyOptions}, {"VacuumOption", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, - &PEGTransformerFactory::FinalizeVacuumOptionTrampoline, &FRAME_PLAN_19}, + &PEGTransformerFactory::FinalizeVacuumOptionTrampoline, + &FRAME_PLAN_ChoiceEarlyIdentifierKeywordStringOperatorThrow}, {"OptAnalyze", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeOptAnalyzeTrampoline, &FRAME_PLAN_532}, + &PEGTransformerFactory::FinalizeOptAnalyzeTrampoline, &FRAME_PLAN_OptAnalyze}, {"OptFull", &PEGTransformerFactory::InitializePlannedTrampoline, &PEGTransformerFactory::FinalizeOptFullTrampoline, - &FRAME_PLAN_12}, + &FRAME_PLAN_Leaf}, {"OptFreeze", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeOptFreezeTrampoline, &FRAME_PLAN_12}, + &PEGTransformerFactory::FinalizeOptFreezeTrampoline, &FRAME_PLAN_Leaf}, {"OptVerbose", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeOptVerboseTrampoline, &FRAME_PLAN_12}, + &PEGTransformerFactory::FinalizeOptVerboseTrampoline, &FRAME_PLAN_Leaf}, {"NameList", &PEGTransformerFactory::InitializePlannedTrampoline, - &PEGTransformerFactory::FinalizeNameListTrampoline, &FRAME_PLAN_425}, + &PEGTransformerFactory::FinalizeNameListTrampoline, &FRAME_PLAN_ColumnAliases}, }; static case_insensitive_map_t BuildGeneratedTransformFrameOps() { diff --git a/src/duckdb/src/planner/binder/expression/bind_star_expression.cpp b/src/duckdb/src/planner/binder/expression/bind_star_expression.cpp index 78b6f1e9a..131dbce2a 100644 --- a/src/duckdb/src/planner/binder/expression/bind_star_expression.cpp +++ b/src/duckdb/src/planner/binder/expression/bind_star_expression.cpp @@ -13,6 +13,7 @@ #include "duckdb/parser/expression/case_expression.hpp" #include "duckdb/parser/expression/conjunction_expression.hpp" #include "duckdb/parser/expression/window_expression.hpp" +#include "duckdb/common/optional.hpp" namespace duckdb { @@ -39,6 +40,25 @@ static vector &GetFunctionArgumentsMutable(ParsedExpression &e return expr.Cast().GetArgumentsMutable(); } +static void FindColumnsRelation(const ParsedExpression &expr, optional &relation_name) { + if (expr.GetExpressionClass() == ExpressionClass::STAR) { + auto &star = expr.Cast(); + if (star.IsColumns()) { + throw BinderException("COLUMNS expression is not allowed inside another COLUMNS expression"); + } + if (relation_name && *relation_name != star.RelationName()) { + if (relation_name->empty() || star.RelationName().empty()) { + throw BinderException(expr, "COLUMNS cannot mix qualified and unqualified stars"); + } + throw BinderException(expr, "COLUMNS cannot combine stars from different relations"); + } + relation_name = star.RelationName(); + return; + } + ParsedExpressionIterator::EnumerateChildren( + expr, [&](const ParsedExpression &child) { FindColumnsRelation(child, relation_name); }); +} + StarExpressionType Binder::FindStarExpression(unique_ptr &expr, StarExpression **star, bool is_root, bool in_columns) { StarExpressionType has_star = StarExpressionType::NONE; @@ -96,6 +116,18 @@ StarExpressionType Binder::FindStarExpression(unique_ptr &expr } in_columns = true; + if (current_star.Expression()) { + // Preserve the selection scope before inner stars become lists of unqualified names. + optional relation_name; + if (!current_star.RelationName().empty()) { + relation_name = current_star.RelationName(); + } + FindColumnsRelation(*current_star.Expression(), relation_name); + if (relation_name) { + current_star.RelationNameMutable() = *relation_name; + } + } + if (*star) { // we can have multiple if (!(*star)->Equals(current_star)) { diff --git a/src/duckdb/src/planner/binder/query_node/bind_select_node.cpp b/src/duckdb/src/planner/binder/query_node/bind_select_node.cpp index 7c4432514..fa4588972 100644 --- a/src/duckdb/src/planner/binder/query_node/bind_select_node.cpp +++ b/src/duckdb/src/planner/binder/query_node/bind_select_node.cpp @@ -315,7 +315,8 @@ static unique_ptr FinalizeBindOrderExpression(unique_ptr } auto result = CreateOrderExpression(std::move(expr), names, sql_types, table_index, ProjectionIndex(index)); if (!collation.empty()) { - if (sql_types[index].id() != LogicalTypeId::VARCHAR) { + if (sql_types[index].id() != LogicalTypeId::VARCHAR || sql_types[index].IsJSONType()) { + // a COLLATE expression (bind_collate_expression) rejects the JSON alias of VARCHAR the same way throw BinderException(*result, "COLLATE can only be applied to varchar columns"); } result->SetReturnType(LogicalType::VARCHAR_COLLATION(std::move(collation))); diff --git a/src/duckdb/src/planner/binder/statement/bind_update_extensions.cpp b/src/duckdb/src/planner/binder/statement/bind_update_extensions.cpp index cc94ffb0a..1af136064 100644 --- a/src/duckdb/src/planner/binder/statement/bind_update_extensions.cpp +++ b/src/duckdb/src/planner/binder/statement/bind_update_extensions.cpp @@ -19,6 +19,8 @@ BoundStatement Binder::Bind(UpdateExtensionsStatement &stmt) { result.types.emplace_back(LogicalType::VARCHAR); result.names.emplace_back("current_version"); result.types.emplace_back(LogicalType::VARCHAR); + result.names.emplace_back("error"); + result.types.emplace_back(LogicalType::VARCHAR); result.plan = make_uniq(std::move(stmt.info)); diff --git a/src/duckdb/src/planner/binder/tableref/bind_basetableref.cpp b/src/duckdb/src/planner/binder/tableref/bind_basetableref.cpp index c04282de1..77de85464 100644 --- a/src/duckdb/src/planner/binder/tableref/bind_basetableref.cpp +++ b/src/duckdb/src/planner/binder/tableref/bind_basetableref.cpp @@ -229,7 +229,7 @@ BoundStatement Binder::Bind(BaseTableRef &ref) { if (ClientConfig::GetConfig(context).use_replacement_scans && Settings::Get(config) && ExtensionHelper::IsFullPath(full_path)) { auto &fs = FileSystem::GetFileSystem(context); - if (!fs.IsDisabledForPath(full_path) && fs.FileExists(full_path)) { + if (!VirtualFileSystem::Get(context).IsDisabledForPath(full_path) && fs.FileExists(full_path)) { throw BinderException( "No extension found that is capable of reading the file \"%s\"\n* If this file is a supported file " "format you can explicitly use the reader functions, such as read_csv, read_json or read_parquet", diff --git a/src/duckdb/src/planner/logical_operator_repeatability.cpp b/src/duckdb/src/planner/logical_operator_repeatability.cpp index 69e87a337..3496096da 100644 --- a/src/duckdb/src/planner/logical_operator_repeatability.cpp +++ b/src/duckdb/src/planner/logical_operator_repeatability.cpp @@ -76,6 +76,7 @@ static LogicalOperatorRepeatability ClassifyOperatorType(LogicalOperator &op) { case LogicalOperatorType::LOGICAL_INVALID: case LogicalOperatorType::LOGICAL_LIMIT: case LogicalOperatorType::LOGICAL_TOP_N: + case LogicalOperatorType::LOGICAL_TOP_KEY_FILTER: case LogicalOperatorType::LOGICAL_COPY_TO_FILE: case LogicalOperatorType::LOGICAL_COPY_DATABASE: case LogicalOperatorType::LOGICAL_DELIM_GET: diff --git a/src/duckdb/src/planner/logical_operator_visitor.cpp b/src/duckdb/src/planner/logical_operator_visitor.cpp index b7c931b44..6d8c7fa2b 100644 --- a/src/duckdb/src/planner/logical_operator_visitor.cpp +++ b/src/duckdb/src/planner/logical_operator_visitor.cpp @@ -110,6 +110,13 @@ static void EnumerateOperatorExpressions(OPERATOR &op, const FUNC &callback) { } break; } + case LogicalOperatorType::LOGICAL_TOP_KEY_FILTER: { + auto &filter = op.template Cast(); + for (auto &node : filter.orders) { + callback(&node.expression); + } + break; + } case LogicalOperatorType::LOGICAL_DISTINCT: { auto &distinct = op.template Cast(); for (auto &target : distinct.distinct_targets) { diff --git a/src/duckdb/src/planner/operator/logical_limit.cpp b/src/duckdb/src/planner/operator/logical_limit.cpp index df0b24eea..87e90777f 100644 --- a/src/duckdb/src/planner/operator/logical_limit.cpp +++ b/src/duckdb/src/planner/operator/logical_limit.cpp @@ -1,5 +1,7 @@ #include "duckdb/planner/operator/logical_limit.hpp" +#include "duckdb/logging/logger.hpp" + namespace duckdb { LogicalLimit::LogicalLimit(BoundLimitNode limit_val, BoundLimitNode offset_val) @@ -34,6 +36,14 @@ idx_t LogicalLimit::EstimateCardinality(ClientContext &context) { return child_cardinality; } +void LogicalLimit::WarnUnorderedOffset(ClientContext &context) { + DUCKDB_LOG_WARNING(context, + "OFFSET is applied to a query whose row order is not guaranteed - the result may " + "differ between runs. This happens when the query contains order-breaking operators (e.g. " + "hash joins or aggregations), reads from a source that does not preserve order, or when " + "preserve_insertion_order=false. Add an ORDER BY to make the result deterministic."); +} + void LogicalLimit::ResolveTypes() { types = children[0]->types; } diff --git a/src/duckdb/src/planner/operator/logical_top_key_filter.cpp b/src/duckdb/src/planner/operator/logical_top_key_filter.cpp new file mode 100644 index 000000000..d6ee22fc5 --- /dev/null +++ b/src/duckdb/src/planner/operator/logical_top_key_filter.cpp @@ -0,0 +1,27 @@ +#include "duckdb/planner/operator/logical_top_key_filter.hpp" + +namespace duckdb { + +LogicalTopKeyFilter::LogicalTopKeyFilter(vector orders, idx_t limit) + : LogicalOperator(LogicalOperatorType::LOGICAL_TOP_KEY_FILTER), orders(std::move(orders)), limit(limit) { +} + +LogicalTopKeyFilter::~LogicalTopKeyFilter() { +} + +InsertionOrderPreservingMap LogicalTopKeyFilter::ParamsToString() const { + InsertionOrderPreservingMap result; + string keys; + for (idx_t i = 0; i < orders.size(); i++) { + if (i > 0) { + keys += "\n"; + } + keys += orders[i].ToString(); + } + result["Keys"] = keys; + result["Limit"] = to_string(limit); + SetParamsEstimatedCardinality(result); + return result; +} + +} // namespace duckdb diff --git a/src/duckdb/src/planner/sql_export/sql_export_window.cpp b/src/duckdb/src/planner/sql_export/sql_export_window.cpp index a4970a188..07579afb7 100644 --- a/src/duckdb/src/planner/sql_export/sql_export_window.cpp +++ b/src/duckdb/src/planner/sql_export/sql_export_window.cpp @@ -201,12 +201,18 @@ BoundExpressionSQLExportState::ExportWindowFunction(const BoundWindowExpression for (idx_t i = 0; i < expression.Partitions().size(); i++) { window->PartitionsMutable().push_back(std::move(children[ordinal++])); } + // Some functions read the ORDER BY values (the argument ordering if there is one, else the window ordering) + auto &window_function = expression.WindowFunction(); + bool requires_ordering = window_function && window_function->GetDefinition()->RequiresOrdering(); // RANGE offsets and GROUPS frames are defined in terms of the ORDER BY - const bool frame_needs_order = + bool needs_order = IsOrderDependentBoundary(expression.WindowStart()) || IsOrderDependentBoundary(expression.WindowEnd()); + if (requires_ordering && expression.ArgOrders().empty()) { + needs_order = true; + } for (auto &order : expression.OrderBy()) { auto &child = children[ordinal++]; - if (!frame_needs_order && SQLExportHelpers::IsConstantOrderKey(*order.expression, *child)) { + if (!needs_order && SQLExportHelpers::IsConstantOrderKey(*order.expression, *child)) { continue; } window->OrderByMutable().emplace_back( @@ -235,7 +241,7 @@ BoundExpressionSQLExportState::ExportWindowFunction(const BoundWindowExpression } for (auto &order : expression.ArgOrders()) { auto &child = children[ordinal++]; - if (SQLExportHelpers::IsConstantOrderKey(*order.expression, *child)) { + if (!requires_ordering && SQLExportHelpers::IsConstantOrderKey(*order.expression, *child)) { continue; } window->ArgOrdersMutable().emplace_back( diff --git a/src/duckdb/src/planner/table_filter_state.cpp b/src/duckdb/src/planner/table_filter_state.cpp index daf20fd9c..a516eb615 100644 --- a/src/duckdb/src/planner/table_filter_state.cpp +++ b/src/duckdb/src/planner/table_filter_state.cpp @@ -3,6 +3,7 @@ #include "duckdb/planner/table_filter_state.hpp" #include "duckdb/common/algorithm.hpp" #include "duckdb/common/operator/comparison_operators.hpp" +#include "duckdb/common/vector_operations/string_comparison.hpp" #include "duckdb/common/vector_operations/vector_operations.hpp" #include "duckdb/common/vector_operations/selection_helpers.hpp" #include "duckdb/common/vector/constant_vector.hpp" @@ -430,6 +431,12 @@ class ComparisonFilterExecutor final : public ExpressionFilterExecutor { } private: + template + static constexpr bool UseSelectionBatch() { + return UseBooleanSelectionBatch() || std::is_same_v || + std::is_same_v; + } + template idx_t TemplatedSelect(const UnifiedVectorFormat &vdata, T predicate, const SelectionVector &sel, idx_t approved_tuple_count) { @@ -437,7 +444,7 @@ class ComparisonFilterExecutor final : public ExpressionFilterExecutor { auto &mask = vdata.validity; idx_t result_count = 0; idx_t i = 0; - if constexpr (UseBooleanSelectionBatch() && !CAN_HAVE_NULL) { + if constexpr (UseSelectionBatch() && !CAN_HAVE_NULL) { if (!sel.IsSet() && !vdata.sel->IsSet()) { array_ptr output(result_sel.data(), result_sel.Capacity()); for (; i + 64 <= approved_tuple_count; i += 64) { @@ -470,21 +477,43 @@ class ComparisonFilterExecutor final : public ExpressionFilterExecutor { return TemplatedSelect(vdata, predicate, sel, approved_tuple_count); } + template + idx_t SelectEquality(const UnifiedVectorFormat &vdata, const SelectionVector &sel, idx_t approved_tuple_count) { + if constexpr (std::is_same_v) { + if (constant.GetValueUnsafe().IsInlined()) { + using INLINED_OP = typename InlinedStringEqualityOperator::OPERATOR; + return SelectOperation(vdata, sel, approved_tuple_count); + } + } + return SelectOperation(vdata, sel, approved_tuple_count); + } + + template + idx_t SelectOrdering(const UnifiedVectorFormat &vdata, const SelectionVector &sel, idx_t approved_tuple_count) { + if constexpr (std::is_same_v) { + auto mode = + StringComparison::SelectMode(vdata, constant.GetValueUnsafe(), sel, approved_tuple_count); + return StringComparison::Dispatch( + mode, [&](auto op) { return SelectOperation(vdata, sel, approved_tuple_count); }); + } + return SelectOperation(vdata, sel, approved_tuple_count); + } + template idx_t SelectTyped(const UnifiedVectorFormat &vdata, const SelectionVector &sel, idx_t approved_tuple_count) { switch (comparison_type) { case ExpressionType::COMPARE_EQUAL: - return SelectOperation(vdata, sel, approved_tuple_count); + return SelectEquality(vdata, sel, approved_tuple_count); case ExpressionType::COMPARE_NOTEQUAL: - return SelectOperation(vdata, sel, approved_tuple_count); + return SelectEquality(vdata, sel, approved_tuple_count); case ExpressionType::COMPARE_GREATERTHAN: - return SelectOperation(vdata, sel, approved_tuple_count); + return SelectOrdering(vdata, sel, approved_tuple_count); case ExpressionType::COMPARE_GREATERTHANOREQUALTO: - return SelectOperation(vdata, sel, approved_tuple_count); + return SelectOrdering(vdata, sel, approved_tuple_count); case ExpressionType::COMPARE_LESSTHAN: - return SelectOperation(vdata, sel, approved_tuple_count); + return SelectOrdering(vdata, sel, approved_tuple_count); case ExpressionType::COMPARE_LESSTHANOREQUALTO: - return SelectOperation(vdata, sel, approved_tuple_count); + return SelectOrdering(vdata, sel, approved_tuple_count); default: InternalException::Throw("Unsupported comparison type for comparison filter executor"); } diff --git a/src/duckdb/src/storage/compression/validity_uncompressed.cpp b/src/duckdb/src/storage/compression/validity_uncompressed.cpp index f395bc6d3..dcf2383f3 100644 --- a/src/duckdb/src/storage/compression/validity_uncompressed.cpp +++ b/src/duckdb/src/storage/compression/validity_uncompressed.cpp @@ -1,3 +1,4 @@ +#include "duckdb/common/atomic.hpp" #include "duckdb/common/exception.hpp" #include "duckdb/common/types/vector.hpp" #include "duckdb/function/compression_function.hpp" @@ -217,6 +218,24 @@ static idx_t ValidityEntryCount(idx_t count) { return count / ValidityMask::BITS_PER_VALUE + (count % ValidityMask::BITS_PER_VALUE != 0); } +//! Whether scans must read the entries atomically: only transient segments can still be appended to +static bool CanBeAppendedTo(ColumnSegment &segment) { + return segment.GetSegmentType() == ColumnSegmentType::TRANSIENT; +} + +static atomic &AtomicValidityEntry(validity_t &entry) { + static_assert(sizeof(atomic) == sizeof(validity_t), "atomic validity entries must not have overhead"); + return reinterpret_cast &>(entry); +} + +template +static validity_t LoadValidityEntry(const validity_t &entry) { + if (ATOMIC) { + return reinterpret_cast &>(entry).load(std::memory_order_relaxed); + } + return entry; +} + static unsafe_array_ptr ValidityScanData(const CompressionSegmentReader &reader, idx_t start, idx_t scan_count) { D_ASSERT(scan_count > 0); @@ -235,8 +254,9 @@ unique_ptr ValidityInitScan(const QueryContext &context, Colum // Scan base data //===--------------------------------------------------------------------===// -void ValidityUncompressed::UnalignedScan(unsafe_array_ptr input, idx_t input_size, idx_t input_start, - ValidityMask &result_mask, idx_t result_offset, idx_t scan_count) { +template +static void UnalignedScanInternal(unsafe_array_ptr input, idx_t input_size, idx_t input_start, + ValidityMask &result_mask, idx_t result_offset, idx_t scan_count) { D_ASSERT(input_start < input_size); D_ASSERT(scan_count <= input_size - input_start); D_ASSERT(ValidityEntryCount(input_size) <= input.size()); @@ -269,7 +289,7 @@ void ValidityUncompressed::UnalignedScan(unsafe_array_ptr inpu // the bitwise ops we use below don't work if the vector size is too small for (idx_t i = 0; i < scan_count; i++) { idx_t source_idx = input_start + i; - if (!ValidityMask::RowIsValid(input[source_idx / ValidityMask::BITS_PER_VALUE], + if (!ValidityMask::RowIsValid(LoadValidityEntry(input[source_idx / ValidityMask::BITS_PER_VALUE]), source_idx % ValidityMask::BITS_PER_VALUE)) { if (result_mask.CannotHaveNull()) { result_mask.Initialize(); @@ -325,7 +345,7 @@ void ValidityUncompressed::UnalignedScan(unsafe_array_ptr inpu // now start the bit games idx_t pos = 0; while (pos < scan_count) { - validity_t input_mask = input[input_entry]; + validity_t input_mask = LoadValidityEntry(input[input_entry]); idx_t bits_left = scan_count - pos; // these are bits left within the current entries (possibly extra than what we need). @@ -366,7 +386,7 @@ void ValidityUncompressed::UnalignedScan(unsafe_array_ptr inpu } else { // current_result_idx >= current_input_idx idx_t shift_amount = result_idx - input_idx; - input_mask = (input_mask & ~UPPER_MASKS[shift_amount]); + input_mask = (input_mask & ~ValidityUncompressed::UPPER_MASKS[shift_amount]); // X is arbitrary bits, P is arbitrary protected bits. // Note the zeroed out bits in INPUT_ENTRY - these have to be zeroed before shifting left to align with @@ -391,8 +411,9 @@ void ValidityUncompressed::UnalignedScan(unsafe_array_ptr inpu } // Once the windows are aligned, mask the input to prevent overwriting protected bits in the result_mask. - auto protected_upper_bits = UPPER_MASKS[ValidityMask::BITS_PER_VALUE - result_idx - window_size]; - auto protected_lower_bits = LOWER_MASKS[result_idx]; + auto protected_upper_bits = + ValidityUncompressed::UPPER_MASKS[ValidityMask::BITS_PER_VALUE - result_idx - window_size]; + auto protected_lower_bits = ValidityUncompressed::LOWER_MASKS[result_idx]; input_mask |= protected_upper_bits; input_mask |= protected_lower_bits; @@ -425,8 +446,9 @@ void ValidityUncompressed::UnalignedScan(unsafe_array_ptr inpu for (idx_t i = 0; i < scan_count; i++) { bool original_valid = debug_original_result.RowIsValid(i); idx_t source_idx = input_start + i; - bool input_valid = ValidityMask::RowIsValid(input[source_idx / ValidityMask::BITS_PER_VALUE], - source_idx % ValidityMask::BITS_PER_VALUE); + bool input_valid = + ValidityMask::RowIsValid(LoadValidityEntry(input[source_idx / ValidityMask::BITS_PER_VALUE]), + source_idx % ValidityMask::BITS_PER_VALUE); bool result_valid = result_mask.RowIsValid(result_offset + i); D_ASSERT(result_valid == (original_valid && input_valid)); } @@ -442,17 +464,24 @@ void ValidityUncompressed::UnalignedScan(unsafe_array_ptr inpu idx_t last_bit_in_last_entry = (result_offset + scan_count - 1) % ValidityMask::BITS_PER_VALUE; // lower bits of first entry should be unchanged - validity_t lower_mask = LOWER_MASKS[first_bit_in_first_entry]; + validity_t lower_mask = ValidityUncompressed::LOWER_MASKS[first_bit_in_first_entry]; D_ASSERT((debug_original_first_entry & lower_mask) == (debug_final_first_entry & lower_mask)); // upper bits of last entry should be unchanged - validity_t upper_mask = UPPER_MASKS[ValidityMask::BITS_PER_VALUE - last_bit_in_last_entry - 1]; + validity_t upper_mask = + ValidityUncompressed::UPPER_MASKS[ValidityMask::BITS_PER_VALUE - last_bit_in_last_entry - 1]; D_ASSERT((debug_original_last_entry & upper_mask) == (debug_final_last_entry & upper_mask)); #endif } -void ValidityUncompressed::AlignedScan(unsafe_array_ptr input, idx_t input_start, - ValidityMask &result_mask, idx_t scan_count) { +void ValidityUncompressed::UnalignedScan(unsafe_array_ptr input, idx_t input_size, idx_t input_start, + ValidityMask &result_mask, idx_t result_offset, idx_t scan_count) { + UnalignedScanInternal(input, input_size, input_start, result_mask, result_offset, scan_count); +} + +template +static void AlignedScanInternal(unsafe_array_ptr input, idx_t input_start, ValidityMask &result_mask, + idx_t scan_count) { D_ASSERT(input_start % ValidityMask::BITS_PER_VALUE == 0); // aligned scan: no need to do anything fancy @@ -464,7 +493,7 @@ void ValidityUncompressed::AlignedScan(unsafe_array_ptr input, D_ASSERT(start_offset <= input.size()); D_ASSERT(entry_scan_count <= input.size() - start_offset); for (idx_t i = 0; i < entry_scan_count; i++) { - auto input_entry = input[start_offset + i]; + auto input_entry = LoadValidityEntry(input[start_offset + i]); if (!result_data && input_entry == ValidityMask::ValidityBuffer::MAX_ENTRY) { continue; } @@ -476,6 +505,24 @@ void ValidityUncompressed::AlignedScan(unsafe_array_ptr input, } } +void ValidityUncompressed::AlignedScan(unsafe_array_ptr input, idx_t input_start, + ValidityMask &result_mask, idx_t scan_count) { + AlignedScanInternal(input, input_start, result_mask, scan_count); +} + +template +static void ValidityScanInternal(unsafe_array_ptr input_data, idx_t start, idx_t scan_count, + ValidityMask &result_mask, idx_t result_offset, ScanVectorType scan_type) { + auto input_start = start % ValidityMask::BITS_PER_VALUE; + if (scan_type == ScanVectorType::SCAN_ENTIRE_VECTOR && input_start == 0) { + D_ASSERT(result_offset == 0); + AlignedScanInternal(input_data, 0, result_mask, scan_count); + } else { + UnalignedScanInternal(input_data, input_start + scan_count, input_start, result_mask, result_offset, + scan_count); + } +} + void ValidityScan(ColumnSegment &segment, ColumnScanState &state, idx_t scan_count, ValidityMask &result_mask, idx_t result_offset, ScanVectorType scan_type) { if (scan_count == 0) { @@ -486,19 +533,32 @@ void ValidityScan(ColumnSegment &segment, ColumnScanState &state, idx_t scan_cou auto &scan_state = state.scan_state->Cast(); auto input_data = ValidityScanData(scan_state.reader, start, scan_count); D_ASSERT(scan_state.block_id == segment.GetBlockHandle()->BlockId()); - auto input_start = start % ValidityMask::BITS_PER_VALUE; - if (scan_type == ScanVectorType::SCAN_ENTIRE_VECTOR && input_start == 0) { - D_ASSERT(result_offset == 0); - ValidityUncompressed::AlignedScan(input_data, 0, result_mask, scan_count); + if (CanBeAppendedTo(segment)) { + ValidityScanInternal(input_data, start, scan_count, result_mask, result_offset, scan_type); } else { - ValidityUncompressed::UnalignedScan(input_data, input_start + scan_count, input_start, result_mask, - result_offset, scan_count); + ValidityScanInternal(input_data, start, scan_count, result_mask, result_offset, scan_type); } } //===--------------------------------------------------------------------===// // Select //===--------------------------------------------------------------------===// +template +static void ValiditySelectInternal(unsafe_array_ptr input_data, idx_t start, + ValidityMask &result_mask, const SelectionVector &sel, idx_t sel_count, + idx_t vector_count, idx_t result_offset) { + auto input_start = start % ValidityMask::BITS_PER_VALUE; + for (idx_t i = 0; i < sel_count; i++) { + auto selected_index = sel.get_index(i); + D_ASSERT(selected_index < vector_count); + auto source_idx = input_start + selected_index; + auto entry = LoadValidityEntry(input_data[source_idx / ValidityMask::BITS_PER_VALUE]); + if (!ValidityMask::RowIsValid(entry, source_idx % ValidityMask::BITS_PER_VALUE)) { + result_mask.SetInvalid(result_offset + i); + } + } +} + void ValiditySelect(ColumnSegment &segment, ColumnScanState &state, idx_t vector_count, ValidityMask &result_mask, const SelectionVector &sel, idx_t sel_count, idx_t result_offset) { auto start = state.GetPositionInSegment(); @@ -510,15 +570,10 @@ void ValiditySelect(ColumnSegment &segment, ColumnScanState &state, idx_t vector auto &scan_state = state.scan_state->Cast(); auto input_data = ValidityScanData(scan_state.reader, start, vector_count); - auto input_start = start % ValidityMask::BITS_PER_VALUE; - for (idx_t i = 0; i < sel_count; i++) { - auto selected_index = sel.get_index(i); - D_ASSERT(selected_index < vector_count); - auto source_idx = input_start + selected_index; - auto entry = input_data[source_idx / ValidityMask::BITS_PER_VALUE]; - if (!ValidityMask::RowIsValid(entry, source_idx % ValidityMask::BITS_PER_VALUE)) { - result_mask.SetInvalid(result_offset + i); - } + if (CanBeAppendedTo(segment)) { + ValiditySelectInternal(input_data, start, result_mask, sel, sel_count, vector_count, result_offset); + } else { + ValiditySelectInternal(input_data, start, result_mask, sel, sel_count, vector_count, result_offset); } } @@ -542,6 +597,37 @@ unique_ptr ValidityInitSegment(ColumnSegment &segment, b return nullptr; } +static void ValidityAppendInvalid(CompressionAppendState &append_state, ColumnSegment &segment, + BaseStatistics &validity_stats, UnifiedVectorFormat &data, idx_t offset, + idx_t append_count) { + auto entries = reinterpret_cast(append_state.handle.GetDataMutable() + segment.GetBlockOffset()); + // the bits of one entry are cleared together: concurrent scans read the entries atomically + idx_t current_entry = 0; + validity_t invalid_bits = 0; + auto flush_entry = [&]() { + if (invalid_bits) { + AtomicValidityEntry(entries[current_entry]).fetch_and(~invalid_bits, std::memory_order_relaxed); + invalid_bits = 0; + } + }; + for (idx_t i = 0; i < append_count; i++) { + auto idx = data.sel->get_index(offset + i); + if (!data.validity.RowIsValidUnsafe(idx)) { + auto row = segment.count + i; + auto entry = row / ValidityMask::BITS_PER_VALUE; + if (entry != current_entry) { + flush_entry(); + current_entry = entry; + } + invalid_bits |= validity_t(1) << (row % ValidityMask::BITS_PER_VALUE); + validity_stats.SetHasNullFast(); + } else { + validity_stats.SetHasNoNullFast(); + } + } + flush_entry(); +} + idx_t ValidityAppend(CompressionAppendState &append_state, ColumnSegment &segment, BaseStatistics &validity_stats, UnifiedVectorFormat &data, idx_t offset, idx_t vcount) { auto max_tuples = segment.SegmentSize() / ValidityMask::STANDARD_MASK_SIZE * STANDARD_VECTOR_SIZE; @@ -550,21 +636,10 @@ idx_t ValidityAppend(CompressionAppendState &append_state, ColumnSegment &segmen // no null values: skip append segment.count += append_count; validity_stats.SetHasNoNullFast(); - return append_count; - } - - ValidityMask mask(reinterpret_cast(append_state.handle.GetDataMutable() + segment.GetBlockOffset()), - max_tuples); - for (idx_t i = 0; i < append_count; i++) { - auto idx = data.sel->get_index(offset + i); - if (!data.validity.RowIsValidUnsafe(idx)) { - mask.SetInvalidUnsafe(segment.count + i); - validity_stats.SetHasNullFast(); - } else { - validity_stats.SetHasNoNullFast(); - } + } else { + ValidityAppendInvalid(append_state, segment, validity_stats, data, offset, append_count); + segment.count += append_count; } - segment.count += append_count; return append_count; } @@ -573,26 +648,21 @@ idx_t ValidityFinalizeAppend(ColumnSegment &segment, BaseStatistics &stats) { } void ValidityRevertAppend(ColumnSegment &segment, idx_t new_count) { - idx_t start_bit = new_count; - + D_ASSERT(new_count <= segment.count); + D_ASSERT(CanBeAppendedTo(segment)); + // appends only clear bits: set the bits of the reverted rows again, concurrent scans read these entries auto &buffer_manager = BufferManager::GetBufferManager(segment.GetDatabase()); auto handle = buffer_manager.Pin(segment.GetBlockHandle()); - auto buffer_ptr = handle.GetDataMutable() + segment.GetBlockOffset(); - idx_t revert_start; - if (start_bit % 8 != 0) { - // handle sub-bit stuff (yay) - idx_t byte_pos = start_bit / 8; - idx_t bit_end = (byte_pos + 1) * 8; - ValidityMask mask(reinterpret_cast(buffer_ptr), segment.count); - for (idx_t i = start_bit; i < bit_end && i < segment.count; i++) { - mask.SetValid(i); + auto entries = reinterpret_cast(handle.GetDataMutable() + segment.GetBlockOffset()); + auto entry_start = new_count / ValidityMask::BITS_PER_VALUE; + auto entry_end = ValidityEntryCount(segment.count); + for (idx_t entry_idx = entry_start; entry_idx < entry_end; entry_idx++) { + auto valid_bits = ValidityMask::ValidityBuffer::MAX_ENTRY; + if (entry_idx == entry_start) { + valid_bits = ~ValidityUncompressed::LOWER_MASKS[new_count % ValidityMask::BITS_PER_VALUE]; } - revert_start = bit_end / 8; - } else { - revert_start = start_bit / 8; + AtomicValidityEntry(entries[entry_idx]).fetch_or(valid_bits, std::memory_order_relaxed); } - // for the rest, we just memset - memset(buffer_ptr + revert_start, 0xFF, segment.SegmentSize() - revert_start); } //===--------------------------------------------------------------------===// diff --git a/src/duckdb/src/storage/data_table.cpp b/src/duckdb/src/storage/data_table.cpp index 8533475b0..5c9235b98 100644 --- a/src/duckdb/src/storage/data_table.cpp +++ b/src/duckdb/src/storage/data_table.cpp @@ -156,7 +156,7 @@ DataTable::DataTable(ClientContext &context, DataTable &parent, idx_t removed_co this->row_groups = parent.row_groups->RemoveColumn(removed_column); // scan the original table, and fill the new column with the transformed value - local_storage.DropColumn(parent, *this, removed_column); + local_storage.DropColumn(context, parent, *this, removed_column); // this table replaces the previous table, hence the parent is no longer the root DataTable parent.version = DataTableVersion::ALTERED; @@ -184,7 +184,7 @@ DataTable::DataTable(ClientContext &context, DataTable &parent, BoundConstraint VerifyNewConstraint(context, local_storage, parent, not_null); } } - local_storage.MoveStorage(parent, *this); + local_storage.MoveStorage(context, parent, *this); parent.version = DataTableVersion::ALTERED; } @@ -723,7 +723,7 @@ void DataTable::VerifyForeignKeyConstraint(optional_ptr stora auto &data_table = table_entry.GetStorage(); auto &local_storage = LocalStorage::Get(context, db); auto sibling_storage = local_storage.GetStorage(data_table); - auto sibling_delete_indexes = sibling_storage ? &sibling_storage->delete_indexes : nullptr; + auto sibling_delete_indexes = sibling_storage ? &sibling_storage->GetDeleteIndexes() : nullptr; data_table.info->indexes.VerifyForeignKey(sibling_delete_indexes, dst_keys_ptr, dst_chunk, global_conflict_manager); @@ -852,7 +852,7 @@ void DataTable::VerifyAppendConstraints(ConstraintState &constraint_state, Clien } if (HasUniqueIndexes()) { - info->indexes.VerifyUniqueIndexes(storage ? &storage->delete_indexes : nullptr, chunk, manager); + info->indexes.VerifyUniqueIndexes(storage ? &storage->GetDeleteIndexes() : nullptr, chunk, manager); } auto &constraints = table.GetConstraints(); diff --git a/src/duckdb/src/storage/external_file_cache/caching_file_system_wrapper.cpp b/src/duckdb/src/storage/external_file_cache/caching_file_system_wrapper.cpp index 8be55c0db..6f77041b2 100644 --- a/src/duckdb/src/storage/external_file_cache/caching_file_system_wrapper.cpp +++ b/src/duckdb/src/storage/external_file_cache/caching_file_system_wrapper.cpp @@ -318,26 +318,6 @@ vector CachingFileSystemWrapper::Glob(const string &path, FileOpen //===----------------------------------------------------------------------===// // SubSystem Operations //===----------------------------------------------------------------------===// -void CachingFileSystemWrapper::RegisterSubSystem(unique_ptr sub_fs) { - underlying_file_system.RegisterSubSystem(std::move(sub_fs)); -} - -void CachingFileSystemWrapper::RegisterCompressionFilesystem(unique_ptr fs) { - underlying_file_system.RegisterCompressionFilesystem(std::move(fs)); -} - -void CachingFileSystemWrapper::UnregisterSubSystem(const string &name) { - underlying_file_system.UnregisterSubSystem(name); -} - -unique_ptr CachingFileSystemWrapper::ExtractSubSystem(const string &name) { - return underlying_file_system.ExtractSubSystem(name); -} - -vector CachingFileSystemWrapper::ListSubSystems() { - return underlying_file_system.ListSubSystems(); -} - bool CachingFileSystemWrapper::CanHandleFile(const string &fpath) { return underlying_file_system.CanHandleFile(fpath); } @@ -392,20 +372,4 @@ unique_ptr CachingFileSystemWrapper::OpenCompressedFile(QueryContext return underlying_file_system.OpenCompressedFile(context, std::move(handle), write); } -void CachingFileSystemWrapper::SetDisabledFileSystems(const vector &names) { - underlying_file_system.SetDisabledFileSystems(names); -} - -vector CachingFileSystemWrapper::GetDisabledFileSystems() { - return underlying_file_system.GetDisabledFileSystems(); -} - -bool CachingFileSystemWrapper::SubSystemIsDisabled(const string &name) { - return underlying_file_system.SubSystemIsDisabled(name); -} - -bool CachingFileSystemWrapper::IsDisabledForPath(const string &path) { - return underlying_file_system.IsDisabledForPath(path); -} - } // namespace duckdb diff --git a/src/duckdb/src/storage/local_storage.cpp b/src/duckdb/src/storage/local_storage.cpp index 821ada7f4..83280d3c9 100644 --- a/src/duckdb/src/storage/local_storage.cpp +++ b/src/duckdb/src/storage/local_storage.cpp @@ -22,7 +22,8 @@ namespace duckdb { LocalTableStorage::LocalTableStorage(Context &context, DataTable &table) - : table_ref(table), allocator(Allocator::Get(table.db)), deleted_rows(0), optimistic_writer(table) { + : table_ref(table), allocator(Allocator::Get(table.db)), deleted_rows(0), optimistic_writer(table), + indexes(make_shared_ptr()) { auto types = table.GetTypes(); auto data_table_info = table.GetDataTableInfo(); row_groups = optimistic_writer.CreateCollection(context, table, types, OptimisticWritePartialManagers::GLOBAL); @@ -30,7 +31,25 @@ LocalTableStorage::LocalTableStorage(Context &context, DataTable &table) collection.InitializeEmpty(); // Create the transaction-local delete and append indexes. - data_table_info->GetIndexes().InitializeLocalIndexes(delete_indexes, append_indexes); + data_table_info->GetIndexes().InitializeLocalIndexes(GetDeleteIndexes(), GetAppendIndexes()); +} + +//! The storage of the old version of the table stays as it is: it shares the indexes and the persistent column +//! data with the new version, and is not used for commit or rollback anymore +static void PrepareParentForAlter(ClientContext &context, LocalTableStorage &parent) { + // finish the partially written blocks: the new version does not take over the writer + parent.GetOptimisticWriter().FinalFlush(context.GetContext()); + for (auto &collection : parent.optimistic_collections) { + if (collection) { + throw TransactionException("Cannot alter a table that is being written to by another statement"); + } + } +} + +static unique_ptr CreateAlteredCollection(shared_ptr collection) { + auto result = make_uniq(); + result->collection = std::move(collection); + return result; } LocalTableStorage::LocalTableStorage(ClientContext &context, DataTable &new_data_table, LocalTableStorage &parent, @@ -38,50 +57,44 @@ LocalTableStorage::LocalTableStorage(ClientContext &context, DataTable &new_data const vector &bound_columns, Expression &cast_expr, TransactionData transaction) : table_ref(new_data_table), allocator(Allocator::Get(new_data_table.db)), deleted_rows(parent.deleted_rows.load()), - optimistic_collections(std::move(parent.optimistic_collections)), - optimistic_writer(new_data_table, parent.optimistic_writer) { + optimistic_writer(new_data_table), indexes(parent.indexes) { + PrepareParentForAlter(context, parent); // Alter the column type. auto &parent_collection = *parent.row_groups->collection; auto new_collection = parent_collection.AlterType(context, alter_column_index, target_type, bound_columns, cast_expr, transaction); parent_collection.CommitDropColumn(alter_column_index); - row_groups = std::move(parent.row_groups); - row_groups->collection = std::move(new_collection); - row_groups->ResetCollectionAccounting(); - - append_indexes.Move(parent.append_indexes); - delete_indexes.Move(parent.delete_indexes); + row_groups = CreateAlteredCollection(std::move(new_collection)); } -LocalTableStorage::LocalTableStorage(DataTable &new_data_table, LocalTableStorage &parent, +LocalTableStorage::LocalTableStorage(ClientContext &context, DataTable &new_data_table, LocalTableStorage &parent, const idx_t drop_column_index) : table_ref(new_data_table), allocator(Allocator::Get(new_data_table.db)), deleted_rows(parent.deleted_rows.load()), - optimistic_collections(std::move(parent.optimistic_collections)), - optimistic_writer(new_data_table, parent.optimistic_writer) { + optimistic_writer(new_data_table), indexes(parent.indexes) { + PrepareParentForAlter(context, parent); // Remove the column from the previous table storage. auto &parent_collection = *parent.row_groups->collection; auto new_collection = parent_collection.RemoveColumn(drop_column_index); parent_collection.CommitDropColumn(drop_column_index); - row_groups = std::move(parent.row_groups); - row_groups->collection = std::move(new_collection); - row_groups->ResetCollectionAccounting(); - - append_indexes.Move(parent.append_indexes); - delete_indexes.Move(parent.delete_indexes); + row_groups = CreateAlteredCollection(std::move(new_collection)); } LocalTableStorage::LocalTableStorage(ClientContext &context, DataTable &new_dt, LocalTableStorage &parent, ColumnDefinition &new_column, ExpressionExecutor &default_executor) : table_ref(new_dt), allocator(Allocator::Get(new_dt.db)), deleted_rows(parent.deleted_rows.load()), - optimistic_collections(std::move(parent.optimistic_collections)), - optimistic_writer(new_dt, parent.optimistic_writer) { + optimistic_writer(new_dt), indexes(parent.indexes) { + PrepareParentForAlter(context, parent); auto &parent_collection = *parent.row_groups->collection; auto new_collection = parent_collection.AddColumn(context, new_column, default_executor); - row_groups = std::move(parent.row_groups); - row_groups->collection = std::move(new_collection); - row_groups->ResetCollectionAccounting(); - append_indexes.Move(parent.append_indexes); - delete_indexes.Move(parent.delete_indexes); + row_groups = CreateAlteredCollection(std::move(new_collection)); +} + +LocalTableStorage::LocalTableStorage(ClientContext &context, DataTable &new_dt, LocalTableStorage &parent) + : table_ref(new_dt), allocator(Allocator::Get(new_dt.db)), deleted_rows(parent.deleted_rows.load()), + optimistic_writer(new_dt), indexes(parent.indexes) { + // a new constraint does not change the data: the row groups are shared with the old version + PrepareParentForAlter(context, parent); + row_groups = CreateAlteredCollection(parent.row_groups->collection); } LocalTableStorage::~LocalTableStorage() { @@ -122,7 +135,7 @@ idx_t LocalTableStorage::EstimatedSize() const { } // return the size of the appended rows and the index size - return data_size + append_indexes.GetInMemorySize(); + return data_size + GetAppendIndexes().GetInMemorySize(); } void LocalTableStorage::WriteNewRowGroup(Context &context, idx_t flushed_row_group_idx) { @@ -193,7 +206,7 @@ ErrorData LocalTableStorage::AppendToIndexes(DuckTransaction &transaction, RowGr table_chunk.data[col_id].Reference(index_chunk.data[i]); } - error = index_list.Append(delete_indexes, table_chunk, start_row, index_append_mode, checkpoint_id); + error = index_list.Append(GetDeleteIndexes(), table_chunk, start_row, index_append_mode, checkpoint_id); if (error.HasError()) { break; } @@ -322,23 +335,21 @@ void LocalTableStorage::Rollback() { //===--------------------------------------------------------------------===// // LocalTableManager //===--------------------------------------------------------------------===// -optional_ptr LocalTableManager::GetStorage(const DataTable &table) const { +shared_ptr LocalTableManager::GetStorage(const DataTable &table) const { lock_guard l(table_storage_lock); auto entry = table_storage.find(table); - return entry == table_storage.end() ? nullptr : entry->second.get(); + return entry == table_storage.end() ? nullptr : entry->second; } -LocalTableStorage &LocalTableManager::GetOrCreateStorage(Context &context, DataTable &table) { +shared_ptr LocalTableManager::GetOrCreateStorage(Context &context, DataTable &table) { lock_guard l(table_storage_lock); auto entry = table_storage.find(table); if (entry == table_storage.end()) { auto new_storage = make_shared_ptr(context, table); - auto storage = new_storage.get(); - table_storage.insert(make_pair(reference(table), std::move(new_storage))); - return *storage; - } else { - return *entry->second.get(); + table_storage.insert(make_pair(reference(table), new_storage)); + return new_storage; } + return entry->second; } bool LocalTableManager::IsEmpty() const { @@ -417,6 +428,7 @@ void LocalStorage::InitializeScan(const QueryContext &context, DataTable &table, if (storage == nullptr || storage->GetCollection().GetTotalRows() == 0) { return; } + state.local_storage = storage; state.local_row_groups_lock = storage->flush_lock.GetSharedLock(); storage->InitializeScan(context, state, table_filters); } @@ -452,6 +464,7 @@ optional_idx LocalStorage::NextParallelScan(ClientContext &context, DataTable &t return optional_idx(); } if (!scan_state.local_row_groups_lock) { + scan_state.local_storage = storage; scan_state.local_row_groups_lock = storage->flush_lock.GetSharedLock(); } return storage->GetCollection().NextParallelScan(context, state, scan_state, initialize_columns); @@ -460,7 +473,7 @@ optional_idx LocalStorage::NextParallelScan(ClientContext &context, DataTable &t void LocalStorage::InitializeAppend(Context &context, LocalAppendState &state, DataTable &table, DuckTableEntry &table_entry) { state.context = &context; - state.storage = &table_manager.GetOrCreateStorage(context, table); + state.storage = table_manager.GetOrCreateStorage(context, table); state.append_lock = state.storage->append_lock.GetExclusiveLock(); state.storage->table_entry = &table_entry; state.storage->GetCollection().InitializeAppend(TransactionData(transaction), state.append_state); @@ -469,7 +482,7 @@ void LocalStorage::InitializeAppend(Context &context, LocalAppendState &state, D void LocalStorage::InitializeStorage(Context &context, LocalAppendState &state, DataTable &table, DuckTableEntry &table_entry) { state.context = &context; - state.storage = &table_manager.GetOrCreateStorage(context, table); + state.storage = table_manager.GetOrCreateStorage(context, table); state.storage->table_entry = &table_entry; } @@ -495,7 +508,7 @@ void LocalTableStorage::AppendToDeleteIndexes(Vector &row_ids, DataChunk &delete return; } if (committed_count == delete_chunk.size()) { - delete_indexes.AppendToDeleteIndexes(delete_chunk, row_ids); + GetDeleteIndexes().AppendToDeleteIndexes(delete_chunk, row_ids); return; } @@ -506,7 +519,7 @@ void LocalTableStorage::AppendToDeleteIndexes(Vector &row_ids, DataChunk &delete Vector committed_row_ids(row_ids, committed_sel, committed_count); committed_row_ids.Flatten(); - delete_indexes.AppendToDeleteIndexes(committed_chunk, committed_row_ids); + GetDeleteIndexes().AppendToDeleteIndexes(committed_chunk, committed_row_ids); } void LocalStorage::Append(LocalAppendState &state, DuckTableEntry &table_entry, DataChunk &table_chunk) { @@ -515,9 +528,10 @@ void LocalStorage::Append(LocalAppendState &state, DuckTableEntry &table_entry, auto offset = NumericCast(MAX_ROW_ID) + storage->GetCollection().GetNextRowId(); idx_t base_id = offset + state.append_state.total_append_count; - if (!storage->append_indexes.Empty()) { - auto error = storage->append_indexes.Append(storage->delete_indexes, table_chunk, NumericCast(base_id), - storage->index_append_mode, optional_idx()); + if (!storage->GetAppendIndexes().Empty()) { + auto error = + storage->GetAppendIndexes().Append(storage->GetDeleteIndexes(), table_chunk, NumericCast(base_id), + storage->index_append_mode, optional_idx()); if (error.HasError()) { error.Throw(); } @@ -539,13 +553,14 @@ void LocalStorage::FinalizeAppend(LocalAppendState &state) { void LocalStorage::LocalMerge(Context &context, DataTable &table, DuckTableEntry &table_entry, OptimisticWriteCollection &collection) { - auto &storage = table_manager.GetOrCreateStorage(context, table); + auto storage_ptr = table_manager.GetOrCreateStorage(context, table); + auto &storage = *storage_ptr; auto append_lock = storage.append_lock.GetExclusiveLock(); storage.table_entry = &table_entry; - if (!storage.append_indexes.Empty()) { + if (!storage.GetAppendIndexes().Empty()) { // append data to indexes if required row_t base_id = MAX_ROW_ID + NumericCast(storage.GetCollection().GetNextRowId()); - auto error = storage.AppendToIndexes(transaction, *collection.collection, storage.append_indexes, + auto error = storage.AppendToIndexes(transaction, *collection.collection, storage.GetAppendIndexes(), table.GetTypes(), base_id); if (error.HasError()) { error.Throw(); @@ -557,23 +572,27 @@ void LocalStorage::LocalMerge(Context &context, DataTable &table, DuckTableEntry PhysicalIndex LocalStorage::CreateOptimisticCollection(Context &context, DataTable &table, unique_ptr collection) { - auto &storage = table_manager.GetOrCreateStorage(context, table); + auto storage_ptr = table_manager.GetOrCreateStorage(context, table); + auto &storage = *storage_ptr; return storage.CreateOptimisticCollection(std::move(collection)); } OptimisticWriteCollection &LocalStorage::GetOptimisticCollection(Context &context, DataTable &table, const PhysicalIndex collection_index) { - auto &storage = table_manager.GetOrCreateStorage(context, table); + auto storage_ptr = table_manager.GetOrCreateStorage(context, table); + auto &storage = *storage_ptr; return storage.GetOptimisticCollection(collection_index); } void LocalStorage::ResetOptimisticCollection(Context &context, DataTable &table, const PhysicalIndex collection_index) { - auto &storage = table_manager.GetOrCreateStorage(context, table); + auto storage_ptr = table_manager.GetOrCreateStorage(context, table); + auto &storage = *storage_ptr; storage.ResetOptimisticCollection(collection_index); } OptimisticDataWriter &LocalStorage::GetOptimisticWriter(Context &context, DataTable &table) { - auto &storage = table_manager.GetOrCreateStorage(context, table); + auto storage_ptr = table_manager.GetOrCreateStorage(context, table); + auto &storage = *storage_ptr; return storage.GetOptimisticWriter(); } @@ -596,7 +615,7 @@ idx_t LocalStorage::Delete(Context &context, DataTable &table, DuckTableEntry &t auto flush_key = storage->flush_lock.GetSharedLock(); auto ids = FlatVector::GetDataMutable(row_ids); - if (storage->append_indexes.Empty()) { + if (storage->GetAppendIndexes().Empty()) { idx_t delete_count = storage->GetCollection().Delete(TransactionData::Unversioned(), table_entry, ids, count); storage->deleted_rows += delete_count; return delete_count; @@ -609,7 +628,7 @@ idx_t LocalStorage::Delete(Context &context, DataTable &table, DuckTableEntry &t storage->deleted_rows += delete_count; if (!deleted_ids.has_skipped_rows) { // all rows were deleted - storage->GetCollection().RemoveFromIndexes(context, storage->append_indexes, row_ids, count, + storage->GetCollection().RemoveFromIndexes(context, storage->GetAppendIndexes(), row_ids, count, IndexRemovalType::MAIN_INDEX_ONLY); return delete_count; } @@ -622,7 +641,7 @@ idx_t LocalStorage::Delete(Context &context, DataTable &table, DuckTableEntry &t writer.WriteValue(row_id); } } - storage->GetCollection().RemoveFromIndexes(context, storage->append_indexes, deleted_row_id_vector, + storage->GetCollection().RemoveFromIndexes(context, storage->GetAppendIndexes(), deleted_row_id_vector, deleted_row_ids.size(), IndexRemovalType::MAIN_INDEX_ONLY); } return delete_count; @@ -783,15 +802,13 @@ void LocalStorage::DropTable(DataTable &table) { storage->is_dropped = true; } -void LocalStorage::MoveStorage(DataTable &old_dt, DataTable &new_dt) { +void LocalStorage::MoveStorage(ClientContext &context, DataTable &old_dt, DataTable &new_dt) { // check if there are any pending appends for the old version of the table - auto new_storage = table_manager.MoveEntry(old_dt); - if (!new_storage) { + auto storage = table_manager.MoveEntry(old_dt); + if (!storage) { return; } - // take over the storage from the old entry - new_storage->table_ref = new_dt; - table_manager.InsertEntry(new_dt, std::move(new_storage)); + table_manager.InsertEntry(new_dt, make_shared_ptr(context, new_dt, *storage)); } void LocalStorage::AddColumn(ClientContext &context, DataTable &old_dt, DataTable &new_dt, ColumnDefinition &new_column, @@ -805,13 +822,14 @@ void LocalStorage::AddColumn(ClientContext &context, DataTable &old_dt, DataTabl table_manager.InsertEntry(new_dt, std::move(new_storage)); } -void LocalStorage::DropColumn(DataTable &old_dt, DataTable &new_dt, const idx_t drop_column_index) { +void LocalStorage::DropColumn(ClientContext &context, DataTable &old_dt, DataTable &new_dt, + const idx_t drop_column_index) { // check if there are any pending appends for the old version of the table auto storage = table_manager.MoveEntry(old_dt); if (!storage) { return; } - auto new_storage = make_shared_ptr(new_dt, *storage, drop_column_index); + auto new_storage = make_shared_ptr(context, new_dt, *storage, drop_column_index); table_manager.InsertEntry(new_dt, std::move(new_storage)); } @@ -848,11 +866,12 @@ bool LocalStorage::CanFetch(DataTable &table, const row_t row_id) { } TableIndexList &LocalStorage::GetIndexes(Context &context, DataTable &table) { - auto &storage = table_manager.GetOrCreateStorage(context, table); - return storage.append_indexes; + auto storage_ptr = table_manager.GetOrCreateStorage(context, table); + auto &storage = *storage_ptr; + return storage.GetAppendIndexes(); } -optional_ptr LocalStorage::GetStorage(const DataTable &table) { +shared_ptr LocalStorage::GetStorage(const DataTable &table) { return table_manager.GetStorage(table); } diff --git a/src/duckdb/src/storage/serialization/serialize_logical_operator.cpp b/src/duckdb/src/storage/serialization/serialize_logical_operator.cpp index 083549e64..10d01c213 100644 --- a/src/duckdb/src/storage/serialization/serialize_logical_operator.cpp +++ b/src/duckdb/src/storage/serialization/serialize_logical_operator.cpp @@ -179,6 +179,9 @@ unique_ptr LogicalOperator::Deserialize(Deserializer &deseriali case LogicalOperatorType::LOGICAL_SET: result = LogicalSet::Deserialize(deserializer); break; + case LogicalOperatorType::LOGICAL_TOP_KEY_FILTER: + result = LogicalTopKeyFilter::Deserialize(deserializer); + break; case LogicalOperatorType::LOGICAL_TOP_N: result = LogicalTopN::Deserialize(deserializer); break; @@ -908,6 +911,19 @@ unique_ptr LogicalSetOperation::Deserialize(Deserializer &deser return std::move(result); } +void LogicalTopKeyFilter::Serialize(Serializer &serializer) const { + LogicalOperator::Serialize(serializer); + serializer.WritePropertyWithDefault>(200, "orders", orders); + serializer.WritePropertyWithDefault(201, "limit", limit); +} + +unique_ptr LogicalTopKeyFilter::Deserialize(Deserializer &deserializer) { + auto orders = deserializer.ReadPropertyWithDefault>(200, "orders"); + auto limit = deserializer.ReadPropertyWithDefault(201, "limit"); + auto result = duckdb::unique_ptr(new LogicalTopKeyFilter(std::move(orders), limit)); + return std::move(result); +} + void LogicalTopN::Serialize(Serializer &serializer) const { LogicalOperator::Serialize(serializer); serializer.WritePropertyWithDefault>(200, "orders", orders); diff --git a/src/duckdb/src/storage/table/column_data_checkpointer.cpp b/src/duckdb/src/storage/table/column_data_checkpointer.cpp index 0055a2ca8..c62f760ea 100644 --- a/src/duckdb/src/storage/table/column_data_checkpointer.cpp +++ b/src/duckdb/src/storage/table/column_data_checkpointer.cpp @@ -312,7 +312,11 @@ bool ColumnDataCheckpointer::ValidityCoveredByBasedata(vector &row_group_map, It i } // Row groups do not overlap: we can guarantee that the tuples qualify qualifying_tuples = last_unresolved_row_group_sum; + // The sum may already count the row groups that wait for a later tuple + qualify_later = 0; ++last_unresolved_entry; auto &upcoming_row_group = last_unresolved_entry->second.row_group.get().GetNode(); auto &upcoming_stats = *last_unresolved_entry->second.stats; diff --git a/src/duckdb/src/storage/table/variant/variant_shredding.cpp b/src/duckdb/src/storage/table/variant/variant_shredding.cpp index a979eb448..783b8b76a 100644 --- a/src/duckdb/src/storage/table/variant/variant_shredding.cpp +++ b/src/duckdb/src/storage/table/variant/variant_shredding.cpp @@ -146,88 +146,21 @@ struct VariantStatsVisitor { } } - static void VisitDefault(VariantLogicalType type_id, const_data_ptr_t, VariantShreddingStats &stats, + static void VisitDefault(const LogicalType &type, const_data_ptr_t, VariantShreddingStats &stats, idx_t stats_column_index) { - throw InternalException("VariantLogicalType(%s) not handled", EnumUtil::ToString(type_id)); + throw InternalException("VariantLogicalType(%s) not handled", type.ToString()); } }; -static unordered_set GetVariantType(const LogicalType &type) { +static unordered_set GetVariantType(const LogicalType &type) { if (type.id() == LogicalTypeId::ANY) { return {}; } - switch (type.id()) { - case LogicalTypeId::STRUCT: - return {VariantLogicalType::OBJECT}; - case LogicalTypeId::LIST: - return {VariantLogicalType::ARRAY}; - case LogicalTypeId::BOOLEAN: - return {VariantLogicalType::BOOL_TRUE, VariantLogicalType::BOOL_FALSE}; - case LogicalTypeId::TINYINT: - return {VariantLogicalType::INT8}; - case LogicalTypeId::SMALLINT: - return {VariantLogicalType::INT16}; - case LogicalTypeId::INTEGER: - return {VariantLogicalType::INT32}; - case LogicalTypeId::BIGINT: - return {VariantLogicalType::INT64}; - case LogicalTypeId::HUGEINT: - return {VariantLogicalType::INT128}; - case LogicalTypeId::UTINYINT: - return {VariantLogicalType::UINT8}; - case LogicalTypeId::USMALLINT: - return {VariantLogicalType::UINT16}; - case LogicalTypeId::UINTEGER: - return {VariantLogicalType::UINT32}; - case LogicalTypeId::UBIGINT: - return {VariantLogicalType::UINT64}; - case LogicalTypeId::UHUGEINT: - return {VariantLogicalType::UINT128}; - case LogicalTypeId::FLOAT: - return {VariantLogicalType::FLOAT}; - case LogicalTypeId::DOUBLE: - return {VariantLogicalType::DOUBLE}; - case LogicalTypeId::DECIMAL: - return {VariantLogicalType::DECIMAL}; - case LogicalTypeId::DATE: - return {VariantLogicalType::DATE}; - case LogicalTypeId::TIME: - return {VariantLogicalType::TIME_MICROS}; - case LogicalTypeId::TIME_TZ: - return {VariantLogicalType::TIME_MICROS_TZ}; - case LogicalTypeId::TIMESTAMP_TZ: - return {VariantLogicalType::TIMESTAMP_MICROS_TZ}; - case LogicalTypeId::TIMESTAMP_TZ_NS: - return {VariantLogicalType::TIMESTAMP_NANOS_TZ}; - case LogicalTypeId::TIMESTAMP: - return {VariantLogicalType::TIMESTAMP_MICROS}; - case LogicalTypeId::TIMESTAMP_SEC: - return {VariantLogicalType::TIMESTAMP_SEC}; - case LogicalTypeId::TIMESTAMP_MS: - return {VariantLogicalType::TIMESTAMP_MILIS}; - case LogicalTypeId::TIMESTAMP_NS: - return {VariantLogicalType::TIMESTAMP_NANOS}; - case LogicalTypeId::BLOB: - return {VariantLogicalType::BLOB}; - case LogicalTypeId::VARCHAR: - return {VariantLogicalType::VARCHAR}; - case LogicalTypeId::UUID: - return {VariantLogicalType::UUID}; - case LogicalTypeId::BIGNUM: - return {VariantLogicalType::BIGNUM}; - case LogicalTypeId::TIME_NS: - return {VariantLogicalType::TIME_NANOS}; - case LogicalTypeId::INTERVAL: - return {VariantLogicalType::INTERVAL}; - case LogicalTypeId::BIT: - return {VariantLogicalType::BITSTRING}; - case LogicalTypeId::GEOMETRY: - return {VariantLogicalType::GEOMETRY}; - case LogicalTypeId::GEOGRAPHY: - return {VariantLogicalType::GEOGRAPHY}; - default: + VariantLogicalType variant_type; + if (type.id() == LogicalTypeId::SQLNULL || !TryVariantTypeFromLogicalTypeId(type.id(), variant_type)) { throw BinderException("Type '%s' can't be translated to a VARIANT type", type.ToString()); } + return {type.id()}; } struct DuckDBVariantShreddingState : public VariantShreddingState { @@ -239,12 +172,12 @@ struct DuckDBVariantShreddingState : public VariantShreddingState { } public: - const unordered_set &GetVariantTypes() override { + const unordered_set &GetVariantTypes() override { return variant_types; } private: - unordered_set variant_types; + unordered_set variant_types; }; struct UnshreddedValue { diff --git a/src/duckdb/src/storage/table/variant_column_data.cpp b/src/duckdb/src/storage/table/variant_column_data.cpp index 495b15251..1def6c626 100644 --- a/src/duckdb/src/storage/table/variant_column_data.cpp +++ b/src/duckdb/src/storage/table/variant_column_data.cpp @@ -394,17 +394,17 @@ static bool ContainsWideDecimal(const VariantNode &root) { auto node = pending.back(); pending.pop_back(); switch (node.GetTypeId()) { - case VariantLogicalType::DECIMAL: + case LogicalTypeId::DECIMAL: if (Decimal::IsWide(node.GetDecimalProperties().width)) { return true; } break; - case VariantLogicalType::OBJECT: + case LogicalTypeId::STRUCT: for (auto &entry : node.GetObjectChildren()) { pending.push_back(entry.value); } break; - case VariantLogicalType::ARRAY: + case LogicalTypeId::LIST: for (auto child : node.GetArrayChildren()) { pending.push_back(child); } diff --git a/src/duckdb/ub_src_common_multi_file.cpp b/src/duckdb/ub_src_common_multi_file.cpp index 7123efe6f..450e84f75 100644 --- a/src/duckdb/ub_src_common_multi_file.cpp +++ b/src/duckdb/ub_src_common_multi_file.cpp @@ -12,5 +12,7 @@ #include "src/common/multi_file/table_function_multi_file.cpp" +#include "src/common/multi_file/table_function_multi_file_list.cpp" + #include "src/common/multi_file/union_by_name.cpp" diff --git a/src/duckdb/ub_src_execution_operator_filter.cpp b/src/duckdb/ub_src_execution_operator_filter.cpp new file mode 100644 index 000000000..1f8e086d4 --- /dev/null +++ b/src/duckdb/ub_src_execution_operator_filter.cpp @@ -0,0 +1,4 @@ +#include "src/execution/operator/filter/physical_filter.cpp" + +#include "src/execution/operator/filter/physical_top_key_filter.cpp" + diff --git a/src/duckdb/ub_src_execution_physical_plan.cpp b/src/duckdb/ub_src_execution_physical_plan.cpp index b179d1ff6..580e591f0 100644 --- a/src/duckdb/ub_src_execution_physical_plan.cpp +++ b/src/duckdb/ub_src_execution_physical_plan.cpp @@ -92,6 +92,8 @@ #include "src/execution/physical_plan/plan_set_operation.cpp" +#include "src/execution/physical_plan/plan_top_key_filter.cpp" + #include "src/execution/physical_plan/plan_top_n.cpp" #include "src/execution/physical_plan/plan_transaction.cpp" diff --git a/src/duckdb/ub_src_function_scalar_system.cpp b/src/duckdb/ub_src_function_scalar_system.cpp index 205373bf9..b46a555b1 100644 --- a/src/duckdb/ub_src_function_scalar_system.cpp +++ b/src/duckdb/ub_src_function_scalar_system.cpp @@ -6,6 +6,8 @@ #include "src/function/scalar/system/current_transaction_id.cpp" +#include "src/function/scalar/system/extension_repository_url.cpp" + #include "src/function/scalar/system/parse_log_message.cpp" #include "src/function/scalar/system/write_log.cpp" diff --git a/src/duckdb/ub_src_optimizer.cpp b/src/duckdb/ub_src_optimizer.cpp index 5a1d9f656..947ef2223 100644 --- a/src/duckdb/ub_src_optimizer.cpp +++ b/src/duckdb/ub_src_optimizer.cpp @@ -58,6 +58,8 @@ #include "src/optimizer/filter_statistics.cpp" +#include "src/optimizer/group_by_top_key.cpp" + #include "src/optimizer/grouping_sets_optimizer.cpp" #include "src/optimizer/in_clause_rewriter.cpp" diff --git a/src/duckdb/ub_src_optimizer_join_order.cpp b/src/duckdb/ub_src_optimizer_join_order.cpp index 66661b4d2..0a261fecf 100644 --- a/src/duckdb/ub_src_optimizer_join_order.cpp +++ b/src/duckdb/ub_src_optimizer_join_order.cpp @@ -12,16 +12,26 @@ #include "src/optimizer/join_order/join_order_candidate.cpp" +#include "src/optimizer/join_order/join_order_linearizer.cpp" + #include "src/optimizer/join_order/join_order_operator.cpp" #include "src/optimizer/join_order/join_order_optimizer.cpp" +#include "src/optimizer/join_order/join_order_plan.cpp" + +#include "src/optimizer/join_order/join_order_precedence.cpp" + +#include "src/optimizer/join_order/join_order_rank.cpp" + #include "src/optimizer/join_order/join_order_source_stats.cpp" #include "src/optimizer/join_order/join_predicate.cpp" #include "src/optimizer/join_order/join_relation_set.cpp" +#include "src/optimizer/join_order/linearized_plan_enumerator.cpp" + #include "src/optimizer/join_order/plan_enumerator.cpp" #include "src/optimizer/join_order/query_graph.cpp" diff --git a/src/duckdb/ub_src_planner_operator.cpp b/src/duckdb/ub_src_planner_operator.cpp index 1c1ed5170..cb5078109 100644 --- a/src/duckdb/ub_src_planner_operator.cpp +++ b/src/duckdb/ub_src_planner_operator.cpp @@ -94,6 +94,8 @@ #include "src/planner/operator/logical_set_operation.cpp" +#include "src/planner/operator/logical_top_key_filter.cpp" + #include "src/planner/operator/logical_top_n.cpp" #include "src/planner/operator/logical_transaction.cpp" diff --git a/src/jni/bindings_value.cpp b/src/jni/bindings_value.cpp index a1f570f9c..530142c5a 100644 --- a/src/jni/bindings_value.cpp +++ b/src/jni/bindings_value.cpp @@ -285,8 +285,8 @@ JNIEXPORT jobject JNICALL Java_org_duckdb_DuckDBBindings_duckdb_1get_1decimal(JN // same as in C API v1, zero is returned for non-decimal and NULL values and for the decimals // that cannot be represented duckdb_v2_hugeint_t dec_value = {0, 0}; - uint8_t dec_width = 0; - uint8_t dec_scale = 0; + uint32_t dec_width = 0; + uint32_t dec_scale = 0; if (duckdb_v2_value_get_decimal(val, &dec_value, &dec_width, &dec_scale, nullptr) != DUCKDB_V2_ERROR_NONE) { dec_value = {0, 0}; dec_scale = 0; From 7259eaeba6b08578c55db27898974d2ae9ff6ce2 Mon Sep 17 00:00:00 2001 From: Robinho-MR Date: Thu, 26 Nov 2026 14:21:51 +0000 Subject: [PATCH 6/8] Apply duckdb/duckdb#29425 to the vendored sources until the next vendoring --- .../duckdb/main/capi_v2/extension_api_v2.hpp | 3 +++ src/duckdb/src/include/duckdb_extension_v2.h | 5 ++++ src/duckdb/src/include/duckdb_v2.h | 25 +++++++++++++++++++ src/duckdb/src/main/capi/v2/capi_v2_value.cpp | 24 ++++++++++++++++++ src/duckdb/tools/cpp/duckdb_cpp.cpp | 6 +++++ src/duckdb/tools/cpp/duckdb_cpp.hpp | 7 ++++++ 6 files changed, 70 insertions(+) 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 index 23b41c389..656c519be 100644 --- a/src/duckdb/tools/cpp/duckdb_cpp.cpp +++ b/src/duckdb/tools/cpp/duckdb_cpp.cpp @@ -1832,6 +1832,12 @@ auto Value::GetChild(idx_t index) const -> Value { 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; diff --git a/src/duckdb/tools/cpp/duckdb_cpp.hpp b/src/duckdb/tools/cpp/duckdb_cpp.hpp index d496d4df8..576705cf5 100644 --- a/src/duckdb/tools/cpp/duckdb_cpp.hpp +++ b/src/duckdb/tools/cpp/duckdb_cpp.hpp @@ -2230,6 +2230,13 @@ class Value final : public detail::Handle { /// @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); From 3c766db4bf093887596bbd9b5908d8cd4a0fc360 Mon Sep 17 00:00:00 2001 From: Robinho-MR Date: Thu, 26 Nov 2026 15:09:26 +0000 Subject: [PATCH 7/8] Update the ASan failure patch for the ported appender --- data/asan/appender_asan_failure.patch | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) 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); From 698dff5e207b5bb1006ede69589750c31a83e69d Mon Sep 17 00:00:00 2001 From: Robinho-MR Date: Thu, 26 Nov 2026 15:32:56 +0000 Subject: [PATCH 8/8] Make the query of test_query_progress outlast the cancel on fast machines --- src/test/java/org/duckdb/TestDuckDBJDBC.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) 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);